Merge branch 'fdonotif-fix-backend-dispose-race' into 'master'
[glib.git] / glib / gstdio.c
blobe158de22337143a0d809e2f96a687e84542951cf
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;
548 g_win32_readlink_utf8 (const gchar *filename,
549 gchar *buf,
550 gsize buf_size)
552 wchar_t *wfilename;
553 int result;
555 wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
557 if (wfilename == NULL)
559 errno = EINVAL;
560 return -1;
563 result = _g_win32_readlink_utf16 (wfilename, (gunichar2 *) buf, buf_size);
565 g_free (wfilename);
567 if (result > 0)
569 glong tmp_len;
570 gchar *tmp = g_utf16_to_utf8 ((const gunichar2 *) buf,
571 result / sizeof (gunichar2),
572 NULL,
573 &tmp_len,
574 NULL);
576 if (tmp == NULL)
578 errno = EINVAL;
579 return -1;
582 if (tmp_len > buf_size - 1)
583 tmp_len = buf_size - 1;
585 memcpy (buf, tmp, tmp_len);
586 /* readlink() doesn't NUL-terminate, but we do.
587 * To be compliant, however, we return the
588 * number of bytes without the NUL-terminator.
590 buf[tmp_len] = '\0';
591 result = tmp_len;
592 g_free (tmp);
595 return result;
598 #endif
601 * g_access:
602 * @filename: (type filename): a pathname in the GLib file name encoding
603 * (UTF-8 on Windows)
604 * @mode: as in access()
606 * A wrapper for the POSIX access() function. This function is used to
607 * test a pathname for one or several of read, write or execute
608 * permissions, or just existence.
610 * On Windows, the file protection mechanism is not at all POSIX-like,
611 * and the underlying function in the C library only checks the
612 * FAT-style READONLY attribute, and does not look at the ACL of a
613 * file at all. This function is this in practise almost useless on
614 * Windows. Software that needs to handle file permissions on Windows
615 * more exactly should use the Win32 API.
617 * See your C library manual for more details about access().
619 * Returns: zero if the pathname refers to an existing file system
620 * object that has all the tested permissions, or -1 otherwise
621 * or on error.
623 * Since: 2.8
626 g_access (const gchar *filename,
627 int mode)
629 #ifdef G_OS_WIN32
630 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
631 int retval;
632 int save_errno;
634 if (wfilename == NULL)
636 errno = EINVAL;
637 return -1;
640 #ifndef X_OK
641 #define X_OK 1
642 #endif
644 retval = _waccess (wfilename, mode & ~X_OK);
645 save_errno = errno;
647 g_free (wfilename);
649 errno = save_errno;
650 return retval;
651 #else
652 return access (filename, mode);
653 #endif
657 * g_chmod:
658 * @filename: (type filename): a pathname in the GLib file name encoding
659 * (UTF-8 on Windows)
660 * @mode: as in chmod()
662 * A wrapper for the POSIX chmod() function. The chmod() function is
663 * used to set the permissions of a file system object.
665 * On Windows the file protection mechanism is not at all POSIX-like,
666 * and the underlying chmod() function in the C library just sets or
667 * clears the FAT-style READONLY attribute. It does not touch any
668 * ACL. Software that needs to manage file permissions on Windows
669 * exactly should use the Win32 API.
671 * See your C library manual for more details about chmod().
673 * Returns: 0 if the operation succeeded, -1 on error
675 * Since: 2.8
678 g_chmod (const gchar *filename,
679 int mode)
681 #ifdef G_OS_WIN32
682 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
683 int retval;
684 int save_errno;
686 if (wfilename == NULL)
688 errno = EINVAL;
689 return -1;
692 retval = _wchmod (wfilename, mode);
693 save_errno = errno;
695 g_free (wfilename);
697 errno = save_errno;
698 return retval;
699 #else
700 return chmod (filename, mode);
701 #endif
704 * g_open:
705 * @filename: (type filename): a pathname in the GLib file name encoding
706 * (UTF-8 on Windows)
707 * @flags: as in open()
708 * @mode: as in open()
710 * A wrapper for the POSIX open() function. The open() function is
711 * used to convert a pathname into a file descriptor.
713 * On POSIX systems file descriptors are implemented by the operating
714 * system. On Windows, it's the C library that implements open() and
715 * file descriptors. The actual Win32 API for opening files is quite
716 * different, see MSDN documentation for CreateFile(). The Win32 API
717 * uses file handles, which are more randomish integers, not small
718 * integers like file descriptors.
720 * Because file descriptors are specific to the C library on Windows,
721 * the file descriptor returned by this function makes sense only to
722 * functions in the same C library. Thus if the GLib-using code uses a
723 * different C library than GLib does, the file descriptor returned by
724 * this function cannot be passed to C library functions like write()
725 * or read().
727 * See your C library manual for more details about open().
729 * Returns: a new file descriptor, or -1 if an error occurred.
730 * The return value can be used exactly like the return value
731 * from open().
733 * Since: 2.6
736 g_open (const gchar *filename,
737 int flags,
738 int mode)
740 #ifdef G_OS_WIN32
741 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
742 int retval;
743 int save_errno;
745 if (wfilename == NULL)
747 errno = EINVAL;
748 return -1;
751 retval = _wopen (wfilename, flags, mode);
752 save_errno = errno;
754 g_free (wfilename);
756 errno = save_errno;
757 return retval;
758 #else
759 int fd;
761 fd = open (filename, flags, mode);
762 while (G_UNLIKELY (fd == -1 && errno == EINTR));
763 return fd;
764 #endif
768 * g_creat:
769 * @filename: (type filename): a pathname in the GLib file name encoding
770 * (UTF-8 on Windows)
771 * @mode: as in creat()
773 * A wrapper for the POSIX creat() function. The creat() function is
774 * used to convert a pathname into a file descriptor, creating a file
775 * if necessary.
777 * On POSIX systems file descriptors are implemented by the operating
778 * system. On Windows, it's the C library that implements creat() and
779 * file descriptors. The actual Windows API for opening files is
780 * different, see MSDN documentation for CreateFile(). The Win32 API
781 * uses file handles, which are more randomish integers, not small
782 * integers like file descriptors.
784 * Because file descriptors are specific to the C library on Windows,
785 * the file descriptor returned by this function makes sense only to
786 * functions in the same C library. Thus if the GLib-using code uses a
787 * different C library than GLib does, the file descriptor returned by
788 * this function cannot be passed to C library functions like write()
789 * or read().
791 * See your C library manual for more details about creat().
793 * Returns: a new file descriptor, or -1 if an error occurred.
794 * The return value can be used exactly like the return value
795 * from creat().
797 * Since: 2.8
800 g_creat (const gchar *filename,
801 int mode)
803 #ifdef G_OS_WIN32
804 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
805 int retval;
806 int save_errno;
808 if (wfilename == NULL)
810 errno = EINVAL;
811 return -1;
814 retval = _wcreat (wfilename, mode);
815 save_errno = errno;
817 g_free (wfilename);
819 errno = save_errno;
820 return retval;
821 #else
822 return creat (filename, mode);
823 #endif
827 * g_rename:
828 * @oldfilename: (type filename): a pathname in the GLib file name encoding
829 * (UTF-8 on Windows)
830 * @newfilename: (type filename): a pathname in the GLib file name encoding
832 * A wrapper for the POSIX rename() function. The rename() function
833 * renames a file, moving it between directories if required.
835 * See your C library manual for more details about how rename() works
836 * on your system. It is not possible in general on Windows to rename
837 * a file that is open to some process.
839 * Returns: 0 if the renaming succeeded, -1 if an error occurred
841 * Since: 2.6
844 g_rename (const gchar *oldfilename,
845 const gchar *newfilename)
847 #ifdef G_OS_WIN32
848 wchar_t *woldfilename = g_utf8_to_utf16 (oldfilename, -1, NULL, NULL, NULL);
849 wchar_t *wnewfilename;
850 int retval;
851 int save_errno = 0;
853 if (woldfilename == NULL)
855 errno = EINVAL;
856 return -1;
859 wnewfilename = g_utf8_to_utf16 (newfilename, -1, NULL, NULL, NULL);
861 if (wnewfilename == NULL)
863 g_free (woldfilename);
864 errno = EINVAL;
865 return -1;
868 if (MoveFileExW (woldfilename, wnewfilename, MOVEFILE_REPLACE_EXISTING))
869 retval = 0;
870 else
872 retval = -1;
873 switch (GetLastError ())
875 #define CASE(a,b) case ERROR_##a: save_errno = b; break
876 CASE (FILE_NOT_FOUND, ENOENT);
877 CASE (PATH_NOT_FOUND, ENOENT);
878 CASE (ACCESS_DENIED, EACCES);
879 CASE (NOT_SAME_DEVICE, EXDEV);
880 CASE (LOCK_VIOLATION, EACCES);
881 CASE (SHARING_VIOLATION, EACCES);
882 CASE (FILE_EXISTS, EEXIST);
883 CASE (ALREADY_EXISTS, EEXIST);
884 #undef CASE
885 default: save_errno = EIO;
889 g_free (woldfilename);
890 g_free (wnewfilename);
892 errno = save_errno;
893 return retval;
894 #else
895 return rename (oldfilename, newfilename);
896 #endif
900 * g_mkdir:
901 * @filename: (type filename): a pathname in the GLib file name encoding
902 * (UTF-8 on Windows)
903 * @mode: permissions to use for the newly created directory
905 * A wrapper for the POSIX mkdir() function. The mkdir() function
906 * attempts to create a directory with the given name and permissions.
907 * The mode argument is ignored on Windows.
909 * See your C library manual for more details about mkdir().
911 * Returns: 0 if the directory was successfully created, -1 if an error
912 * occurred
914 * Since: 2.6
917 g_mkdir (const gchar *filename,
918 int mode)
920 #ifdef G_OS_WIN32
921 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
922 int retval;
923 int save_errno;
925 if (wfilename == NULL)
927 errno = EINVAL;
928 return -1;
931 retval = _wmkdir (wfilename);
932 save_errno = errno;
934 g_free (wfilename);
936 errno = save_errno;
937 return retval;
938 #else
939 return mkdir (filename, mode);
940 #endif
944 * g_chdir:
945 * @path: (type filename): a pathname in the GLib file name encoding
946 * (UTF-8 on Windows)
948 * A wrapper for the POSIX chdir() function. The function changes the
949 * current directory of the process to @path.
951 * See your C library manual for more details about chdir().
953 * Returns: 0 on success, -1 if an error occurred.
955 * Since: 2.8
958 g_chdir (const gchar *path)
960 #ifdef G_OS_WIN32
961 wchar_t *wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, NULL);
962 int retval;
963 int save_errno;
965 if (wpath == NULL)
967 errno = EINVAL;
968 return -1;
971 retval = _wchdir (wpath);
972 save_errno = errno;
974 g_free (wpath);
976 errno = save_errno;
977 return retval;
978 #else
979 return chdir (path);
980 #endif
984 * GStatBuf:
986 * A type corresponding to the appropriate struct type for the stat()
987 * system call, depending on the platform and/or compiler being used.
989 * See g_stat() for more information.
992 * g_stat:
993 * @filename: (type filename): a pathname in the GLib file name encoding
994 * (UTF-8 on Windows)
995 * @buf: a pointer to a stat struct, which will be filled with the file
996 * information
998 * A wrapper for the POSIX stat() function. The stat() function
999 * returns information about a file. On Windows the stat() function in
1000 * the C library checks only the FAT-style READONLY attribute and does
1001 * not look at the ACL at all. Thus on Windows the protection bits in
1002 * the @st_mode field are a fabrication of little use.
1004 * On Windows the Microsoft C libraries have several variants of the
1005 * stat struct and stat() function with names like _stat(), _stat32(),
1006 * _stat32i64() and _stat64i32(). The one used here is for 32-bit code
1007 * the one with 32-bit size and time fields, specifically called _stat32().
1009 * In Microsoft's compiler, by default struct stat means one with
1010 * 64-bit time fields while in MinGW struct stat is the legacy one
1011 * with 32-bit fields. To hopefully clear up this messs, the gstdio.h
1012 * header defines a type #GStatBuf which is the appropriate struct type
1013 * depending on the platform and/or compiler being used. On POSIX it
1014 * is just struct stat, but note that even on POSIX platforms, stat()
1015 * might be a macro.
1017 * See your C library manual for more details about stat().
1019 * Returns: 0 if the information was successfully retrieved,
1020 * -1 if an error occurred
1022 * Since: 2.6
1025 g_stat (const gchar *filename,
1026 GStatBuf *buf)
1028 #ifdef G_OS_WIN32
1029 GWin32PrivateStat w32_buf;
1030 int retval = g_win32_stat_utf8 (filename, &w32_buf);
1032 buf->st_dev = w32_buf.st_dev;
1033 buf->st_ino = w32_buf.st_ino;
1034 buf->st_mode = w32_buf.st_mode;
1035 buf->st_nlink = w32_buf.st_nlink;
1036 buf->st_uid = w32_buf.st_uid;
1037 buf->st_gid = w32_buf.st_gid;
1038 buf->st_rdev = w32_buf.st_dev;
1039 buf->st_size = w32_buf.st_size;
1040 buf->st_atime = w32_buf.st_atime;
1041 buf->st_mtime = w32_buf.st_mtime;
1042 buf->st_ctime = w32_buf.st_ctime;
1044 return retval;
1045 #else
1046 return stat (filename, buf);
1047 #endif
1051 * g_lstat:
1052 * @filename: (type filename): a pathname in the GLib file name encoding
1053 * (UTF-8 on Windows)
1054 * @buf: a pointer to a stat struct, which will be filled with the file
1055 * information
1057 * A wrapper for the POSIX lstat() function. The lstat() function is
1058 * like stat() except that in the case of symbolic links, it returns
1059 * information about the symbolic link itself and not the file that it
1060 * refers to. If the system does not support symbolic links g_lstat()
1061 * is identical to g_stat().
1063 * See your C library manual for more details about lstat().
1065 * Returns: 0 if the information was successfully retrieved,
1066 * -1 if an error occurred
1068 * Since: 2.6
1071 g_lstat (const gchar *filename,
1072 GStatBuf *buf)
1074 #ifdef HAVE_LSTAT
1075 /* This can't be Win32, so don't do the widechar dance. */
1076 return lstat (filename, buf);
1077 #elif defined (G_OS_WIN32)
1078 GWin32PrivateStat w32_buf;
1079 int retval = g_win32_lstat_utf8 (filename, &w32_buf);
1081 buf->st_dev = w32_buf.st_dev;
1082 buf->st_ino = w32_buf.st_ino;
1083 buf->st_mode = w32_buf.st_mode;
1084 buf->st_nlink = w32_buf.st_nlink;
1085 buf->st_uid = w32_buf.st_uid;
1086 buf->st_gid = w32_buf.st_gid;
1087 buf->st_rdev = w32_buf.st_dev;
1088 buf->st_size = w32_buf.st_size;
1089 buf->st_atime = w32_buf.st_atime;
1090 buf->st_mtime = w32_buf.st_mtime;
1091 buf->st_ctime = w32_buf.st_ctime;
1093 return retval;
1094 #else
1095 return g_stat (filename, buf);
1096 #endif
1100 * g_unlink:
1101 * @filename: (type filename): a pathname in the GLib file name encoding
1102 * (UTF-8 on Windows)
1104 * A wrapper for the POSIX unlink() function. The unlink() function
1105 * deletes a name from the filesystem. If this was the last link to the
1106 * file and no processes have it opened, the diskspace occupied by the
1107 * file is freed.
1109 * See your C library manual for more details about unlink(). Note
1110 * that on Windows, it is in general not possible to delete files that
1111 * are open to some process, or mapped into memory.
1113 * Returns: 0 if the name was successfully deleted, -1 if an error
1114 * occurred
1116 * Since: 2.6
1119 g_unlink (const gchar *filename)
1121 #ifdef G_OS_WIN32
1122 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1123 int retval;
1124 int save_errno;
1126 if (wfilename == NULL)
1128 errno = EINVAL;
1129 return -1;
1132 retval = _wunlink (wfilename);
1133 save_errno = errno;
1135 g_free (wfilename);
1137 errno = save_errno;
1138 return retval;
1139 #else
1140 return unlink (filename);
1141 #endif
1145 * g_remove:
1146 * @filename: (type filename): a pathname in the GLib file name encoding
1147 * (UTF-8 on Windows)
1149 * A wrapper for the POSIX remove() function. The remove() function
1150 * deletes a name from the filesystem.
1152 * See your C library manual for more details about how remove() works
1153 * on your system. On Unix, remove() removes also directories, as it
1154 * calls unlink() for files and rmdir() for directories. On Windows,
1155 * although remove() in the C library only works for files, this
1156 * function tries first remove() and then if that fails rmdir(), and
1157 * thus works for both files and directories. Note however, that on
1158 * Windows, it is in general not possible to remove a file that is
1159 * open to some process, or mapped into memory.
1161 * If this function fails on Windows you can't infer too much from the
1162 * errno value. rmdir() is tried regardless of what caused remove() to
1163 * fail. Any errno value set by remove() will be overwritten by that
1164 * set by rmdir().
1166 * Returns: 0 if the file was successfully removed, -1 if an error
1167 * occurred
1169 * Since: 2.6
1172 g_remove (const gchar *filename)
1174 #ifdef G_OS_WIN32
1175 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1176 int retval;
1177 int save_errno;
1179 if (wfilename == NULL)
1181 errno = EINVAL;
1182 return -1;
1185 retval = _wremove (wfilename);
1186 if (retval == -1)
1187 retval = _wrmdir (wfilename);
1188 save_errno = errno;
1190 g_free (wfilename);
1192 errno = save_errno;
1193 return retval;
1194 #else
1195 return remove (filename);
1196 #endif
1200 * g_rmdir:
1201 * @filename: (type filename): a pathname in the GLib file name encoding
1202 * (UTF-8 on Windows)
1204 * A wrapper for the POSIX rmdir() function. The rmdir() function
1205 * deletes a directory from the filesystem.
1207 * See your C library manual for more details about how rmdir() works
1208 * on your system.
1210 * Returns: 0 if the directory was successfully removed, -1 if an error
1211 * occurred
1213 * Since: 2.6
1216 g_rmdir (const gchar *filename)
1218 #ifdef G_OS_WIN32
1219 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1220 int retval;
1221 int save_errno;
1223 if (wfilename == NULL)
1225 errno = EINVAL;
1226 return -1;
1229 retval = _wrmdir (wfilename);
1230 save_errno = errno;
1232 g_free (wfilename);
1234 errno = save_errno;
1235 return retval;
1236 #else
1237 return rmdir (filename);
1238 #endif
1242 * g_fopen:
1243 * @filename: (type filename): a pathname in the GLib file name encoding
1244 * (UTF-8 on Windows)
1245 * @mode: a string describing the mode in which the file should be opened
1247 * A wrapper for the stdio fopen() function. The fopen() function
1248 * opens a file and associates a new stream with it.
1250 * Because file descriptors are specific to the C library on Windows,
1251 * and a file descriptor is part of the FILE struct, the FILE* returned
1252 * by this function makes sense only to functions in the same C library.
1253 * Thus if the GLib-using code uses a different C library than GLib does,
1254 * the FILE* returned by this function cannot be passed to C library
1255 * functions like fprintf() or fread().
1257 * See your C library manual for more details about fopen().
1259 * Returns: A FILE* if the file was successfully opened, or %NULL if
1260 * an error occurred
1262 * Since: 2.6
1264 FILE *
1265 g_fopen (const gchar *filename,
1266 const gchar *mode)
1268 #ifdef G_OS_WIN32
1269 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1270 wchar_t *wmode;
1271 FILE *retval;
1272 int save_errno;
1274 if (wfilename == NULL)
1276 errno = EINVAL;
1277 return NULL;
1280 wmode = g_utf8_to_utf16 (mode, -1, NULL, NULL, NULL);
1282 if (wmode == NULL)
1284 g_free (wfilename);
1285 errno = EINVAL;
1286 return NULL;
1289 retval = _wfopen (wfilename, wmode);
1290 save_errno = errno;
1292 g_free (wfilename);
1293 g_free (wmode);
1295 errno = save_errno;
1296 return retval;
1297 #else
1298 return fopen (filename, mode);
1299 #endif
1303 * g_freopen:
1304 * @filename: (type filename): a pathname in the GLib file name encoding
1305 * (UTF-8 on Windows)
1306 * @mode: a string describing the mode in which the file should be opened
1307 * @stream: (nullable): an existing stream which will be reused, or %NULL
1309 * A wrapper for the POSIX freopen() function. The freopen() function
1310 * opens a file and associates it with an existing stream.
1312 * See your C library manual for more details about freopen().
1314 * Returns: A FILE* if the file was successfully opened, or %NULL if
1315 * an error occurred.
1317 * Since: 2.6
1319 FILE *
1320 g_freopen (const gchar *filename,
1321 const gchar *mode,
1322 FILE *stream)
1324 #ifdef G_OS_WIN32
1325 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1326 wchar_t *wmode;
1327 FILE *retval;
1328 int save_errno;
1330 if (wfilename == NULL)
1332 errno = EINVAL;
1333 return NULL;
1336 wmode = g_utf8_to_utf16 (mode, -1, NULL, NULL, NULL);
1338 if (wmode == NULL)
1340 g_free (wfilename);
1341 errno = EINVAL;
1342 return NULL;
1345 retval = _wfreopen (wfilename, wmode, stream);
1346 save_errno = errno;
1348 g_free (wfilename);
1349 g_free (wmode);
1351 errno = save_errno;
1352 return retval;
1353 #else
1354 return freopen (filename, mode, stream);
1355 #endif
1359 * g_utime:
1360 * @filename: (type filename): a pathname in the GLib file name encoding
1361 * (UTF-8 on Windows)
1362 * @utb: a pointer to a struct utimbuf.
1364 * A wrapper for the POSIX utime() function. The utime() function
1365 * sets the access and modification timestamps of a file.
1367 * See your C library manual for more details about how utime() works
1368 * on your system.
1370 * Returns: 0 if the operation was successful, -1 if an error occurred
1372 * Since: 2.18
1375 g_utime (const gchar *filename,
1376 struct utimbuf *utb)
1378 #ifdef G_OS_WIN32
1379 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1380 int retval;
1381 int save_errno;
1383 if (wfilename == NULL)
1385 errno = EINVAL;
1386 return -1;
1389 retval = _wutime (wfilename, (struct _utimbuf*) utb);
1390 save_errno = errno;
1392 g_free (wfilename);
1394 errno = save_errno;
1395 return retval;
1396 #else
1397 return utime (filename, utb);
1398 #endif
1402 * g_close:
1403 * @fd: A file descriptor
1404 * @error: a #GError
1406 * This wraps the close() call; in case of error, %errno will be
1407 * preserved, but the error will also be stored as a #GError in @error.
1409 * Besides using #GError, there is another major reason to prefer this
1410 * function over the call provided by the system; on Unix, it will
1411 * attempt to correctly handle %EINTR, which has platform-specific
1412 * semantics.
1414 * Returns: %TRUE on success, %FALSE if there was an error.
1416 * Since: 2.36
1418 gboolean
1419 g_close (gint fd,
1420 GError **error)
1422 int res;
1423 res = close (fd);
1424 /* Just ignore EINTR for now; a retry loop is the wrong thing to do
1425 * on Linux at least. Anyone who wants to add a conditional check
1426 * for e.g. HP-UX is welcome to do so later...
1428 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
1429 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
1430 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
1431 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
1433 if (G_UNLIKELY (res == -1 && errno == EINTR))
1434 return TRUE;
1435 else if (res == -1)
1437 int errsv = errno;
1438 g_set_error_literal (error, G_FILE_ERROR,
1439 g_file_error_from_errno (errsv),
1440 g_strerror (errsv));
1441 errno = errsv;
1442 return FALSE;
1444 return TRUE;