1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * giochannel.c: IO Channel abstraction
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
43 #undef G_DISABLE_DEPRECATED
47 #include "giochannel.h"
56 * @short_description: portable support for using files, pipes and
58 * @see_also: <para> <variablelist> <varlistentry>
59 * <term>gtk_input_add_full(), gtk_input_remove(),
60 * gdk_input_add(), gdk_input_add_full(),
61 * gdk_input_remove()</term> <listitem><para> Convenience
62 * functions for creating #GIOChannel instances and adding
63 * them to the <link linkend="glib-The-Main-Event-Loop">main
64 * event loop</link>. </para></listitem> </varlistentry>
65 * </variablelist> </para>
67 * The #GIOChannel data type aims to provide a portable method for
68 * using file descriptors, pipes, and sockets, and integrating them
69 * into the <link linkend="glib-The-Main-Event-Loop">main event
70 * loop</link>. Currently full support is available on UNIX platforms,
71 * support for Windows is only partially complete.
73 * To create a new #GIOChannel on UNIX systems use
74 * g_io_channel_unix_new(). This works for plain file descriptors,
75 * pipes and sockets. Alternatively, a channel can be created for a
76 * file in a system independent manner using g_io_channel_new_file().
78 * Once a #GIOChannel has been created, it can be used in a generic
79 * manner with the functions g_io_channel_read_chars(),
80 * g_io_channel_write_chars(), g_io_channel_seek_position(), and
81 * g_io_channel_shutdown().
83 * To add a #GIOChannel to the <link
84 * linkend="glib-The-Main-Event-Loop">main event loop</link> use
85 * g_io_add_watch() or g_io_add_watch_full(). Here you specify which
86 * events you are interested in on the #GIOChannel, and provide a
87 * function to be called whenever these events occur.
89 * #GIOChannel instances are created with an initial reference count of
90 * 1. g_io_channel_ref() and g_io_channel_unref() can be used to
91 * increment or decrement the reference count respectively. When the
92 * reference count falls to 0, the #GIOChannel is freed. (Though it
93 * isn't closed automatically, unless it was created using
94 * g_io_channel_new_from_file().) Using g_io_add_watch() or
95 * g_io_add_watch_full() increments a channel's reference count.
97 * The new functions g_io_channel_read_chars(),
98 * g_io_channel_read_line(), g_io_channel_read_line_string(),
99 * g_io_channel_read_to_end(), g_io_channel_write_chars(),
100 * g_io_channel_seek_position(), and g_io_channel_flush() should not be
101 * mixed with the deprecated functions g_io_channel_read(),
102 * g_io_channel_write(), and g_io_channel_seek() on the same channel.
108 * A data structure representing an IO Channel. The fields should be
109 * considered private and should only be accessed with the following
115 * @io_read: reads raw bytes from the channel. This is called from
116 * various functions such as g_io_channel_read_chars() to
117 * read raw bytes from the channel. Encoding and buffering
118 * issues are dealt with at a higher level.
119 * @io_write: writes raw bytes to the channel. This is called from
120 * various functions such as g_io_channel_write_chars() to
121 * write raw bytes to the channel. Encoding and buffering
122 * issues are dealt with at a higher level.
123 * @io_seek: (optional) seeks the channel. This is called from
124 * g_io_channel_seek() on channels that support it.
125 * @io_close: closes the channel. This is called from
126 * g_io_channel_close() after flushing the buffers.
127 * @io_create_watch: creates a watch on the channel. This call
128 * corresponds directly to g_io_create_watch().
129 * @io_free: called from g_io_channel_unref() when the channel needs to
130 * be freed. This function must free the memory associated
131 * with the channel, including freeing the #GIOChannel
132 * structure itself. The channel buffers have been flushed
133 * and possibly @io_close has been called by the time this
134 * function is called.
135 * @io_set_flags: sets the #GIOFlags on the channel. This is called
136 * from g_io_channel_set_flags() with all flags except
137 * for %G_IO_FLAG_APPEND and %G_IO_FLAG_NONBLOCK masked
139 * @io_get_flags: gets the #GIOFlags for the channel. This function
140 * need only return the %G_IO_FLAG_APPEND and
141 * %G_IO_FLAG_NONBLOCK flags; g_io_channel_get_flags()
142 * automatically adds the others as appropriate.
144 * A table of functions used to handle different types of #GIOChannel
150 * @G_IO_STATUS_ERROR: An error occurred.
151 * @G_IO_STATUS_NORMAL: Success.
152 * @G_IO_STATUS_EOF: End of file.
153 * @G_IO_STATUS_AGAIN: Resource temporarily unavailable.
155 * Stati returned by most of the #GIOFuncs functions.
160 * @G_IO_ERROR_NONE: no error
161 * @G_IO_ERROR_AGAIN: an EAGAIN error occurred
162 * @G_IO_ERROR_INVAL: an EINVAL error occurred
163 * @G_IO_ERROR_UNKNOWN: another error occurred
165 * #GIOError is only used by the deprecated functions
166 * g_io_channel_read(), g_io_channel_write(), and g_io_channel_seek().
169 #define G_IO_NICE_BUF_SIZE 1024
171 /* This needs to be as wide as the largest character in any possible encoding */
172 #define MAX_CHAR_SIZE 10
174 /* Some simplifying macros, which reduce the need to worry whether the
175 * buffers have been allocated. These also make USE_BUF () an lvalue,
176 * which is used in g_io_channel_read_to_end ().
178 #define USE_BUF(channel) ((channel)->encoding ? (channel)->encoded_read_buf \
179 : (channel)->read_buf)
180 #define BUF_LEN(string) ((string) ? (string)->len : 0)
182 static GIOError g_io_error_get_from_g_error (GIOStatus status,
184 static void g_io_channel_purge (GIOChannel *channel);
185 static GIOStatus g_io_channel_fill_buffer (GIOChannel *channel,
187 static GIOStatus g_io_channel_read_line_backend (GIOChannel *channel,
189 gsize *terminator_pos,
194 * @channel: a #GIOChannel
196 * Initializes a #GIOChannel struct.
198 * This is called by each of the above functions when creating a
199 * #GIOChannel, and so is not often needed by the application
200 * programmer (unless you are creating a new type of #GIOChannel).
203 g_io_channel_init (GIOChannel *channel)
205 channel->ref_count = 1;
206 channel->encoding = g_strdup ("UTF-8");
207 channel->line_term = NULL;
208 channel->line_term_len = 0;
209 channel->buf_size = G_IO_NICE_BUF_SIZE;
210 channel->read_cd = (GIConv) -1;
211 channel->write_cd = (GIConv) -1;
212 channel->read_buf = NULL; /* Lazy allocate buffers */
213 channel->encoded_read_buf = NULL;
214 channel->write_buf = NULL;
215 channel->partial_write_buf[0] = '\0';
216 channel->use_buffer = TRUE;
217 channel->do_encode = FALSE;
218 channel->close_on_unref = FALSE;
223 * @channel: a #GIOChannel
225 * Increments the reference count of a #GIOChannel.
227 * Returns: the @channel that was passed in (since 2.6)
230 g_io_channel_ref (GIOChannel *channel)
232 g_return_val_if_fail (channel != NULL, NULL);
234 g_atomic_int_inc (&channel->ref_count);
240 * g_io_channel_unref:
241 * @channel: a #GIOChannel
243 * Decrements the reference count of a #GIOChannel.
246 g_io_channel_unref (GIOChannel *channel)
250 g_return_if_fail (channel != NULL);
252 is_zero = g_atomic_int_dec_and_test (&channel->ref_count);
254 if (G_UNLIKELY (is_zero))
256 if (channel->close_on_unref)
257 g_io_channel_shutdown (channel, TRUE, NULL);
259 g_io_channel_purge (channel);
260 g_free (channel->encoding);
261 if (channel->read_cd != (GIConv) -1)
262 g_iconv_close (channel->read_cd);
263 if (channel->write_cd != (GIConv) -1)
264 g_iconv_close (channel->write_cd);
265 g_free (channel->line_term);
266 if (channel->read_buf)
267 g_string_free (channel->read_buf, TRUE);
268 if (channel->write_buf)
269 g_string_free (channel->write_buf, TRUE);
270 if (channel->encoded_read_buf)
271 g_string_free (channel->encoded_read_buf, TRUE);
272 channel->funcs->io_free (channel);
277 g_io_error_get_from_g_error (GIOStatus status,
282 case G_IO_STATUS_NORMAL:
283 case G_IO_STATUS_EOF:
284 return G_IO_ERROR_NONE;
285 case G_IO_STATUS_AGAIN:
286 return G_IO_ERROR_AGAIN;
287 case G_IO_STATUS_ERROR:
288 g_return_val_if_fail (err != NULL, G_IO_ERROR_UNKNOWN);
290 if (err->domain != G_IO_CHANNEL_ERROR)
291 return G_IO_ERROR_UNKNOWN;
294 case G_IO_CHANNEL_ERROR_INVAL:
295 return G_IO_ERROR_INVAL;
297 return G_IO_ERROR_UNKNOWN;
300 g_assert_not_reached ();
306 * @channel: a #GIOChannel
307 * @buf: a buffer to read the data into (which should be at least
309 * @count: the number of bytes to read from the #GIOChannel
310 * @bytes_read: returns the number of bytes actually read
312 * Reads data from a #GIOChannel.
314 * Return value: %G_IO_ERROR_NONE if the operation was successful.
316 * Deprecated:2.2: Use g_io_channel_read_chars() instead.
319 g_io_channel_read (GIOChannel *channel,
328 g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
329 g_return_val_if_fail (bytes_read != NULL, G_IO_ERROR_UNKNOWN);
335 return G_IO_ERROR_NONE;
338 g_return_val_if_fail (buf != NULL, G_IO_ERROR_UNKNOWN);
340 status = channel->funcs->io_read (channel, buf, count, bytes_read, &err);
342 error = g_io_error_get_from_g_error (status, err);
351 * g_io_channel_write:
352 * @channel: a #GIOChannel
353 * @buf: the buffer containing the data to write
354 * @count: the number of bytes to write
355 * @bytes_written: the number of bytes actually written
357 * Writes data to a #GIOChannel.
359 * Return value: %G_IO_ERROR_NONE if the operation was successful.
361 * Deprecated:2.2: Use g_io_channel_write_chars() instead.
364 g_io_channel_write (GIOChannel *channel,
367 gsize *bytes_written)
373 g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
374 g_return_val_if_fail (bytes_written != NULL, G_IO_ERROR_UNKNOWN);
376 status = channel->funcs->io_write (channel, buf, count, bytes_written, &err);
378 error = g_io_error_get_from_g_error (status, err);
388 * @channel: a #GIOChannel
389 * @offset: an offset, in bytes, which is added to the position specified
391 * @type: the position in the file, which can be %G_SEEK_CUR (the current
392 * position), %G_SEEK_SET (the start of the file), or %G_SEEK_END
393 * (the end of the file)
395 * Sets the current position in the #GIOChannel, similar to the standard
396 * library function fseek().
398 * Return value: %G_IO_ERROR_NONE if the operation was successful.
400 * Deprecated:2.2: Use g_io_channel_seek_position() instead.
403 g_io_channel_seek (GIOChannel *channel,
411 g_return_val_if_fail (channel != NULL, G_IO_ERROR_UNKNOWN);
412 g_return_val_if_fail (channel->is_seekable, G_IO_ERROR_UNKNOWN);
421 g_warning ("g_io_channel_seek: unknown seek type");
422 return G_IO_ERROR_UNKNOWN;
425 status = channel->funcs->io_seek (channel, offset, type, &err);
427 error = g_io_error_get_from_g_error (status, err);
435 /* The function g_io_channel_new_file() is prototyped in both
436 * giounix.c and giowin32.c, so we stick its documentation here.
440 * g_io_channel_new_file:
441 * @filename: A string containing the name of a file
442 * @mode: One of "r", "w", "a", "r+", "w+", "a+". These have
443 * the same meaning as in fopen()
444 * @error: A location to return an error of type %G_FILE_ERROR
446 * Open a file @filename as a #GIOChannel using mode @mode. This
447 * channel will be closed when the last reference to it is dropped,
448 * so there is no need to call g_io_channel_close() (though doing
449 * so will not cause problems, as long as no attempt is made to
450 * access the channel after it is closed).
452 * Return value: A #GIOChannel on success, %NULL on failure.
456 * g_io_channel_close:
457 * @channel: A #GIOChannel
459 * Close an IO channel. Any pending data to be written will be
460 * flushed, ignoring errors. The channel will not be freed until the
461 * last reference is dropped using g_io_channel_unref().
463 * Deprecated:2.2: Use g_io_channel_shutdown() instead.
466 g_io_channel_close (GIOChannel *channel)
470 g_return_if_fail (channel != NULL);
472 g_io_channel_purge (channel);
474 channel->funcs->io_close (channel, &err);
477 { /* No way to return the error */
478 g_warning ("Error closing channel: %s", err->message);
482 channel->close_on_unref = FALSE; /* Because we already did */
483 channel->is_readable = FALSE;
484 channel->is_writeable = FALSE;
485 channel->is_seekable = FALSE;
489 * g_io_channel_shutdown:
490 * @channel: a #GIOChannel
491 * @flush: if %TRUE, flush pending
492 * @err: location to store a #GIOChannelError
494 * Close an IO channel. Any pending data to be written will be
495 * flushed if @flush is %TRUE. The channel will not be freed until the
496 * last reference is dropped using g_io_channel_unref().
498 * Return value: the status of the operation.
501 g_io_channel_shutdown (GIOChannel *channel,
505 GIOStatus status, result;
506 GError *tmperr = NULL;
508 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
509 g_return_val_if_fail (err == NULL || *err == NULL, G_IO_STATUS_ERROR);
511 if (channel->write_buf && channel->write_buf->len > 0)
517 /* Set the channel to blocking, to avoid a busy loop
519 flags = g_io_channel_get_flags (channel);
520 /* Ignore any errors here, they're irrelevant */
521 g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
523 result = g_io_channel_flush (channel, &tmperr);
526 result = G_IO_STATUS_NORMAL;
528 g_string_truncate(channel->write_buf, 0);
531 result = G_IO_STATUS_NORMAL;
533 if (channel->partial_write_buf[0] != '\0')
536 g_warning ("Partial character at end of write buffer not flushed.\n");
537 channel->partial_write_buf[0] = '\0';
540 status = channel->funcs->io_close (channel, err);
542 channel->close_on_unref = FALSE; /* Because we already did */
543 channel->is_readable = FALSE;
544 channel->is_writeable = FALSE;
545 channel->is_seekable = FALSE;
547 if (status != G_IO_STATUS_NORMAL)
549 g_clear_error (&tmperr);
552 else if (result != G_IO_STATUS_NORMAL)
554 g_propagate_error (err, tmperr);
558 return G_IO_STATUS_NORMAL;
561 /* This function is used for the final flush on close or unref */
563 g_io_channel_purge (GIOChannel *channel)
568 g_return_if_fail (channel != NULL);
570 if (channel->write_buf && channel->write_buf->len > 0)
574 /* Set the channel to blocking, to avoid a busy loop
576 flags = g_io_channel_get_flags (channel);
577 g_io_channel_set_flags (channel, flags & ~G_IO_FLAG_NONBLOCK, NULL);
579 status = g_io_channel_flush (channel, &err);
582 { /* No way to return the error */
583 g_warning ("Error flushing string: %s", err->message);
588 /* Flush these in case anyone tries to close without unrefing */
590 if (channel->read_buf)
591 g_string_truncate (channel->read_buf, 0);
592 if (channel->write_buf)
593 g_string_truncate (channel->write_buf, 0);
594 if (channel->encoding)
596 if (channel->encoded_read_buf)
597 g_string_truncate (channel->encoded_read_buf, 0);
599 if (channel->partial_write_buf[0] != '\0')
601 g_warning ("Partial character at end of write buffer not flushed.\n");
602 channel->partial_write_buf[0] = '\0';
609 * @channel: a #GIOChannel to watch
610 * @condition: conditions to watch for
612 * Creates a #GSource that's dispatched when @condition is met for the
613 * given @channel. For example, if condition is #G_IO_IN, the source will
614 * be dispatched when there's data available for reading.
616 * g_io_add_watch() is a simpler interface to this same functionality, for
617 * the case where you want to add the source to the default main loop context
618 * at the default priority.
620 * On Windows, polling a #GSource created to watch a channel for a socket
621 * puts the socket in non-blocking mode. This is a side-effect of the
622 * implementation and unavoidable.
624 * Returns: a new #GSource
627 g_io_create_watch (GIOChannel *channel,
628 GIOCondition condition)
630 g_return_val_if_fail (channel != NULL, NULL);
632 return channel->funcs->io_create_watch (channel, condition);
636 * g_io_add_watch_full:
637 * @channel: a #GIOChannel
638 * @priority: the priority of the #GIOChannel source
639 * @condition: the condition to watch for
640 * @func: the function to call when the condition is satisfied
641 * @user_data: user data to pass to @func
642 * @notify: the function to call when the source is removed
644 * Adds the #GIOChannel into the default main loop context
645 * with the given priority.
647 * This internally creates a main loop source using g_io_create_watch()
648 * and attaches it to the main loop context with g_source_attach().
649 * You can do these steps manuallt if you need greater control.
651 * Returns: the event source id
654 g_io_add_watch_full (GIOChannel *channel,
656 GIOCondition condition,
659 GDestroyNotify notify)
664 g_return_val_if_fail (channel != NULL, 0);
666 source = g_io_create_watch (channel, condition);
668 if (priority != G_PRIORITY_DEFAULT)
669 g_source_set_priority (source, priority);
670 g_source_set_callback (source, (GSourceFunc)func, user_data, notify);
672 id = g_source_attach (source, NULL);
673 g_source_unref (source);
680 * @channel: a #GIOChannel
681 * @condition: the condition to watch for
682 * @func: the function to call when the condition is satisfied
683 * @user_data: user data to pass to @func
685 * Adds the #GIOChannel into the default main loop context
686 * with the default priority.
688 * Returns: the event source id
692 * @source: the #GIOChannel event source
693 * @condition: the condition which has been satisfied
694 * @data: user data set in g_io_add_watch() or g_io_add_watch_full()
695 * @Returns: the function should return %FALSE if the event source
698 * Specifies the type of function passed to g_io_add_watch() or
699 * g_io_add_watch_full(), which is called when the requested condition
700 * on a #GIOChannel is satisfied.
704 * @G_IO_IN: There is data to read.
705 * @G_IO_OUT: Data can be written (without blocking).
706 * @G_IO_PRI: There is urgent data to read.
707 * @G_IO_ERR: Error condition.
708 * @G_IO_HUP: Hung up (the connection has been broken, usually for
709 * pipes and sockets).
710 * @G_IO_NVAL: Invalid request. The file descriptor is not open.
712 * A bitwise combination representing a condition to watch for on an
716 g_io_add_watch (GIOChannel *channel,
717 GIOCondition condition,
721 return g_io_add_watch_full (channel, G_PRIORITY_DEFAULT, condition, func, user_data, NULL);
725 * g_io_channel_get_buffer_condition:
726 * @channel: A #GIOChannel
728 * This function returns a #GIOCondition depending on whether there
729 * is data to be read/space to write data in the internal buffers in
730 * the #GIOChannel. Only the flags %G_IO_IN and %G_IO_OUT may be set.
732 * Return value: A #GIOCondition
735 g_io_channel_get_buffer_condition (GIOChannel *channel)
737 GIOCondition condition = 0;
739 if (channel->encoding)
741 if (channel->encoded_read_buf && (channel->encoded_read_buf->len > 0))
742 condition |= G_IO_IN; /* Only return if we have full characters */
746 if (channel->read_buf && (channel->read_buf->len > 0))
747 condition |= G_IO_IN;
750 if (channel->write_buf && (channel->write_buf->len < channel->buf_size))
751 condition |= G_IO_OUT;
757 * g_io_channel_error_from_errno:
758 * @en: an <literal>errno</literal> error number, e.g. %EINVAL
760 * Converts an <literal>errno</literal> error number to a #GIOChannelError.
762 * Return value: a #GIOChannelError error number, e.g.
763 * %G_IO_CHANNEL_ERROR_INVAL.
766 g_io_channel_error_from_errno (gint en)
769 g_return_val_if_fail (en != EAGAIN, G_IO_CHANNEL_ERROR_FAILED);
776 g_warning("Invalid file descriptor.\n");
777 return G_IO_CHANNEL_ERROR_FAILED;
782 g_warning("Buffer outside valid address space.\n");
783 return G_IO_CHANNEL_ERROR_FAILED;
788 return G_IO_CHANNEL_ERROR_FBIG;
792 /* In general, we should catch EINTR before we get here,
793 * but close() is allowed to return EINTR by POSIX, so
794 * we need to catch it here; EINTR from close() is
795 * unrecoverable, because it's undefined whether
796 * the fd was actually closed or not, so we just return
797 * a generic error code.
800 return G_IO_CHANNEL_ERROR_FAILED;
805 return G_IO_CHANNEL_ERROR_INVAL;
810 return G_IO_CHANNEL_ERROR_IO;
815 return G_IO_CHANNEL_ERROR_ISDIR;
820 return G_IO_CHANNEL_ERROR_NOSPC;
825 return G_IO_CHANNEL_ERROR_NXIO;
830 return G_IO_CHANNEL_ERROR_OVERFLOW;
835 return G_IO_CHANNEL_ERROR_PIPE;
839 return G_IO_CHANNEL_ERROR_FAILED;
844 * g_io_channel_set_buffer_size:
845 * @channel: a #GIOChannel
846 * @size: the size of the buffer, or 0 to let GLib pick a good size
848 * Sets the buffer size.
851 g_io_channel_set_buffer_size (GIOChannel *channel,
854 g_return_if_fail (channel != NULL);
857 size = G_IO_NICE_BUF_SIZE;
859 if (size < MAX_CHAR_SIZE)
860 size = MAX_CHAR_SIZE;
862 channel->buf_size = size;
866 * g_io_channel_get_buffer_size:
867 * @channel: a #GIOChannel
869 * Gets the buffer size.
871 * Return value: the size of the buffer.
874 g_io_channel_get_buffer_size (GIOChannel *channel)
876 g_return_val_if_fail (channel != NULL, 0);
878 return channel->buf_size;
882 * g_io_channel_set_line_term:
883 * @channel: a #GIOChannel
884 * @line_term: The line termination string. Use %NULL for autodetect.
885 * Autodetection breaks on "\n", "\r\n", "\r", "\0", and
886 * the Unicode paragraph separator. Autodetection should
887 * not be used for anything other than file-based channels.
888 * @length: The length of the termination string. If -1 is passed, the
889 * string is assumed to be nul-terminated. This option allows
890 * termination strings with embedded nuls.
892 * This sets the string that #GIOChannel uses to determine
893 * where in the file a line break occurs.
896 g_io_channel_set_line_term (GIOChannel *channel,
897 const gchar *line_term,
900 g_return_if_fail (channel != NULL);
901 g_return_if_fail (line_term == NULL || length != 0); /* Disallow "" */
903 if (line_term == NULL)
906 length = strlen (line_term);
908 g_free (channel->line_term);
909 channel->line_term = line_term ? g_memdup (line_term, length) : NULL;
910 channel->line_term_len = length;
914 * g_io_channel_get_line_term:
915 * @channel: a #GIOChannel
916 * @length: a location to return the length of the line terminator
918 * This returns the string that #GIOChannel uses to determine
919 * where in the file a line break occurs. A value of %NULL
920 * indicates autodetection.
922 * Return value: The line termination string. This value
923 * is owned by GLib and must not be freed.
925 G_CONST_RETURN gchar*
926 g_io_channel_get_line_term (GIOChannel *channel,
929 g_return_val_if_fail (channel != NULL, NULL);
932 *length = channel->line_term_len;
934 return channel->line_term;
938 * g_io_channel_set_flags:
939 * @channel: a #GIOChannel
940 * @flags: the flags to set on the IO channel
941 * @error: A location to return an error of type #GIOChannelError
943 * Sets the (writeable) flags in @channel to (@flags & %G_IO_CHANNEL_SET_MASK).
945 * Return value: the status of the operation.
949 * @G_IO_FLAG_APPEND: turns on append mode, corresponds to %O_APPEND
950 * (see the documentation of the UNIX open()
952 * @G_IO_FLAG_NONBLOCK: turns on nonblocking mode, corresponds to
953 * %O_NONBLOCK/%O_NDELAY (see the documentation of
954 * the UNIX open() syscall).
955 * @G_IO_FLAG_IS_READABLE: indicates that the io channel is readable.
956 * This flag can not be changed.
957 * @G_IO_FLAG_IS_WRITEABLE: indicates that the io channel is writable.
958 * This flag can not be changed.
959 * @G_IO_FLAG_IS_SEEKABLE: indicates that the io channel is seekable,
960 * i.e. that g_io_channel_seek_position() can
961 * be used on it. This flag can not be changed.
962 * @G_IO_FLAG_MASK: the mask that specifies all the valid flags.
963 * @G_IO_FLAG_GET_MASK: the mask of the flags that are returned from
964 * g_io_channel_get_flags().
965 * @G_IO_FLAG_SET_MASK: the mask of the flags that the user can modify
966 * with g_io_channel_set_flags().
968 * Specifies properties of a #GIOChannel. Some of the flags can only be
969 * read with g_io_channel_get_flags(), but not changed with
970 * g_io_channel_set_flags().
973 g_io_channel_set_flags (GIOChannel *channel,
977 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
978 g_return_val_if_fail ((error == NULL) || (*error == NULL),
981 return (*channel->funcs->io_set_flags) (channel,
982 flags & G_IO_FLAG_SET_MASK,
987 * g_io_channel_get_flags:
988 * @channel: a #GIOChannel
990 * Gets the current flags for a #GIOChannel, including read-only
991 * flags such as %G_IO_FLAG_IS_READABLE.
993 * The values of the flags %G_IO_FLAG_IS_READABLE and %G_IO_FLAG_IS_WRITEABLE
994 * are cached for internal use by the channel when it is created.
995 * If they should change at some later point (e.g. partial shutdown
996 * of a socket with the UNIX shutdown() function), the user
997 * should immediately call g_io_channel_get_flags() to update
998 * the internal values of these flags.
1000 * Return value: the flags which are set on the channel
1003 g_io_channel_get_flags (GIOChannel *channel)
1007 g_return_val_if_fail (channel != NULL, 0);
1009 flags = (* channel->funcs->io_get_flags) (channel);
1011 /* Cross implementation code */
1013 if (channel->is_seekable)
1014 flags |= G_IO_FLAG_IS_SEEKABLE;
1015 if (channel->is_readable)
1016 flags |= G_IO_FLAG_IS_READABLE;
1017 if (channel->is_writeable)
1018 flags |= G_IO_FLAG_IS_WRITEABLE;
1024 * g_io_channel_set_close_on_unref:
1025 * @channel: a #GIOChannel
1026 * @do_close: Whether to close the channel on the final unref of
1027 * the GIOChannel data structure. The default value of
1028 * this is %TRUE for channels created by g_io_channel_new_file (),
1029 * and %FALSE for all other channels.
1031 * Setting this flag to %TRUE for a channel you have already closed
1032 * can cause problems.
1035 g_io_channel_set_close_on_unref (GIOChannel *channel,
1038 g_return_if_fail (channel != NULL);
1040 channel->close_on_unref = do_close;
1044 * g_io_channel_get_close_on_unref:
1045 * @channel: a #GIOChannel.
1047 * Returns whether the file/socket/whatever associated with @channel
1048 * will be closed when @channel receives its final unref and is
1049 * destroyed. The default value of this is %TRUE for channels created
1050 * by g_io_channel_new_file (), and %FALSE for all other channels.
1052 * Return value: Whether the channel will be closed on the final unref of
1053 * the GIOChannel data structure.
1056 g_io_channel_get_close_on_unref (GIOChannel *channel)
1058 g_return_val_if_fail (channel != NULL, FALSE);
1060 return channel->close_on_unref;
1064 * g_io_channel_seek_position:
1065 * @channel: a #GIOChannel
1066 * @offset: The offset in bytes from the position specified by @type
1067 * @type: a #GSeekType. The type %G_SEEK_CUR is only allowed in those
1068 * cases where a call to g_io_channel_set_encoding ()
1069 * is allowed. See the documentation for
1070 * g_io_channel_set_encoding () for details.
1071 * @error: A location to return an error of type #GIOChannelError
1073 * Replacement for g_io_channel_seek() with the new API.
1075 * Return value: the status of the operation.
1079 * @G_SEEK_CUR: the current position in the file.
1080 * @G_SEEK_SET: the start of the file.
1081 * @G_SEEK_END: the end of the file.
1083 * An enumeration specifying the base position for a
1084 * g_io_channel_seek_position() operation.
1087 g_io_channel_seek_position (GIOChannel *channel,
1094 /* For files, only one of the read and write buffers can contain data.
1095 * For sockets, both can contain data.
1098 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1099 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1101 g_return_val_if_fail (channel->is_seekable, G_IO_STATUS_ERROR);
1105 case G_SEEK_CUR: /* The user is seeking relative to the head of the buffer */
1106 if (channel->use_buffer)
1108 if (channel->do_encode && channel->encoded_read_buf
1109 && channel->encoded_read_buf->len > 0)
1111 g_warning ("Seek type G_SEEK_CUR not allowed for this"
1112 " channel's encoding.\n");
1113 return G_IO_STATUS_ERROR;
1115 if (channel->read_buf)
1116 offset -= channel->read_buf->len;
1117 if (channel->encoded_read_buf)
1119 g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
1121 /* If there's anything here, it's because the encoding is UTF-8,
1122 * so we can just subtract the buffer length, the same as for
1123 * the unencoded data.
1126 offset -= channel->encoded_read_buf->len;
1134 g_warning ("g_io_channel_seek_position: unknown seek type");
1135 return G_IO_STATUS_ERROR;
1138 if (channel->use_buffer)
1140 status = g_io_channel_flush (channel, error);
1141 if (status != G_IO_STATUS_NORMAL)
1145 status = channel->funcs->io_seek (channel, offset, type, error);
1147 if ((status == G_IO_STATUS_NORMAL) && (channel->use_buffer))
1149 if (channel->read_buf)
1150 g_string_truncate (channel->read_buf, 0);
1152 /* Conversion state no longer matches position in file */
1153 if (channel->read_cd != (GIConv) -1)
1154 g_iconv (channel->read_cd, NULL, NULL, NULL, NULL);
1155 if (channel->write_cd != (GIConv) -1)
1156 g_iconv (channel->write_cd, NULL, NULL, NULL, NULL);
1158 if (channel->encoded_read_buf)
1160 g_assert (channel->encoded_read_buf->len == 0 || !channel->do_encode);
1161 g_string_truncate (channel->encoded_read_buf, 0);
1164 if (channel->partial_write_buf[0] != '\0')
1166 g_warning ("Partial character at end of write buffer not flushed.\n");
1167 channel->partial_write_buf[0] = '\0';
1175 * g_io_channel_flush:
1176 * @channel: a #GIOChannel
1177 * @error: location to store an error of type #GIOChannelError
1179 * Flushes the write buffer for the GIOChannel.
1181 * Return value: the status of the operation: One of
1182 * #G_IO_STATUS_NORMAL, #G_IO_STATUS_AGAIN, or
1183 * #G_IO_STATUS_ERROR.
1186 g_io_channel_flush (GIOChannel *channel,
1190 gsize this_time = 1, bytes_written = 0;
1192 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1193 g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
1195 if (channel->write_buf == NULL || channel->write_buf->len == 0)
1196 return G_IO_STATUS_NORMAL;
1200 g_assert (this_time > 0);
1202 status = channel->funcs->io_write (channel,
1203 channel->write_buf->str + bytes_written,
1204 channel->write_buf->len - bytes_written,
1206 bytes_written += this_time;
1208 while ((bytes_written < channel->write_buf->len)
1209 && (status == G_IO_STATUS_NORMAL));
1211 g_string_erase (channel->write_buf, 0, bytes_written);
1217 * g_io_channel_set_buffered:
1218 * @channel: a #GIOChannel
1219 * @buffered: whether to set the channel buffered or unbuffered
1221 * The buffering state can only be set if the channel's encoding
1222 * is %NULL. For any other encoding, the channel must be buffered.
1224 * A buffered channel can only be set unbuffered if the channel's
1225 * internal buffers have been flushed. Newly created channels or
1226 * channels which have returned %G_IO_STATUS_EOF
1227 * not require such a flush. For write-only channels, a call to
1228 * g_io_channel_flush () is sufficient. For all other channels,
1229 * the buffers may be flushed by a call to g_io_channel_seek_position ().
1230 * This includes the possibility of seeking with seek type %G_SEEK_CUR
1231 * and an offset of zero. Note that this means that socket-based
1232 * channels cannot be set unbuffered once they have had data
1235 * On unbuffered channels, it is safe to mix read and write
1236 * calls from the new and old APIs, if this is necessary for
1237 * maintaining old code.
1239 * The default state of the channel is buffered.
1242 g_io_channel_set_buffered (GIOChannel *channel,
1245 g_return_if_fail (channel != NULL);
1247 if (channel->encoding != NULL)
1249 g_warning ("Need to have NULL encoding to set the buffering state of the "
1254 g_return_if_fail (!channel->read_buf || channel->read_buf->len == 0);
1255 g_return_if_fail (!channel->write_buf || channel->write_buf->len == 0);
1257 channel->use_buffer = buffered;
1261 * g_io_channel_get_buffered:
1262 * @channel: a #GIOChannel
1264 * Returns whether @channel is buffered.
1266 * Return Value: %TRUE if the @channel is buffered.
1269 g_io_channel_get_buffered (GIOChannel *channel)
1271 g_return_val_if_fail (channel != NULL, FALSE);
1273 return channel->use_buffer;
1277 * g_io_channel_set_encoding:
1278 * @channel: a #GIOChannel
1279 * @encoding: the encoding type
1280 * @error: location to store an error of type #GConvertError
1282 * Sets the encoding for the input/output of the channel.
1283 * The internal encoding is always UTF-8. The default encoding
1284 * for the external file is UTF-8.
1286 * The encoding %NULL is safe to use with binary data.
1288 * The encoding can only be set if one of the following conditions
1292 * The channel was just created, and has not been written to or read
1294 * </para></listitem>
1296 * The channel is write-only.
1297 * </para></listitem>
1299 * The channel is a file, and the file pointer was just
1300 * repositioned by a call to g_io_channel_seek_position().
1301 * (This flushes all the internal buffers.)
1302 * </para></listitem>
1304 * The current encoding is %NULL or UTF-8.
1305 * </para></listitem>
1307 * One of the (new API) read functions has just returned %G_IO_STATUS_EOF
1308 * (or, in the case of g_io_channel_read_to_end(), %G_IO_STATUS_NORMAL).
1309 * </para></listitem>
1311 * One of the functions g_io_channel_read_chars() or
1312 * g_io_channel_read_unichar() has returned %G_IO_STATUS_AGAIN or
1313 * %G_IO_STATUS_ERROR. This may be useful in the case of
1314 * %G_CONVERT_ERROR_ILLEGAL_SEQUENCE.
1315 * Returning one of these statuses from g_io_channel_read_line(),
1316 * g_io_channel_read_line_string(), or g_io_channel_read_to_end()
1317 * does <emphasis>not</emphasis> guarantee that the encoding can
1319 * </para></listitem>
1321 * Channels which do not meet one of the above conditions cannot call
1322 * g_io_channel_seek_position() with an offset of %G_SEEK_CUR, and, if
1323 * they are "seekable", cannot call g_io_channel_write_chars() after
1324 * calling one of the API "read" functions.
1326 * Return Value: %G_IO_STATUS_NORMAL if the encoding was successfully set.
1329 g_io_channel_set_encoding (GIOChannel *channel,
1330 const gchar *encoding,
1333 GIConv read_cd, write_cd;
1334 gboolean did_encode;
1336 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1337 g_return_val_if_fail ((error == NULL) || (*error == NULL), G_IO_STATUS_ERROR);
1339 /* Make sure the encoded buffers are empty */
1341 g_return_val_if_fail (!channel->do_encode || !channel->encoded_read_buf ||
1342 channel->encoded_read_buf->len == 0, G_IO_STATUS_ERROR);
1344 if (!channel->use_buffer)
1346 g_warning ("Need to set the channel buffered before setting the encoding.\n");
1347 g_warning ("Assuming this is what you meant and acting accordingly.\n");
1349 channel->use_buffer = TRUE;
1352 if (channel->partial_write_buf[0] != '\0')
1354 g_warning ("Partial character at end of write buffer not flushed.\n");
1355 channel->partial_write_buf[0] = '\0';
1358 did_encode = channel->do_encode;
1360 if (!encoding || strcmp (encoding, "UTF8") == 0 || strcmp (encoding, "UTF-8") == 0)
1362 channel->do_encode = FALSE;
1363 read_cd = write_cd = (GIConv) -1;
1368 const gchar *from_enc = NULL, *to_enc = NULL;
1370 if (channel->is_readable)
1372 read_cd = g_iconv_open ("UTF-8", encoding);
1374 if (read_cd == (GIConv) -1)
1377 from_enc = encoding;
1382 read_cd = (GIConv) -1;
1384 if (channel->is_writeable && err == 0)
1386 write_cd = g_iconv_open (encoding, "UTF-8");
1388 if (write_cd == (GIConv) -1)
1396 write_cd = (GIConv) -1;
1400 g_assert (from_enc);
1404 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
1405 _("Conversion from character set '%s' to '%s' is not supported"),
1408 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1409 _("Could not open converter from '%s' to '%s': %s"),
1410 from_enc, to_enc, g_strerror (err));
1412 if (read_cd != (GIConv) -1)
1413 g_iconv_close (read_cd);
1414 if (write_cd != (GIConv) -1)
1415 g_iconv_close (write_cd);
1417 return G_IO_STATUS_ERROR;
1420 channel->do_encode = TRUE;
1423 /* The encoding is ok, so set the fields in channel */
1425 if (channel->read_cd != (GIConv) -1)
1426 g_iconv_close (channel->read_cd);
1427 if (channel->write_cd != (GIConv) -1)
1428 g_iconv_close (channel->write_cd);
1430 if (channel->encoded_read_buf && channel->encoded_read_buf->len > 0)
1432 g_assert (!did_encode); /* Encoding UTF-8, NULL doesn't use encoded_read_buf */
1434 /* This is just validated UTF-8, so we can copy it back into read_buf
1435 * so it can be encoded in whatever the new encoding is.
1438 g_string_prepend_len (channel->read_buf, channel->encoded_read_buf->str,
1439 channel->encoded_read_buf->len);
1440 g_string_truncate (channel->encoded_read_buf, 0);
1443 channel->read_cd = read_cd;
1444 channel->write_cd = write_cd;
1446 g_free (channel->encoding);
1447 channel->encoding = g_strdup (encoding);
1449 return G_IO_STATUS_NORMAL;
1453 * g_io_channel_get_encoding:
1454 * @channel: a #GIOChannel
1456 * Gets the encoding for the input/output of the channel.
1457 * The internal encoding is always UTF-8. The encoding %NULL
1458 * makes the channel safe for binary data.
1460 * Return value: A string containing the encoding, this string is
1461 * owned by GLib and must not be freed.
1463 G_CONST_RETURN gchar*
1464 g_io_channel_get_encoding (GIOChannel *channel)
1466 g_return_val_if_fail (channel != NULL, NULL);
1468 return channel->encoding;
1472 g_io_channel_fill_buffer (GIOChannel *channel,
1475 gsize read_size, cur_len, oldlen;
1478 if (channel->is_seekable && channel->write_buf && channel->write_buf->len > 0)
1480 status = g_io_channel_flush (channel, err);
1481 if (status != G_IO_STATUS_NORMAL)
1484 if (channel->is_seekable && channel->partial_write_buf[0] != '\0')
1486 g_warning ("Partial character at end of write buffer not flushed.\n");
1487 channel->partial_write_buf[0] = '\0';
1490 if (!channel->read_buf)
1491 channel->read_buf = g_string_sized_new (channel->buf_size);
1493 cur_len = channel->read_buf->len;
1495 g_string_set_size (channel->read_buf, channel->read_buf->len + channel->buf_size);
1497 status = channel->funcs->io_read (channel, channel->read_buf->str + cur_len,
1498 channel->buf_size, &read_size, err);
1500 g_assert ((status == G_IO_STATUS_NORMAL) || (read_size == 0));
1502 g_string_truncate (channel->read_buf, read_size + cur_len);
1504 if ((status != G_IO_STATUS_NORMAL) &&
1505 ((status != G_IO_STATUS_EOF) || (channel->read_buf->len == 0)))
1508 g_assert (channel->read_buf->len > 0);
1510 if (channel->encoded_read_buf)
1511 oldlen = channel->encoded_read_buf->len;
1515 if (channel->encoding)
1516 channel->encoded_read_buf = g_string_sized_new (channel->buf_size);
1519 if (channel->do_encode)
1521 gsize errnum, inbytes_left, outbytes_left;
1522 gchar *inbuf, *outbuf;
1525 g_assert (channel->encoded_read_buf);
1529 inbytes_left = channel->read_buf->len;
1530 outbytes_left = MAX (channel->read_buf->len,
1531 channel->encoded_read_buf->allocated_len
1532 - channel->encoded_read_buf->len - 1); /* 1 for NULL */
1533 outbytes_left = MAX (outbytes_left, 6);
1535 inbuf = channel->read_buf->str;
1536 g_string_set_size (channel->encoded_read_buf,
1537 channel->encoded_read_buf->len + outbytes_left);
1538 outbuf = channel->encoded_read_buf->str + channel->encoded_read_buf->len
1541 errnum = g_iconv (channel->read_cd, &inbuf, &inbytes_left,
1542 &outbuf, &outbytes_left);
1545 g_assert (inbuf + inbytes_left == channel->read_buf->str
1546 + channel->read_buf->len);
1547 g_assert (outbuf + outbytes_left == channel->encoded_read_buf->str
1548 + channel->encoded_read_buf->len);
1550 g_string_erase (channel->read_buf, 0,
1551 channel->read_buf->len - inbytes_left);
1552 g_string_truncate (channel->encoded_read_buf,
1553 channel->encoded_read_buf->len - outbytes_left);
1555 if (errnum == (gsize) -1)
1560 if ((oldlen == channel->encoded_read_buf->len)
1561 && (status == G_IO_STATUS_EOF))
1562 status = G_IO_STATUS_EOF;
1564 status = G_IO_STATUS_NORMAL;
1567 /* Buffer size at least 6, wrote at least on character */
1568 g_assert (inbuf != channel->read_buf->str);
1571 if (oldlen < channel->encoded_read_buf->len)
1572 status = G_IO_STATUS_NORMAL;
1575 g_set_error_literal (err, G_CONVERT_ERROR,
1576 G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1577 _("Invalid byte sequence in conversion input"));
1578 return G_IO_STATUS_ERROR;
1582 g_assert (errval != EBADF); /* The converter should be open */
1583 g_set_error (err, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1584 _("Error during conversion: %s"), g_strerror (errval));
1585 return G_IO_STATUS_ERROR;
1588 g_assert ((status != G_IO_STATUS_NORMAL)
1589 || (channel->encoded_read_buf->len > 0));
1591 else if (channel->encoding) /* UTF-8 */
1593 gchar *nextchar, *lastchar;
1595 g_assert (channel->encoded_read_buf);
1597 nextchar = channel->read_buf->str;
1598 lastchar = channel->read_buf->str + channel->read_buf->len;
1600 while (nextchar < lastchar)
1604 val_char = g_utf8_get_char_validated (nextchar, lastchar - nextchar);
1609 /* stop, leave partial character in buffer */
1610 lastchar = nextchar;
1613 if (oldlen < channel->encoded_read_buf->len)
1614 status = G_IO_STATUS_NORMAL;
1617 g_set_error_literal (err, G_CONVERT_ERROR,
1618 G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1619 _("Invalid byte sequence in conversion input"));
1620 status = G_IO_STATUS_ERROR;
1622 lastchar = nextchar;
1625 nextchar = g_utf8_next_char (nextchar);
1630 if (lastchar > channel->read_buf->str)
1632 gint copy_len = lastchar - channel->read_buf->str;
1634 g_string_append_len (channel->encoded_read_buf, channel->read_buf->str,
1636 g_string_erase (channel->read_buf, 0, copy_len);
1644 * g_io_channel_read_line:
1645 * @channel: a #GIOChannel
1646 * @str_return: The line read from the #GIOChannel, including the
1647 * line terminator. This data should be freed with g_free()
1648 * when no longer needed. This is a nul-terminated string.
1649 * If a @length of zero is returned, this will be %NULL instead.
1650 * @length: location to store length of the read data, or %NULL
1651 * @terminator_pos: location to store position of line terminator, or %NULL
1652 * @error: A location to return an error of type #GConvertError
1653 * or #GIOChannelError
1655 * Reads a line, including the terminating character(s),
1656 * from a #GIOChannel into a newly-allocated string.
1657 * @str_return will contain allocated memory if the return
1658 * is %G_IO_STATUS_NORMAL.
1660 * Return value: the status of the operation.
1663 g_io_channel_read_line (GIOChannel *channel,
1666 gsize *terminator_pos,
1672 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1673 g_return_val_if_fail (str_return != NULL, G_IO_STATUS_ERROR);
1674 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1676 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1678 status = g_io_channel_read_line_backend (channel, &got_length, terminator_pos, error);
1681 *length = got_length;
1683 if (status == G_IO_STATUS_NORMAL)
1685 g_assert (USE_BUF (channel));
1686 *str_return = g_strndup (USE_BUF (channel)->str, got_length);
1687 g_string_erase (USE_BUF (channel), 0, got_length);
1696 * g_io_channel_read_line_string:
1697 * @channel: a #GIOChannel
1698 * @buffer: a #GString into which the line will be written.
1699 * If @buffer already contains data, the old data will
1701 * @terminator_pos: location to store position of line terminator, or %NULL
1702 * @error: a location to store an error of type #GConvertError
1703 * or #GIOChannelError
1705 * Reads a line from a #GIOChannel, using a #GString as a buffer.
1707 * Return value: the status of the operation.
1710 g_io_channel_read_line_string (GIOChannel *channel,
1712 gsize *terminator_pos,
1718 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1719 g_return_val_if_fail (buffer != NULL, G_IO_STATUS_ERROR);
1720 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1722 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1724 if (buffer->len > 0)
1725 g_string_truncate (buffer, 0); /* clear out the buffer */
1727 status = g_io_channel_read_line_backend (channel, &length, terminator_pos, error);
1729 if (status == G_IO_STATUS_NORMAL)
1731 g_assert (USE_BUF (channel));
1732 g_string_append_len (buffer, USE_BUF (channel)->str, length);
1733 g_string_erase (USE_BUF (channel), 0, length);
1741 g_io_channel_read_line_backend (GIOChannel *channel,
1743 gsize *terminator_pos,
1747 gsize checked_to, line_term_len, line_length, got_term_len;
1748 gboolean first_time = TRUE;
1750 if (!channel->use_buffer)
1752 /* Can't do a raw read in read_line */
1753 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1754 _("Can't do a raw read in g_io_channel_read_line_string"));
1755 return G_IO_STATUS_ERROR;
1758 status = G_IO_STATUS_NORMAL;
1760 if (channel->line_term)
1761 line_term_len = channel->line_term_len;
1764 /* This value used for setting checked_to, it's the longest of the four
1765 * we autodetect for.
1772 gchar *nextchar, *lastchar;
1775 if (!first_time || (BUF_LEN (USE_BUF (channel)) == 0))
1778 status = g_io_channel_fill_buffer (channel, error);
1781 case G_IO_STATUS_NORMAL:
1782 if (BUF_LEN (USE_BUF (channel)) == 0)
1783 /* Can happen when using conversion and only read
1784 * part of a character
1791 case G_IO_STATUS_EOF:
1792 if (BUF_LEN (USE_BUF (channel)) == 0)
1797 if (channel->encoding && channel->read_buf->len != 0)
1799 g_set_error_literal (error, G_CONVERT_ERROR,
1800 G_CONVERT_ERROR_PARTIAL_INPUT,
1801 _("Leftover unconverted data in "
1803 return G_IO_STATUS_ERROR;
1806 return G_IO_STATUS_EOF;
1816 g_assert (BUF_LEN (USE_BUF (channel)) != 0);
1818 use_buf = USE_BUF (channel); /* The buffer has been created by this point */
1822 lastchar = use_buf->str + use_buf->len;
1824 for (nextchar = use_buf->str + checked_to; nextchar < lastchar;
1825 channel->encoding ? nextchar = g_utf8_next_char (nextchar) : nextchar++)
1827 if (channel->line_term)
1829 if (memcmp (channel->line_term, nextchar, line_term_len) == 0)
1831 line_length = nextchar - use_buf->str;
1832 got_term_len = line_term_len;
1836 else /* auto detect */
1840 case '\n': /* unix */
1841 line_length = nextchar - use_buf->str;
1844 case '\r': /* Warning: do not use with sockets */
1845 line_length = nextchar - use_buf->str;
1846 if ((nextchar == lastchar - 1) && (status != G_IO_STATUS_EOF)
1847 && (lastchar == use_buf->str + use_buf->len))
1848 goto read_again; /* Try to read more data */
1849 if ((nextchar < lastchar - 1) && (*(nextchar + 1) == '\n')) /* dos */
1854 case '\xe2': /* Unicode paragraph separator */
1855 if (strncmp ("\xe2\x80\xa9", nextchar, 3) == 0)
1857 line_length = nextchar - use_buf->str;
1862 case '\0': /* Embeded null in input */
1863 line_length = nextchar - use_buf->str;
1866 default: /* no match */
1872 /* If encoding != NULL, valid UTF-8, didn't overshoot */
1873 g_assert (nextchar == lastchar);
1877 if (status == G_IO_STATUS_EOF)
1879 if (channel->encoding && channel->read_buf->len > 0)
1881 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1882 _("Channel terminates in a partial character"));
1883 return G_IO_STATUS_ERROR;
1885 line_length = use_buf->len;
1890 if (use_buf->len > line_term_len - 1)
1891 checked_to = use_buf->len - (line_term_len - 1);
1899 *terminator_pos = line_length;
1902 *length = line_length + got_term_len;
1904 return G_IO_STATUS_NORMAL;
1908 * g_io_channel_read_to_end:
1909 * @channel: a #GIOChannel
1910 * @str_return: Location to store a pointer to a string holding
1911 * the remaining data in the #GIOChannel. This data should
1912 * be freed with g_free() when no longer needed. This
1913 * data is terminated by an extra nul character, but there
1914 * may be other nuls in the intervening data.
1915 * @length: location to store length of the data
1916 * @error: location to return an error of type #GConvertError
1917 * or #GIOChannelError
1919 * Reads all the remaining data from the file.
1921 * Return value: %G_IO_STATUS_NORMAL on success.
1922 * This function never returns %G_IO_STATUS_EOF.
1925 g_io_channel_read_to_end (GIOChannel *channel,
1932 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
1933 g_return_val_if_fail ((error == NULL) || (*error == NULL),
1935 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
1942 if (!channel->use_buffer)
1944 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1945 _("Can't do a raw read in g_io_channel_read_to_end"));
1946 return G_IO_STATUS_ERROR;
1950 status = g_io_channel_fill_buffer (channel, error);
1951 while (status == G_IO_STATUS_NORMAL);
1953 if (status != G_IO_STATUS_EOF)
1956 if (channel->encoding && channel->read_buf->len > 0)
1958 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1959 _("Channel terminates in a partial character"));
1960 return G_IO_STATUS_ERROR;
1963 if (USE_BUF (channel) == NULL)
1965 /* length is already set to zero */
1967 *str_return = g_strdup ("");
1972 *length = USE_BUF (channel)->len;
1975 *str_return = g_string_free (USE_BUF (channel), FALSE);
1977 g_string_free (USE_BUF (channel), TRUE);
1979 if (channel->encoding)
1980 channel->encoded_read_buf = NULL;
1982 channel->read_buf = NULL;
1985 return G_IO_STATUS_NORMAL;
1989 * g_io_channel_read_chars:
1990 * @channel: a #GIOChannel
1991 * @buf: a buffer to read data into
1992 * @count: the size of the buffer. Note that the buffer may
1993 * not be complelely filled even if there is data
1994 * in the buffer if the remaining data is not a
1995 * complete character.
1996 * @bytes_read: The number of bytes read. This may be zero even on
1997 * success if count < 6 and the channel's encoding is non-%NULL.
1998 * This indicates that the next UTF-8 character is too wide for
2000 * @error: a location to return an error of type #GConvertError
2001 * or #GIOChannelError.
2003 * Replacement for g_io_channel_read() with the new API.
2005 * Return value: the status of the operation.
2008 g_io_channel_read_chars (GIOChannel *channel,
2017 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2018 g_return_val_if_fail ((error == NULL) || (*error == NULL),
2020 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
2025 return G_IO_STATUS_NORMAL;
2027 g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
2029 if (!channel->use_buffer)
2033 g_assert (!channel->read_buf || channel->read_buf->len == 0);
2035 status = channel->funcs->io_read (channel, buf, count, &tmp_bytes, error);
2038 *bytes_read = tmp_bytes;
2043 status = G_IO_STATUS_NORMAL;
2045 while (BUF_LEN (USE_BUF (channel)) < count && status == G_IO_STATUS_NORMAL)
2046 status = g_io_channel_fill_buffer (channel, error);
2048 /* Only return an error if we have no data */
2050 if (BUF_LEN (USE_BUF (channel)) == 0)
2052 g_assert (status != G_IO_STATUS_NORMAL);
2054 if (status == G_IO_STATUS_EOF && channel->encoding
2055 && BUF_LEN (channel->read_buf) > 0)
2057 g_set_error_literal (error, G_CONVERT_ERROR,
2058 G_CONVERT_ERROR_PARTIAL_INPUT,
2059 _("Leftover unconverted data in read buffer"));
2060 status = G_IO_STATUS_ERROR;
2069 if (status == G_IO_STATUS_ERROR)
2070 g_clear_error (error);
2072 got_bytes = MIN (count, BUF_LEN (USE_BUF (channel)));
2074 g_assert (got_bytes > 0);
2076 if (channel->encoding)
2077 /* Don't validate for NULL encoding, binary safe */
2079 gchar *nextchar, *prevchar;
2081 g_assert (USE_BUF (channel) == channel->encoded_read_buf);
2083 nextchar = channel->encoded_read_buf->str;
2087 prevchar = nextchar;
2088 nextchar = g_utf8_next_char (nextchar);
2089 g_assert (nextchar != prevchar); /* Possible for *prevchar of -1 or -2 */
2091 while (nextchar < channel->encoded_read_buf->str + got_bytes);
2093 if (nextchar > channel->encoded_read_buf->str + got_bytes)
2094 got_bytes = prevchar - channel->encoded_read_buf->str;
2096 g_assert (got_bytes > 0 || count < 6);
2099 memcpy (buf, USE_BUF (channel)->str, got_bytes);
2100 g_string_erase (USE_BUF (channel), 0, got_bytes);
2103 *bytes_read = got_bytes;
2105 return G_IO_STATUS_NORMAL;
2109 * g_io_channel_read_unichar:
2110 * @channel: a #GIOChannel
2111 * @thechar: a location to return a character
2112 * @error: a location to return an error of type #GConvertError
2113 * or #GIOChannelError
2115 * Reads a Unicode character from @channel.
2116 * This function cannot be called on a channel with %NULL encoding.
2118 * Return value: a #GIOStatus
2121 g_io_channel_read_unichar (GIOChannel *channel,
2125 GIOStatus status = G_IO_STATUS_NORMAL;
2127 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2128 g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
2129 g_return_val_if_fail ((error == NULL) || (*error == NULL),
2131 g_return_val_if_fail (channel->is_readable, G_IO_STATUS_ERROR);
2133 while (BUF_LEN (channel->encoded_read_buf) == 0 && status == G_IO_STATUS_NORMAL)
2134 status = g_io_channel_fill_buffer (channel, error);
2136 /* Only return an error if we have no data */
2138 if (BUF_LEN (USE_BUF (channel)) == 0)
2140 g_assert (status != G_IO_STATUS_NORMAL);
2142 if (status == G_IO_STATUS_EOF && BUF_LEN (channel->read_buf) > 0)
2144 g_set_error_literal (error, G_CONVERT_ERROR,
2145 G_CONVERT_ERROR_PARTIAL_INPUT,
2146 _("Leftover unconverted data in read buffer"));
2147 status = G_IO_STATUS_ERROR;
2151 *thechar = (gunichar) -1;
2156 if (status == G_IO_STATUS_ERROR)
2157 g_clear_error (error);
2160 *thechar = g_utf8_get_char (channel->encoded_read_buf->str);
2162 g_string_erase (channel->encoded_read_buf, 0,
2163 g_utf8_next_char (channel->encoded_read_buf->str)
2164 - channel->encoded_read_buf->str);
2166 return G_IO_STATUS_NORMAL;
2170 * g_io_channel_write_chars:
2171 * @channel: a #GIOChannel
2172 * @buf: a buffer to write data from
2173 * @count: the size of the buffer. If -1, the buffer
2174 * is taken to be a nul-terminated string.
2175 * @bytes_written: The number of bytes written. This can be nonzero
2176 * even if the return value is not %G_IO_STATUS_NORMAL.
2177 * If the return value is %G_IO_STATUS_NORMAL and the
2178 * channel is blocking, this will always be equal
2179 * to @count if @count >= 0.
2180 * @error: a location to return an error of type #GConvertError
2181 * or #GIOChannelError
2183 * Replacement for g_io_channel_write() with the new API.
2185 * On seekable channels with encodings other than %NULL or UTF-8, generic
2186 * mixing of reading and writing is not allowed. A call to g_io_channel_write_chars ()
2187 * may only be made on a channel from which data has been read in the
2188 * cases described in the documentation for g_io_channel_set_encoding ().
2190 * Return value: the status of the operation.
2193 g_io_channel_write_chars (GIOChannel *channel,
2196 gsize *bytes_written,
2200 gssize wrote_bytes = 0;
2202 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2203 g_return_val_if_fail ((error == NULL) || (*error == NULL),
2205 g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
2207 if ((count < 0) && buf)
2208 count = strlen (buf);
2214 return G_IO_STATUS_NORMAL;
2217 g_return_val_if_fail (buf != NULL, G_IO_STATUS_ERROR);
2218 g_return_val_if_fail (count > 0, G_IO_STATUS_ERROR);
2220 /* Raw write case */
2222 if (!channel->use_buffer)
2226 g_assert (!channel->write_buf || channel->write_buf->len == 0);
2227 g_assert (channel->partial_write_buf[0] == '\0');
2229 status = channel->funcs->io_write (channel, buf, count, &tmp_bytes, error);
2232 *bytes_written = tmp_bytes;
2239 if (channel->is_seekable && (( BUF_LEN (channel->read_buf) > 0)
2240 || (BUF_LEN (channel->encoded_read_buf) > 0)))
2242 if (channel->do_encode && BUF_LEN (channel->encoded_read_buf) > 0)
2244 g_warning("Mixed reading and writing not allowed on encoded files");
2245 return G_IO_STATUS_ERROR;
2247 status = g_io_channel_seek_position (channel, 0, G_SEEK_CUR, error);
2248 if (status != G_IO_STATUS_NORMAL)
2256 if (!channel->write_buf)
2257 channel->write_buf = g_string_sized_new (channel->buf_size);
2259 while (wrote_bytes < count)
2263 /* If the buffer is full, try a write immediately. In
2264 * the nonblocking case, this prevents the user from
2265 * writing just a little bit to the buffer every time
2266 * and never receiving an EAGAIN.
2269 if (channel->write_buf->len >= channel->buf_size - MAX_CHAR_SIZE)
2271 gsize did_write = 0, this_time;
2275 status = channel->funcs->io_write (channel, channel->write_buf->str
2276 + did_write, channel->write_buf->len
2277 - did_write, &this_time, error);
2278 did_write += this_time;
2280 while (status == G_IO_STATUS_NORMAL &&
2281 did_write < MIN (channel->write_buf->len, MAX_CHAR_SIZE));
2283 g_string_erase (channel->write_buf, 0, did_write);
2285 if (status != G_IO_STATUS_NORMAL)
2287 if (status == G_IO_STATUS_AGAIN && wrote_bytes > 0)
2288 status = G_IO_STATUS_NORMAL;
2290 *bytes_written = wrote_bytes;
2295 space_in_buf = MAX (channel->buf_size, channel->write_buf->allocated_len - 1)
2296 - channel->write_buf->len; /* 1 for NULL */
2298 /* This is only true because g_io_channel_set_buffer_size ()
2299 * ensures that channel->buf_size >= MAX_CHAR_SIZE.
2301 g_assert (space_in_buf >= MAX_CHAR_SIZE);
2303 if (!channel->encoding)
2305 gssize write_this = MIN (space_in_buf, count - wrote_bytes);
2307 g_string_append_len (channel->write_buf, buf, write_this);
2309 wrote_bytes += write_this;
2313 const gchar *from_buf;
2314 gsize from_buf_len, from_buf_old_len, left_len;
2318 if (channel->partial_write_buf[0] != '\0')
2320 g_assert (wrote_bytes == 0);
2322 from_buf = channel->partial_write_buf;
2323 from_buf_old_len = strlen (channel->partial_write_buf);
2324 g_assert (from_buf_old_len > 0);
2325 from_buf_len = MIN (6, from_buf_old_len + count);
2327 memcpy (channel->partial_write_buf + from_buf_old_len, buf,
2328 from_buf_len - from_buf_old_len);
2333 from_buf_len = count - wrote_bytes;
2334 from_buf_old_len = 0;
2339 if (!channel->do_encode) /* UTF-8 encoding */
2341 const gchar *badchar;
2342 gsize try_len = MIN (from_buf_len, space_in_buf);
2344 /* UTF-8, just validate, emulate g_iconv */
2346 if (!g_utf8_validate (from_buf, try_len, &badchar))
2349 gsize incomplete_len = from_buf + try_len - badchar;
2351 left_len = from_buf + from_buf_len - badchar;
2353 try_char = g_utf8_get_char_validated (badchar, incomplete_len);
2358 g_assert (incomplete_len < 6);
2359 if (try_len == from_buf_len)
2371 g_warning ("Invalid UTF-8 passed to g_io_channel_write_chars().");
2372 /* FIXME bail here? */
2377 g_assert_not_reached ();
2379 errnum = 0; /* Don't confunse the compiler */
2386 left_len = from_buf_len - try_len;
2389 g_string_append_len (channel->write_buf, from_buf,
2390 from_buf_len - left_len);
2391 from_buf += from_buf_len - left_len;
2397 left_len = from_buf_len;
2398 g_string_set_size (channel->write_buf, channel->write_buf->len
2400 outbuf = channel->write_buf->str + channel->write_buf->len
2402 err = g_iconv (channel->write_cd, (gchar **) &from_buf, &left_len,
2403 &outbuf, &space_in_buf);
2405 g_string_truncate (channel->write_buf, channel->write_buf->len
2409 if (err == (gsize) -1)
2414 g_assert (left_len < 6);
2416 if (from_buf_old_len == 0)
2418 /* Not from partial_write_buf */
2420 memcpy (channel->partial_write_buf, from_buf, left_len);
2421 channel->partial_write_buf[left_len] = '\0';
2423 *bytes_written = count;
2424 return G_IO_STATUS_NORMAL;
2427 /* Working in partial_write_buf */
2429 if (left_len == from_buf_len)
2431 /* Didn't convert anything, must still have
2432 * less than a full character
2435 g_assert (count == from_buf_len - from_buf_old_len);
2437 channel->partial_write_buf[from_buf_len] = '\0';
2440 *bytes_written = count;
2442 return G_IO_STATUS_NORMAL;
2445 g_assert (from_buf_len - left_len >= from_buf_old_len);
2447 /* We converted all the old data. This is fine */
2451 if (from_buf_len == left_len)
2453 /* Nothing was written, add enough space for
2454 * at least one character.
2456 space_in_buf += MAX_CHAR_SIZE;
2461 g_set_error_literal (error, G_CONVERT_ERROR,
2462 G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2463 _("Invalid byte sequence in conversion input"));
2464 if (from_buf_old_len > 0 && from_buf_len == left_len)
2465 g_warning ("Illegal sequence due to partial character "
2466 "at the end of a previous write.\n");
2468 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2470 *bytes_written = wrote_bytes;
2471 channel->partial_write_buf[0] = '\0';
2472 return G_IO_STATUS_ERROR;
2474 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
2475 _("Error during conversion: %s"), g_strerror (errnum));
2476 if (from_buf_len >= left_len + from_buf_old_len)
2477 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2479 *bytes_written = wrote_bytes;
2480 channel->partial_write_buf[0] = '\0';
2481 return G_IO_STATUS_ERROR;
2485 g_assert (from_buf_len - left_len >= from_buf_old_len);
2487 wrote_bytes += from_buf_len - left_len - from_buf_old_len;
2489 if (from_buf_old_len > 0)
2491 /* We were working in partial_write_buf */
2493 buf += from_buf_len - left_len - from_buf_old_len;
2494 channel->partial_write_buf[0] = '\0';
2502 *bytes_written = count;
2504 return G_IO_STATUS_NORMAL;
2508 * g_io_channel_write_unichar:
2509 * @channel: a #GIOChannel
2510 * @thechar: a character
2511 * @error: location to return an error of type #GConvertError
2512 * or #GIOChannelError
2514 * Writes a Unicode character to @channel.
2515 * This function cannot be called on a channel with %NULL encoding.
2517 * Return value: a #GIOStatus
2520 g_io_channel_write_unichar (GIOChannel *channel,
2525 gchar static_buf[6];
2526 gsize char_len, wrote_len;
2528 g_return_val_if_fail (channel != NULL, G_IO_STATUS_ERROR);
2529 g_return_val_if_fail (channel->encoding != NULL, G_IO_STATUS_ERROR);
2530 g_return_val_if_fail ((error == NULL) || (*error == NULL),
2532 g_return_val_if_fail (channel->is_writeable, G_IO_STATUS_ERROR);
2534 char_len = g_unichar_to_utf8 (thechar, static_buf);
2536 if (channel->partial_write_buf[0] != '\0')
2538 g_warning ("Partial charater written before writing unichar.\n");
2539 channel->partial_write_buf[0] = '\0';
2542 status = g_io_channel_write_chars (channel, static_buf,
2543 char_len, &wrote_len, error);
2545 /* We validate UTF-8, so we can't get a partial write */
2547 g_assert (wrote_len == char_len || status != G_IO_STATUS_NORMAL);
2553 * g_io_channel_error_quark:
2555 * Return value: the quark used as %G_IO_CHANNEL_ERROR
2558 * G_IO_CHANNEL_ERROR:
2560 * Error domain for #GIOChannel operations. Errors in this domain will
2561 * be from the #GIOChannelError enumeration. See #GError for
2562 * information on error domains.
2566 * @G_IO_CHANNEL_ERROR_FBIG: File too large.
2567 * @G_IO_CHANNEL_ERROR_INVAL: Invalid argument.
2568 * @G_IO_CHANNEL_ERROR_IO: IO error.
2569 * @G_IO_CHANNEL_ERROR_ISDIR: File is a directory.
2570 * @G_IO_CHANNEL_ERROR_NOSPC: No space left on device.
2571 * @G_IO_CHANNEL_ERROR_NXIO: No such device or address.
2572 * @G_IO_CHANNEL_ERROR_OVERFLOW: Value too large for defined datatype.
2573 * @G_IO_CHANNEL_ERROR_PIPE: Broken pipe.
2574 * @G_IO_CHANNEL_ERROR_FAILED: Some other error.
2576 * Error codes returned by #GIOChannel operations.
2579 g_io_channel_error_quark (void)
2581 return g_quark_from_static_string ("g-io-channel-error-quark");
2584 #define __G_IOCHANNEL_C__
2585 #include "galiasdef.c"