Merge branch 'test-ip_mreq_source-android-only' into 'master'
[glib.git] / glib / gstdio.c
blobffbd371803e985f6c755eb4fd881762869975792
1 /* gstdio.c - wrappers for C library functions
3 * Copyright 2004 Tor Lillqvist
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with this library; if not, see <http://www.gnu.org/licenses/>.
19 #include "config.h"
20 #include "glibconfig.h"
22 #define G_STDIO_NO_WRAP_ON_UNIX
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <fcntl.h>
28 #ifdef G_OS_UNIX
29 #include <unistd.h>
30 #endif
32 #ifdef G_OS_WIN32
33 #include <windows.h>
34 #include <errno.h>
35 #include <wchar.h>
36 #include <direct.h>
37 #include <io.h>
38 #include <sys/utime.h>
39 #else
40 #include <utime.h>
41 #include <errno.h>
42 #endif
44 #include "gstdio.h"
45 #include "gstdioprivate.h"
47 #if !defined (G_OS_UNIX) && !defined (G_OS_WIN32)
48 #error Please port this to your operating system
49 #endif
51 #if defined (_MSC_VER) && !defined(_WIN64)
52 #undef _wstat
53 #define _wstat _wstat32
54 #endif
56 #if defined (G_OS_WIN32)
58 /* We can't include Windows DDK and Windows SDK simultaneously,
59 * so let's copy this here from MinGW-w64 DDK.
60 * The structure is ultimately documented here:
61 * https://msdn.microsoft.com/en-us/library/ff552012(v=vs.85).aspx
63 typedef struct _REPARSE_DATA_BUFFER
65 ULONG ReparseTag;
66 USHORT ReparseDataLength;
67 USHORT Reserved;
68 union
70 struct
72 USHORT SubstituteNameOffset;
73 USHORT SubstituteNameLength;
74 USHORT PrintNameOffset;
75 USHORT PrintNameLength;
76 ULONG Flags;
77 WCHAR PathBuffer[1];
78 } SymbolicLinkReparseBuffer;
79 struct
81 USHORT SubstituteNameOffset;
82 USHORT SubstituteNameLength;
83 USHORT PrintNameOffset;
84 USHORT PrintNameLength;
85 WCHAR PathBuffer[1];
86 } MountPointReparseBuffer;
87 struct
89 UCHAR DataBuffer[1];
90 } GenericReparseBuffer;
92 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
94 static int
95 w32_error_to_errno (DWORD error_code)
97 switch (error_code)
99 case ERROR_ACCESS_DENIED:
100 return EACCES;
101 break;
102 case ERROR_INVALID_HANDLE:
103 return EBADF;
104 break;
105 case ERROR_INVALID_FUNCTION:
106 return EFAULT;
107 break;
108 case ERROR_FILE_NOT_FOUND:
109 return ENOENT;
110 break;
111 case ERROR_PATH_NOT_FOUND:
112 return ENOENT; /* or ELOOP, or ENAMETOOLONG */
113 break;
114 case ERROR_NOT_ENOUGH_MEMORY:
115 case ERROR_OUTOFMEMORY:
116 return ENOMEM;
117 break;
118 default:
119 return EIO;
120 break;
124 static int
125 _g_win32_stat_utf16_no_trailing_slashes (const gunichar2 *filename,
126 int fd,
127 GWin32PrivateStat *buf,
128 gboolean for_symlink)
130 HANDLE file_handle;
131 gboolean succeeded_so_far;
132 DWORD error_code;
133 struct __stat64 statbuf;
134 BY_HANDLE_FILE_INFORMATION handle_info;
135 FILE_STANDARD_INFO std_info;
136 WIN32_FIND_DATAW finddata;
137 DWORD immediate_attributes;
138 gboolean is_symlink = FALSE;
139 gboolean is_directory;
140 DWORD open_flags;
141 wchar_t *filename_target = NULL;
142 int result;
144 if (fd < 0)
146 immediate_attributes = GetFileAttributesW (filename);
148 if (immediate_attributes == INVALID_FILE_ATTRIBUTES)
150 error_code = GetLastError ();
151 errno = w32_error_to_errno (error_code);
153 return -1;
156 is_symlink = (immediate_attributes & FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT;
157 is_directory = (immediate_attributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY;
159 open_flags = FILE_ATTRIBUTE_NORMAL;
161 if (for_symlink && is_symlink)
162 open_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
164 if (is_directory)
165 open_flags |= FILE_FLAG_BACKUP_SEMANTICS;
167 file_handle = CreateFileW (filename, FILE_READ_ATTRIBUTES,
168 FILE_SHARE_READ, NULL, OPEN_EXISTING,
169 open_flags,
170 NULL);
172 if (file_handle == INVALID_HANDLE_VALUE)
174 error_code = GetLastError ();
175 errno = w32_error_to_errno (error_code);
176 return -1;
179 else
181 file_handle = (HANDLE) _get_osfhandle (fd);
183 if (file_handle == INVALID_HANDLE_VALUE)
184 return -1;
187 succeeded_so_far = GetFileInformationByHandle (file_handle,
188 &handle_info);
189 error_code = GetLastError ();
191 if (succeeded_so_far)
193 succeeded_so_far = GetFileInformationByHandleEx (file_handle,
194 FileStandardInfo,
195 &std_info,
196 sizeof (std_info));
197 error_code = GetLastError ();
200 if (!succeeded_so_far)
202 if (fd < 0)
203 CloseHandle (file_handle);
204 errno = w32_error_to_errno (error_code);
205 return -1;
208 /* It's tempting to use GetFileInformationByHandleEx(FileAttributeTagInfo),
209 * but it always reports that the ReparseTag is 0.
211 if (fd < 0)
213 memset (&finddata, 0, sizeof (finddata));
215 if (handle_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
217 HANDLE tmp = FindFirstFileW (filename,
218 &finddata);
220 if (tmp == INVALID_HANDLE_VALUE)
222 error_code = GetLastError ();
223 errno = w32_error_to_errno (error_code);
224 CloseHandle (file_handle);
225 return -1;
228 FindClose (tmp);
231 if (is_symlink && !for_symlink)
233 /* If filename is a symlink, _wstat64 obtains information about
234 * the symlink (except that st_size will be 0).
235 * To get information about the target we need to resolve
236 * the symlink first. And we need _wstat64() to get st_dev,
237 * it's a bother to try finding it ourselves.
239 DWORD filename_target_len;
240 DWORD new_len;
242 /* Just in case, give it a real memory location instead of NULL */
243 new_len = GetFinalPathNameByHandleW (file_handle,
244 (wchar_t *) &filename_target_len,
246 FILE_NAME_NORMALIZED);
248 #define SANE_LIMIT 1024 * 10
249 if (new_len >= SANE_LIMIT)
250 #undef SANE_LIMIT
252 new_len = 0;
253 error_code = ERROR_BUFFER_OVERFLOW;
255 else if (new_len == 0)
257 error_code = GetLastError ();
260 if (new_len > 0)
262 const wchar_t *extended_prefix = L"\\\\?\\";
263 const gsize extended_prefix_len = wcslen (extended_prefix);
264 const gsize extended_prefix_len_bytes = sizeof (wchar_t) * extended_prefix_len;
266 /* Pretend that new_len doesn't count the terminating NUL char,
267 * and ask for a bit more space than is needed.
269 filename_target_len = new_len + 5;
270 filename_target = g_malloc (filename_target_len * sizeof (wchar_t));
272 new_len = GetFinalPathNameByHandleW (file_handle,
273 filename_target,
274 filename_target_len,
275 FILE_NAME_NORMALIZED);
277 /* filename_target_len is already larger than needed,
278 * new_len should be smaller than that, even if the size
279 * is off by 1 for some reason.
281 if (new_len >= filename_target_len - 1)
283 new_len = 0;
284 error_code = ERROR_BUFFER_OVERFLOW;
285 g_clear_pointer (&filename_target, g_free);
287 /* GetFinalPathNameByHandle() is documented to return extended paths,
288 * strip the extended prefix.
290 else if (new_len > extended_prefix_len &&
291 memcmp (filename_target, extended_prefix, extended_prefix_len_bytes) == 0)
293 new_len -= extended_prefix_len;
294 memmove (filename_target,
295 filename_target + extended_prefix_len,
296 (new_len + 1) * sizeof (wchar_t));
300 if (new_len == 0)
301 succeeded_so_far = FALSE;
304 CloseHandle (file_handle);
306 /* else if fd >= 0 the file_handle was obtained via _get_osfhandle()
307 * and must not be closed, it is owned by fd.
310 if (!succeeded_so_far)
312 errno = w32_error_to_errno (error_code);
313 return -1;
316 if (fd < 0)
317 result = _wstat64 (filename_target != NULL ? filename_target : filename, &statbuf);
318 else
319 result = _fstat64 (fd, &statbuf);
321 if (result != 0)
323 int errsv = errno;
325 g_free (filename_target);
326 errno = errsv;
328 return -1;
331 g_free (filename_target);
333 buf->st_dev = statbuf.st_dev;
334 buf->st_mode = statbuf.st_mode;
335 buf->volume_serial = handle_info.dwVolumeSerialNumber;
336 buf->file_index = (((guint64) handle_info.nFileIndexHigh) << 32) | handle_info.nFileIndexLow;
337 /* Note that immediate_attributes is for the symlink
338 * (if it's a symlink), while handle_info contains info
339 * about the symlink or the target, depending on the flags
340 * we used earlier.
342 buf->attributes = handle_info.dwFileAttributes;
343 buf->st_nlink = handle_info.nNumberOfLinks;
344 buf->st_size = (((guint64) handle_info.nFileSizeHigh) << 32) | handle_info.nFileSizeLow;
345 buf->allocated_size = std_info.AllocationSize.QuadPart;
347 if (fd < 0 && buf->attributes & FILE_ATTRIBUTE_REPARSE_POINT)
348 buf->reparse_tag = finddata.dwReserved0;
349 else
350 buf->reparse_tag = 0;
352 buf->st_ctime = statbuf.st_ctime;
353 buf->st_atime = statbuf.st_atime;
354 buf->st_mtime = statbuf.st_mtime;
356 return 0;
359 static int
360 _g_win32_stat_utf8 (const gchar *filename,
361 GWin32PrivateStat *buf,
362 gboolean for_symlink)
364 wchar_t *wfilename;
365 int result;
366 gsize len;
368 if (filename == NULL)
370 errno = EINVAL;
371 return -1;
374 len = strlen (filename);
376 while (len > 0 && G_IS_DIR_SEPARATOR (filename[len - 1]))
377 len--;
379 if (len <= 0 ||
380 (g_path_is_absolute (filename) && len <= g_path_skip_root (filename) - filename))
381 len = strlen (filename);
383 wfilename = g_utf8_to_utf16 (filename, len, NULL, NULL, NULL);
385 if (wfilename == NULL)
387 errno = EINVAL;
388 return -1;
391 result = _g_win32_stat_utf16_no_trailing_slashes (wfilename, -1, buf, for_symlink);
393 g_free (wfilename);
395 return result;
399 g_win32_stat_utf8 (const gchar *filename,
400 GWin32PrivateStat *buf)
402 return _g_win32_stat_utf8 (filename, buf, FALSE);
406 g_win32_lstat_utf8 (const gchar *filename,
407 GWin32PrivateStat *buf)
409 return _g_win32_stat_utf8 (filename, buf, TRUE);
413 g_win32_fstat (int fd,
414 GWin32PrivateStat *buf)
416 return _g_win32_stat_utf16_no_trailing_slashes (NULL, fd, buf, FALSE);
419 static int
420 _g_win32_readlink_utf16_raw (const gunichar2 *filename,
421 gunichar2 *buf,
422 gsize buf_size)
424 DWORD returned_bytes;
425 BYTE returned_data[MAXIMUM_REPARSE_DATA_BUFFER_SIZE]; /* This is 16k, by the way */
426 HANDLE h;
427 DWORD attributes;
428 REPARSE_DATA_BUFFER *rep_buf;
429 DWORD to_copy;
430 DWORD error_code;
432 if (buf_size > G_MAXSIZE / sizeof (wchar_t))
434 /* "buf_size * sizeof (wchar_t)" overflows */
435 errno = EFAULT;
436 return -1;
439 if ((attributes = GetFileAttributesW (filename)) == 0)
441 error_code = GetLastError ();
442 errno = w32_error_to_errno (error_code);
443 return -1;
446 if ((attributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
448 errno = EINVAL;
449 return -1;
452 /* To read symlink target we need to open the file as a reparse
453 * point and use DeviceIoControl() on it.
455 h = CreateFileW (filename,
456 FILE_READ_ATTRIBUTES | SYNCHRONIZE | GENERIC_READ,
457 FILE_SHARE_READ, NULL, OPEN_EXISTING,
458 FILE_ATTRIBUTE_NORMAL
459 | FILE_FLAG_OPEN_REPARSE_POINT
460 | (attributes & FILE_ATTRIBUTE_DIRECTORY ? FILE_FLAG_BACKUP_SEMANTICS : 0),
461 NULL);
463 if (h == INVALID_HANDLE_VALUE)
465 error_code = GetLastError ();
466 errno = w32_error_to_errno (error_code);
467 return -1;
470 if (!DeviceIoControl (h, FSCTL_GET_REPARSE_POINT, NULL, 0,
471 returned_data, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
472 &returned_bytes, NULL))
474 error_code = GetLastError ();
475 errno = w32_error_to_errno (error_code);
476 CloseHandle (h);
477 return -1;
480 rep_buf = (REPARSE_DATA_BUFFER *) returned_data;
481 to_copy = 0;
483 if (rep_buf->ReparseTag == IO_REPARSE_TAG_SYMLINK)
485 to_copy = rep_buf->SymbolicLinkReparseBuffer.SubstituteNameLength;
487 if (to_copy > buf_size * sizeof (wchar_t))
488 to_copy = buf_size * sizeof (wchar_t);
490 memcpy (buf,
491 &((BYTE *) rep_buf->SymbolicLinkReparseBuffer.PathBuffer)[rep_buf->SymbolicLinkReparseBuffer.SubstituteNameOffset],
492 to_copy);
494 else if (rep_buf->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
496 to_copy = rep_buf->MountPointReparseBuffer.SubstituteNameLength;
498 if (to_copy > buf_size * sizeof (wchar_t))
499 to_copy = buf_size * sizeof (wchar_t);
501 memcpy (buf,
502 &((BYTE *) rep_buf->MountPointReparseBuffer.PathBuffer)[rep_buf->MountPointReparseBuffer.SubstituteNameOffset],
503 to_copy);
506 CloseHandle (h);
508 return to_copy;
511 static int
512 _g_win32_readlink_utf16 (const gunichar2 *filename,
513 gunichar2 *buf,
514 gsize buf_size)
516 const wchar_t *ntobjm_prefix = L"\\??\\";
517 const gsize ntobjm_prefix_len_unichar2 = wcslen (ntobjm_prefix);
518 const gsize ntobjm_prefix_len_bytes = sizeof (gunichar2) * ntobjm_prefix_len_unichar2;
519 int result = _g_win32_readlink_utf16_raw (filename, buf, buf_size);
521 if (result <= 0)
522 return result;
524 /* Ensure that output is a multiple of sizeof (gunichar2),
525 * cutting any trailing partial gunichar2, if present.
527 result -= result % sizeof (gunichar2);
529 if (result <= 0)
530 return result;
532 /* DeviceIoControl () tends to return filenames as NT Object Manager
533 * names , i.e. "\\??\\C:\\foo\\bar".
534 * Remove the leading 4-byte \??\ prefix, as glib (as well as many W32 API
535 * functions) is unprepared to deal with it.
537 if (result > ntobjm_prefix_len_bytes &&
538 memcmp (buf, ntobjm_prefix, ntobjm_prefix_len_bytes) == 0)
540 result -= ntobjm_prefix_len_bytes;
541 memmove (buf, buf + ntobjm_prefix_len_unichar2, result);
544 return result;
547 static gchar *
548 _g_win32_get_mode_alias (const gchar *mode)
550 gchar *alias;
552 alias = g_strdup (mode);
553 if (strlen (mode) > 2 && mode[2] == '+')
555 /* Windows implementation of fopen() does not accept modes such as
556 * "wb+". The 'b' needs to be appended to "w+", i.e. "w+b". Note
557 * that otherwise these 2 modes are supposed to be aliases, hence
558 * swappable at will.
560 alias[1] = '+';
561 alias[2] = mode[1];
564 return alias;
568 g_win32_readlink_utf8 (const gchar *filename,
569 gchar *buf,
570 gsize buf_size)
572 wchar_t *wfilename;
573 int result;
575 wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
577 if (wfilename == NULL)
579 errno = EINVAL;
580 return -1;
583 result = _g_win32_readlink_utf16 (wfilename, (gunichar2 *) buf, buf_size);
585 g_free (wfilename);
587 if (result > 0)
589 glong tmp_len;
590 gchar *tmp = g_utf16_to_utf8 ((const gunichar2 *) buf,
591 result / sizeof (gunichar2),
592 NULL,
593 &tmp_len,
594 NULL);
596 if (tmp == NULL)
598 errno = EINVAL;
599 return -1;
602 if (tmp_len > buf_size - 1)
603 tmp_len = buf_size - 1;
605 memcpy (buf, tmp, tmp_len);
606 /* readlink() doesn't NUL-terminate, but we do.
607 * To be compliant, however, we return the
608 * number of bytes without the NUL-terminator.
610 buf[tmp_len] = '\0';
611 result = tmp_len;
612 g_free (tmp);
615 return result;
618 #endif
621 * g_access:
622 * @filename: (type filename): a pathname in the GLib file name encoding
623 * (UTF-8 on Windows)
624 * @mode: as in access()
626 * A wrapper for the POSIX access() function. This function is used to
627 * test a pathname for one or several of read, write or execute
628 * permissions, or just existence.
630 * On Windows, the file protection mechanism is not at all POSIX-like,
631 * and the underlying function in the C library only checks the
632 * FAT-style READONLY attribute, and does not look at the ACL of a
633 * file at all. This function is this in practise almost useless on
634 * Windows. Software that needs to handle file permissions on Windows
635 * more exactly should use the Win32 API.
637 * See your C library manual for more details about access().
639 * Returns: zero if the pathname refers to an existing file system
640 * object that has all the tested permissions, or -1 otherwise
641 * or on error.
643 * Since: 2.8
646 g_access (const gchar *filename,
647 int mode)
649 #ifdef G_OS_WIN32
650 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
651 int retval;
652 int save_errno;
654 if (wfilename == NULL)
656 errno = EINVAL;
657 return -1;
660 #ifndef X_OK
661 #define X_OK 1
662 #endif
664 retval = _waccess (wfilename, mode & ~X_OK);
665 save_errno = errno;
667 g_free (wfilename);
669 errno = save_errno;
670 return retval;
671 #else
672 return access (filename, mode);
673 #endif
677 * g_chmod:
678 * @filename: (type filename): a pathname in the GLib file name encoding
679 * (UTF-8 on Windows)
680 * @mode: as in chmod()
682 * A wrapper for the POSIX chmod() function. The chmod() function is
683 * used to set the permissions of a file system object.
685 * On Windows the file protection mechanism is not at all POSIX-like,
686 * and the underlying chmod() function in the C library just sets or
687 * clears the FAT-style READONLY attribute. It does not touch any
688 * ACL. Software that needs to manage file permissions on Windows
689 * exactly should use the Win32 API.
691 * See your C library manual for more details about chmod().
693 * Returns: 0 if the operation succeeded, -1 on error
695 * Since: 2.8
698 g_chmod (const gchar *filename,
699 int mode)
701 #ifdef G_OS_WIN32
702 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
703 int retval;
704 int save_errno;
706 if (wfilename == NULL)
708 errno = EINVAL;
709 return -1;
712 retval = _wchmod (wfilename, mode);
713 save_errno = errno;
715 g_free (wfilename);
717 errno = save_errno;
718 return retval;
719 #else
720 return chmod (filename, mode);
721 #endif
724 * g_open:
725 * @filename: (type filename): a pathname in the GLib file name encoding
726 * (UTF-8 on Windows)
727 * @flags: as in open()
728 * @mode: as in open()
730 * A wrapper for the POSIX open() function. The open() function is
731 * used to convert a pathname into a file descriptor.
733 * On POSIX systems file descriptors are implemented by the operating
734 * system. On Windows, it's the C library that implements open() and
735 * file descriptors. The actual Win32 API for opening files is quite
736 * different, see MSDN documentation for CreateFile(). The Win32 API
737 * uses file handles, which are more randomish integers, not small
738 * integers like file descriptors.
740 * Because file descriptors are specific to the C library on Windows,
741 * the file descriptor returned by this function makes sense only to
742 * functions in the same C library. Thus if the GLib-using code uses a
743 * different C library than GLib does, the file descriptor returned by
744 * this function cannot be passed to C library functions like write()
745 * or read().
747 * See your C library manual for more details about open().
749 * Returns: a new file descriptor, or -1 if an error occurred.
750 * The return value can be used exactly like the return value
751 * from open().
753 * Since: 2.6
756 g_open (const gchar *filename,
757 int flags,
758 int mode)
760 #ifdef G_OS_WIN32
761 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
762 int retval;
763 int save_errno;
765 if (wfilename == NULL)
767 errno = EINVAL;
768 return -1;
771 retval = _wopen (wfilename, flags, mode);
772 save_errno = errno;
774 g_free (wfilename);
776 errno = save_errno;
777 return retval;
778 #else
779 int fd;
781 fd = open (filename, flags, mode);
782 while (G_UNLIKELY (fd == -1 && errno == EINTR));
783 return fd;
784 #endif
788 * g_creat:
789 * @filename: (type filename): a pathname in the GLib file name encoding
790 * (UTF-8 on Windows)
791 * @mode: as in creat()
793 * A wrapper for the POSIX creat() function. The creat() function is
794 * used to convert a pathname into a file descriptor, creating a file
795 * if necessary.
797 * On POSIX systems file descriptors are implemented by the operating
798 * system. On Windows, it's the C library that implements creat() and
799 * file descriptors. The actual Windows API for opening files is
800 * different, see MSDN documentation for CreateFile(). The Win32 API
801 * uses file handles, which are more randomish integers, not small
802 * integers like file descriptors.
804 * Because file descriptors are specific to the C library on Windows,
805 * the file descriptor returned by this function makes sense only to
806 * functions in the same C library. Thus if the GLib-using code uses a
807 * different C library than GLib does, the file descriptor returned by
808 * this function cannot be passed to C library functions like write()
809 * or read().
811 * See your C library manual for more details about creat().
813 * Returns: a new file descriptor, or -1 if an error occurred.
814 * The return value can be used exactly like the return value
815 * from creat().
817 * Since: 2.8
820 g_creat (const gchar *filename,
821 int mode)
823 #ifdef G_OS_WIN32
824 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
825 int retval;
826 int save_errno;
828 if (wfilename == NULL)
830 errno = EINVAL;
831 return -1;
834 retval = _wcreat (wfilename, mode);
835 save_errno = errno;
837 g_free (wfilename);
839 errno = save_errno;
840 return retval;
841 #else
842 return creat (filename, mode);
843 #endif
847 * g_rename:
848 * @oldfilename: (type filename): a pathname in the GLib file name encoding
849 * (UTF-8 on Windows)
850 * @newfilename: (type filename): a pathname in the GLib file name encoding
852 * A wrapper for the POSIX rename() function. The rename() function
853 * renames a file, moving it between directories if required.
855 * See your C library manual for more details about how rename() works
856 * on your system. It is not possible in general on Windows to rename
857 * a file that is open to some process.
859 * Returns: 0 if the renaming succeeded, -1 if an error occurred
861 * Since: 2.6
864 g_rename (const gchar *oldfilename,
865 const gchar *newfilename)
867 #ifdef G_OS_WIN32
868 wchar_t *woldfilename = g_utf8_to_utf16 (oldfilename, -1, NULL, NULL, NULL);
869 wchar_t *wnewfilename;
870 int retval;
871 int save_errno = 0;
873 if (woldfilename == NULL)
875 errno = EINVAL;
876 return -1;
879 wnewfilename = g_utf8_to_utf16 (newfilename, -1, NULL, NULL, NULL);
881 if (wnewfilename == NULL)
883 g_free (woldfilename);
884 errno = EINVAL;
885 return -1;
888 if (MoveFileExW (woldfilename, wnewfilename, MOVEFILE_REPLACE_EXISTING))
889 retval = 0;
890 else
892 retval = -1;
893 switch (GetLastError ())
895 #define CASE(a,b) case ERROR_##a: save_errno = b; break
896 CASE (FILE_NOT_FOUND, ENOENT);
897 CASE (PATH_NOT_FOUND, ENOENT);
898 CASE (ACCESS_DENIED, EACCES);
899 CASE (NOT_SAME_DEVICE, EXDEV);
900 CASE (LOCK_VIOLATION, EACCES);
901 CASE (SHARING_VIOLATION, EACCES);
902 CASE (FILE_EXISTS, EEXIST);
903 CASE (ALREADY_EXISTS, EEXIST);
904 #undef CASE
905 default: save_errno = EIO;
909 g_free (woldfilename);
910 g_free (wnewfilename);
912 errno = save_errno;
913 return retval;
914 #else
915 return rename (oldfilename, newfilename);
916 #endif
920 * g_mkdir:
921 * @filename: (type filename): a pathname in the GLib file name encoding
922 * (UTF-8 on Windows)
923 * @mode: permissions to use for the newly created directory
925 * A wrapper for the POSIX mkdir() function. The mkdir() function
926 * attempts to create a directory with the given name and permissions.
927 * The mode argument is ignored on Windows.
929 * See your C library manual for more details about mkdir().
931 * Returns: 0 if the directory was successfully created, -1 if an error
932 * occurred
934 * Since: 2.6
937 g_mkdir (const gchar *filename,
938 int mode)
940 #ifdef G_OS_WIN32
941 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
942 int retval;
943 int save_errno;
945 if (wfilename == NULL)
947 errno = EINVAL;
948 return -1;
951 retval = _wmkdir (wfilename);
952 save_errno = errno;
954 g_free (wfilename);
956 errno = save_errno;
957 return retval;
958 #else
959 return mkdir (filename, mode);
960 #endif
964 * g_chdir:
965 * @path: (type filename): a pathname in the GLib file name encoding
966 * (UTF-8 on Windows)
968 * A wrapper for the POSIX chdir() function. The function changes the
969 * current directory of the process to @path.
971 * See your C library manual for more details about chdir().
973 * Returns: 0 on success, -1 if an error occurred.
975 * Since: 2.8
978 g_chdir (const gchar *path)
980 #ifdef G_OS_WIN32
981 wchar_t *wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, NULL);
982 int retval;
983 int save_errno;
985 if (wpath == NULL)
987 errno = EINVAL;
988 return -1;
991 retval = _wchdir (wpath);
992 save_errno = errno;
994 g_free (wpath);
996 errno = save_errno;
997 return retval;
998 #else
999 return chdir (path);
1000 #endif
1004 * GStatBuf:
1006 * A type corresponding to the appropriate struct type for the stat()
1007 * system call, depending on the platform and/or compiler being used.
1009 * See g_stat() for more information.
1012 * g_stat:
1013 * @filename: (type filename): a pathname in the GLib file name encoding
1014 * (UTF-8 on Windows)
1015 * @buf: a pointer to a stat struct, which will be filled with the file
1016 * information
1018 * A wrapper for the POSIX stat() function. The stat() function
1019 * returns information about a file. On Windows the stat() function in
1020 * the C library checks only the FAT-style READONLY attribute and does
1021 * not look at the ACL at all. Thus on Windows the protection bits in
1022 * the @st_mode field are a fabrication of little use.
1024 * On Windows the Microsoft C libraries have several variants of the
1025 * stat struct and stat() function with names like _stat(), _stat32(),
1026 * _stat32i64() and _stat64i32(). The one used here is for 32-bit code
1027 * the one with 32-bit size and time fields, specifically called _stat32().
1029 * In Microsoft's compiler, by default struct stat means one with
1030 * 64-bit time fields while in MinGW struct stat is the legacy one
1031 * with 32-bit fields. To hopefully clear up this messs, the gstdio.h
1032 * header defines a type #GStatBuf which is the appropriate struct type
1033 * depending on the platform and/or compiler being used. On POSIX it
1034 * is just struct stat, but note that even on POSIX platforms, stat()
1035 * might be a macro.
1037 * See your C library manual for more details about stat().
1039 * Returns: 0 if the information was successfully retrieved,
1040 * -1 if an error occurred
1042 * Since: 2.6
1045 g_stat (const gchar *filename,
1046 GStatBuf *buf)
1048 #ifdef G_OS_WIN32
1049 GWin32PrivateStat w32_buf;
1050 int retval = g_win32_stat_utf8 (filename, &w32_buf);
1052 buf->st_dev = w32_buf.st_dev;
1053 buf->st_ino = w32_buf.st_ino;
1054 buf->st_mode = w32_buf.st_mode;
1055 buf->st_nlink = w32_buf.st_nlink;
1056 buf->st_uid = w32_buf.st_uid;
1057 buf->st_gid = w32_buf.st_gid;
1058 buf->st_rdev = w32_buf.st_dev;
1059 buf->st_size = w32_buf.st_size;
1060 buf->st_atime = w32_buf.st_atime;
1061 buf->st_mtime = w32_buf.st_mtime;
1062 buf->st_ctime = w32_buf.st_ctime;
1064 return retval;
1065 #else
1066 return stat (filename, buf);
1067 #endif
1071 * g_lstat:
1072 * @filename: (type filename): a pathname in the GLib file name encoding
1073 * (UTF-8 on Windows)
1074 * @buf: a pointer to a stat struct, which will be filled with the file
1075 * information
1077 * A wrapper for the POSIX lstat() function. The lstat() function is
1078 * like stat() except that in the case of symbolic links, it returns
1079 * information about the symbolic link itself and not the file that it
1080 * refers to. If the system does not support symbolic links g_lstat()
1081 * is identical to g_stat().
1083 * See your C library manual for more details about lstat().
1085 * Returns: 0 if the information was successfully retrieved,
1086 * -1 if an error occurred
1088 * Since: 2.6
1091 g_lstat (const gchar *filename,
1092 GStatBuf *buf)
1094 #ifdef HAVE_LSTAT
1095 /* This can't be Win32, so don't do the widechar dance. */
1096 return lstat (filename, buf);
1097 #elif defined (G_OS_WIN32)
1098 GWin32PrivateStat w32_buf;
1099 int retval = g_win32_lstat_utf8 (filename, &w32_buf);
1101 buf->st_dev = w32_buf.st_dev;
1102 buf->st_ino = w32_buf.st_ino;
1103 buf->st_mode = w32_buf.st_mode;
1104 buf->st_nlink = w32_buf.st_nlink;
1105 buf->st_uid = w32_buf.st_uid;
1106 buf->st_gid = w32_buf.st_gid;
1107 buf->st_rdev = w32_buf.st_dev;
1108 buf->st_size = w32_buf.st_size;
1109 buf->st_atime = w32_buf.st_atime;
1110 buf->st_mtime = w32_buf.st_mtime;
1111 buf->st_ctime = w32_buf.st_ctime;
1113 return retval;
1114 #else
1115 return g_stat (filename, buf);
1116 #endif
1120 * g_unlink:
1121 * @filename: (type filename): a pathname in the GLib file name encoding
1122 * (UTF-8 on Windows)
1124 * A wrapper for the POSIX unlink() function. The unlink() function
1125 * deletes a name from the filesystem. If this was the last link to the
1126 * file and no processes have it opened, the diskspace occupied by the
1127 * file is freed.
1129 * See your C library manual for more details about unlink(). Note
1130 * that on Windows, it is in general not possible to delete files that
1131 * are open to some process, or mapped into memory.
1133 * Returns: 0 if the name was successfully deleted, -1 if an error
1134 * occurred
1136 * Since: 2.6
1139 g_unlink (const gchar *filename)
1141 #ifdef G_OS_WIN32
1142 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1143 int retval;
1144 int save_errno;
1146 if (wfilename == NULL)
1148 errno = EINVAL;
1149 return -1;
1152 retval = _wunlink (wfilename);
1153 save_errno = errno;
1155 g_free (wfilename);
1157 errno = save_errno;
1158 return retval;
1159 #else
1160 return unlink (filename);
1161 #endif
1165 * g_remove:
1166 * @filename: (type filename): a pathname in the GLib file name encoding
1167 * (UTF-8 on Windows)
1169 * A wrapper for the POSIX remove() function. The remove() function
1170 * deletes a name from the filesystem.
1172 * See your C library manual for more details about how remove() works
1173 * on your system. On Unix, remove() removes also directories, as it
1174 * calls unlink() for files and rmdir() for directories. On Windows,
1175 * although remove() in the C library only works for files, this
1176 * function tries first remove() and then if that fails rmdir(), and
1177 * thus works for both files and directories. Note however, that on
1178 * Windows, it is in general not possible to remove a file that is
1179 * open to some process, or mapped into memory.
1181 * If this function fails on Windows you can't infer too much from the
1182 * errno value. rmdir() is tried regardless of what caused remove() to
1183 * fail. Any errno value set by remove() will be overwritten by that
1184 * set by rmdir().
1186 * Returns: 0 if the file was successfully removed, -1 if an error
1187 * occurred
1189 * Since: 2.6
1192 g_remove (const gchar *filename)
1194 #ifdef G_OS_WIN32
1195 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1196 int retval;
1197 int save_errno;
1199 if (wfilename == NULL)
1201 errno = EINVAL;
1202 return -1;
1205 retval = _wremove (wfilename);
1206 if (retval == -1)
1207 retval = _wrmdir (wfilename);
1208 save_errno = errno;
1210 g_free (wfilename);
1212 errno = save_errno;
1213 return retval;
1214 #else
1215 return remove (filename);
1216 #endif
1220 * g_rmdir:
1221 * @filename: (type filename): a pathname in the GLib file name encoding
1222 * (UTF-8 on Windows)
1224 * A wrapper for the POSIX rmdir() function. The rmdir() function
1225 * deletes a directory from the filesystem.
1227 * See your C library manual for more details about how rmdir() works
1228 * on your system.
1230 * Returns: 0 if the directory was successfully removed, -1 if an error
1231 * occurred
1233 * Since: 2.6
1236 g_rmdir (const gchar *filename)
1238 #ifdef G_OS_WIN32
1239 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1240 int retval;
1241 int save_errno;
1243 if (wfilename == NULL)
1245 errno = EINVAL;
1246 return -1;
1249 retval = _wrmdir (wfilename);
1250 save_errno = errno;
1252 g_free (wfilename);
1254 errno = save_errno;
1255 return retval;
1256 #else
1257 return rmdir (filename);
1258 #endif
1262 * g_fopen:
1263 * @filename: (type filename): a pathname in the GLib file name encoding
1264 * (UTF-8 on Windows)
1265 * @mode: a string describing the mode in which the file should be opened
1267 * A wrapper for the stdio fopen() function. The fopen() function
1268 * opens a file and associates a new stream with it.
1270 * Because file descriptors are specific to the C library on Windows,
1271 * and a file descriptor is part of the FILE struct, the FILE* returned
1272 * by this function makes sense only to functions in the same C library.
1273 * Thus if the GLib-using code uses a different C library than GLib does,
1274 * the FILE* returned by this function cannot be passed to C library
1275 * functions like fprintf() or fread().
1277 * See your C library manual for more details about fopen().
1279 * Returns: A FILE* if the file was successfully opened, or %NULL if
1280 * an error occurred
1282 * Since: 2.6
1284 FILE *
1285 g_fopen (const gchar *filename,
1286 const gchar *mode)
1288 #ifdef G_OS_WIN32
1289 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1290 wchar_t *wmode;
1291 gchar *mode2;
1292 FILE *retval;
1293 int save_errno;
1295 if (wfilename == NULL)
1297 errno = EINVAL;
1298 return NULL;
1301 mode2 = _g_win32_get_mode_alias (mode);
1302 wmode = g_utf8_to_utf16 (mode2, -1, NULL, NULL, NULL);
1303 g_free (mode2);
1305 if (wmode == NULL)
1307 g_free (wfilename);
1308 errno = EINVAL;
1309 return NULL;
1312 retval = _wfopen (wfilename, wmode);
1313 save_errno = errno;
1315 g_free (wfilename);
1316 g_free (wmode);
1318 errno = save_errno;
1319 return retval;
1320 #else
1321 return fopen (filename, mode);
1322 #endif
1326 * g_freopen:
1327 * @filename: (type filename): a pathname in the GLib file name encoding
1328 * (UTF-8 on Windows)
1329 * @mode: a string describing the mode in which the file should be opened
1330 * @stream: (nullable): an existing stream which will be reused, or %NULL
1332 * A wrapper for the POSIX freopen() function. The freopen() function
1333 * opens a file and associates it with an existing stream.
1335 * See your C library manual for more details about freopen().
1337 * Returns: A FILE* if the file was successfully opened, or %NULL if
1338 * an error occurred.
1340 * Since: 2.6
1342 FILE *
1343 g_freopen (const gchar *filename,
1344 const gchar *mode,
1345 FILE *stream)
1347 #ifdef G_OS_WIN32
1348 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1349 wchar_t *wmode;
1350 gchar *mode2;
1351 FILE *retval;
1352 int save_errno;
1354 if (wfilename == NULL)
1356 errno = EINVAL;
1357 return NULL;
1360 mode2 = _g_win32_get_mode_alias (mode);
1361 wmode = g_utf8_to_utf16 (mode2, -1, NULL, NULL, NULL);
1362 g_free (mode2);
1364 if (wmode == NULL)
1366 g_free (wfilename);
1367 errno = EINVAL;
1368 return NULL;
1371 retval = _wfreopen (wfilename, wmode, stream);
1372 save_errno = errno;
1374 g_free (wfilename);
1375 g_free (wmode);
1377 errno = save_errno;
1378 return retval;
1379 #else
1380 return freopen (filename, mode, stream);
1381 #endif
1385 * g_utime:
1386 * @filename: (type filename): a pathname in the GLib file name encoding
1387 * (UTF-8 on Windows)
1388 * @utb: a pointer to a struct utimbuf.
1390 * A wrapper for the POSIX utime() function. The utime() function
1391 * sets the access and modification timestamps of a file.
1393 * See your C library manual for more details about how utime() works
1394 * on your system.
1396 * Returns: 0 if the operation was successful, -1 if an error occurred
1398 * Since: 2.18
1401 g_utime (const gchar *filename,
1402 struct utimbuf *utb)
1404 #ifdef G_OS_WIN32
1405 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1406 int retval;
1407 int save_errno;
1409 if (wfilename == NULL)
1411 errno = EINVAL;
1412 return -1;
1415 retval = _wutime (wfilename, (struct _utimbuf*) utb);
1416 save_errno = errno;
1418 g_free (wfilename);
1420 errno = save_errno;
1421 return retval;
1422 #else
1423 return utime (filename, utb);
1424 #endif
1428 * g_close:
1429 * @fd: A file descriptor
1430 * @error: a #GError
1432 * This wraps the close() call; in case of error, %errno will be
1433 * preserved, but the error will also be stored as a #GError in @error.
1435 * Besides using #GError, there is another major reason to prefer this
1436 * function over the call provided by the system; on Unix, it will
1437 * attempt to correctly handle %EINTR, which has platform-specific
1438 * semantics.
1440 * Returns: %TRUE on success, %FALSE if there was an error.
1442 * Since: 2.36
1444 gboolean
1445 g_close (gint fd,
1446 GError **error)
1448 int res;
1449 res = close (fd);
1450 /* Just ignore EINTR for now; a retry loop is the wrong thing to do
1451 * on Linux at least. Anyone who wants to add a conditional check
1452 * for e.g. HP-UX is welcome to do so later...
1454 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
1455 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
1456 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
1457 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
1459 if (G_UNLIKELY (res == -1 && errno == EINTR))
1460 return TRUE;
1461 else if (res == -1)
1463 int errsv = errno;
1464 g_set_error_literal (error, G_FILE_ERROR,
1465 g_file_error_from_errno (errsv),
1466 g_strerror (errsv));
1467 errno = errsv;
1468 return FALSE;
1470 return TRUE;