文章目录
1、stat
NAME
stat, fstat, lstat, fstatat - get file status
SYNOPSIS
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *pathname, struct stat *buf);
int fstat(int fd, struct stat *buf);
int lstat(const char *pathname, struct stat *buf);
#include <fcntl.h> /* Definition of AT_* constants */
#include <sys/stat.h>
int fstatat(int dirfd, const char *pathname, struct stat *buf,
int flags);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
lstat():
/* glibc 2.19 and earlier */ _BSD_SOURCE ||
/* Since glibc 2.20 */_DEFAULT_SOURCE ||
_XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED
|| /* Since glibc 2.10: */ _POSIX_C_SOURCE >= 200112L
fstatat():
Since glibc 2.10:
_XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
Before glibc 2.10:
_ATFILE_SOURCE
DESCRIPTION
These functions return information about a file, in the buffer pointed
to by buf. No permissions are required on the file itself, but—in the
case of stat(), fstatat(), and lstat()—execute (search) permission is
required on all of the directories in pathname that lead to the file.
stat() and fstatat() retrieve information about the file pointed to by
pathname; the differences for fstatat() are described below.
lstat() is identical to stat(), except that if pathname is a symbolic
link, then it returns information about the link itself, not the file
that it refers to.
fstat() is identical to stat(), except that the file about which infor‐
mation is to be retrieved is specified by the file descriptor fd.
All of these system calls return a stat structure, which contains the
following fields:
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for filesystem I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
/* Since Linux 2.6, the kernel supports nanosecond
precision for the following timestamp fields.
For the details before Linux 2.6, see NOTES. */
struct timespec st_atim; /* time of last access */
struct timespec st_mtim; /* time of last modification */
struct timespec st_ctim; /* time of last status change */
#define st_atime st_atim.tv_sec /* Backward compatibility */
#define st_mtime st_mtim.tv_sec
#define st_ctime st_ctim.tv_sec
};
1.1、文件类型
/*
EXAMPLE
The following program calls stat() and displays selected fields in the
returned stat structure.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
struct stat sb;
if (argc != 2) {
fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (stat(argv[1], &sb) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
printf("File type: ");
switch (sb.st_mode & S_IFMT) {
case S_IFBLK: printf("block device\n"); break;
case S_IFCHR: printf("character device\n"); break;
case S_IFDIR: printf("directory\n"); break;
case S_IFIFO: printf("FIFO/pipe\n"); break;
case S_IFLNK: printf("symlink\n"); break;
case S_IFREG: printf("regular file\n"); break;
case S_IFSOCK: printf("socket\n"); break;
default: printf("unknown?\n"); break;
}
printf("I-node number: %ld\n", (long) sb.st_ino);
printf("Mode: %lo (octal)\n",
(unsigned long) sb.st_mode);
printf("Link count: %ld\n", (long) sb.st_nlink);
printf("Ownership: UID=%ld GID=%ld\n",
(long) sb.st_uid, (long) sb.st_gid);
printf("Preferred I/O block size: %ld bytes\n",
(long) sb.st_blksize);
printf("File size: %lld bytes\n",
(long long) sb.st_size);
printf("Blocks allocated: %lld\n",
(long long) sb.st_blocks);
printf("Last status change: %s", ctime(&sb.st_ctime));
printf("Last file access: %s", ctime(&sb.st_atime));
printf("Last file modification: %s", ctime(&sb.st_mtime));
exit(EXIT_SUCCESS);
}
1.2、文件权限
S_ISUID 04000 set-user-ID bit
S_ISGID 02000 set-group-ID bit (see below)
S_ISVTX 01000 sticky bit (see below)
S_IRWXU 00700 owner has read, write, and execute permission
S_IRUSR 00400 owner has read permission
S_IWUSR 00200 owner has write permission
S_IXUSR 00100 owner has execute permission
S_IRWXG 00070 group has read, write, and execute permission
S_IRGRP 00040 group has read permission
S_IWGRP 00020 group has write permission
S_IXGRP 00010 group has execute permission
S_IRWXO 00007 others (not in group) have read, write, and
execute permission
S_IROTH 00004 others have read permission
S_IWOTH 00002 others have write permission
S_IXOTH 00001 others have execute permission
2、acess
NAME
access, faccessat - check user's permissions for a file
SYNOPSIS
#include <unistd.h>
int access(const char *pathname, int mode);
#include <fcntl.h> /* Definition of AT_* constants */
#include <unistd.h>
int faccessat(int dirfd, const char *pathname, int mode, int flags);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
faccessat():
Since glibc 2.10:
_XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
Before glibc 2.10:
_ATFILE_SOURCE
DESCRIPTION
access() checks whether the calling process can access the file path‐
name. If pathname is a symbolic link, it is dereferenced.
The mode specifies the accessibility check(s) to be performed, and is
either the value F_OK, or a mask consisting of the bitwise OR of one or
more of R_OK, W_OK, and X_OK. F_OK tests for the existence of the
file. R_OK, W_OK, and X_OK test whether the file exists and grants
read, write, and execute permissions, respectively.
The check is done using the calling process's real UID and GID, rather
than the effective IDs as is done when actually attempting an operation
(e.g., open(2)) on the file. Similarly, for the root user, the check
uses the set of permitted capabilities rather than the set of effective
capabilities; and for non-root users, the check uses an empty set of
capabilities.
This allows set-user-ID programs and capability-endowed programs to
easily determine the invoking user's authority. In other words,
access() does not answer the "can I read/write/execute this file?"
question. It answers a slightly different question: "(assuming I'm a
setuid binary) can the user who invoked me read/write/execute this
file?", which gives set-user-ID programs the possibility to prevent
malicious users from causing them to read files which users shouldn't
be able to read.
If the calling process is privileged (i.e., its real UID is zero), then
an X_OK check is successful for a regular file if execute permission is
enabled for any of the file owner, group, or other.
RETURN VALUE
On success (all requested permissions granted, or mode is F_OK and the
file exists), zero is returned. On error (at least one bit in mode
asked for a permission that is denied, or mode is F_OK and the file
does not exist, or some other error occurred), -1 is returned, and
errno is set appropriately.
ERRORS
access() and faccessat() shall fail if:
EACCES The requested access would be denied to the file, or search per‐
mission is denied for one of the directories in the path prefix
of pathname. (See also path_resolution(7).)
ELOOP Too many symbolic links were encountered in resolving pathname.
ENAMETOOLONG
pathname is too long.
ENOENT A component of pathname does not exist or is a dangling symbolic
link.
ENOTDIR
A component used as a directory in pathname is not, in fact, a
directory.
EROFS Write permission was requested for a file on a read-only
filesystem.
access() and faccessat() may fail if:
EFAULT pathname points outside your accessible address space.
EINVAL mode was incorrectly specified.
EIO An I/O error occurred.
ENOMEM Insufficient kernel memory was available.
ETXTBSY
Write access was requested to an executable which is being exe‐
cuted.
The following additional errors can occur for faccessat():
EBADF dirfd is not a valid file descriptor.
EINVAL Invalid flag specified in flags.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring to
a file other than a directory.
VERSIONS
faccessat() was added to Linux in kernel 2.6.16; library support was
added to glibc in version 2.4.
CONFORMING TO
access(): SVr4, 4.3BSD, POSIX.1-2001, POSIX.1-2008.
faccessat(): POSIX.1-2008.
3、umask
NAME
umask — set and get the file mode creation mask
SYNOPSIS
#include <sys/stat.h>
mode_t umask(mode_t cmask);
DESCRIPTION
The umask() function shall set the file mode creation mask of the
process to cmask and return the previous value of the mask. Only the
file permission bits of cmask (see <sys/stat.h>) are used; the meaning
of the other bits is implementation-defined.
The file mode creation mask of the process is used to turn off permis‐
sion bits in the mode argument supplied during calls to the following
functions:
* open(), openat(), creat(), mkdir(), mkdirat(), mkfifo(), and mkfi‐
foat()
* mknod(), mknodat()
* mq_open()
* sem_open()
Bit positions that are set in cmask are cleared in the mode of the cre‐
ated file.
RETURN VALUE
The file permission bits in the value returned by umask() shall be the
previous value of the file mode creation mask. The state of any other
bits in that value is unspecified, except that a subsequent call to
umask() with the returned value as cmask shall leave the state of the
mask the same as its state before the first call, including any unspec‐
ified use of those bits.
ERRORS
No errors are defined.
4、chmod fchmod
NAME
chmod, fchmod, fchmodat - change permissions of a file
SYNOPSIS
#include <sys/stat.h>
int chmod(const char *pathname, mode_t mode);
int fchmod(int fd, mode_t mode);
#include <fcntl.h> /* Definition of AT_* constants */
#include <sys/stat.h>
S_ISUID (04000) set-user-ID (set process effective user ID on
execve(2))
S_ISGID (02000) set-group-ID (set process effective group ID on
execve(2); mandatory locking, as described in
fcntl(2); take a new file's group from parent direc‐
tory, as described in chown(2) and mkdir(2))
S_ISVTX (01000) sticky bit (restricted deletion flag, as described in
unlink(2))
S_IRUSR (00400) read by owner
S_IWUSR (00200) write by owner
S_IXUSR (00100) execute/search by owner ("search" applies for direc‐
tories, and means that entries within the directory
can be accessed)
S_IRGRP (00040) read by group
S_IWGRP (00020) write by group
S_IXGRP (00010) execute/search by group
S_IROTH (00004) read by others
S_IWOTH (00002) write by others
S_IXOTH (00001) execute/search by others
RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is
set appropriately.
ERRORS
Depending on the filesystem, errors other than those listed below can
be returned.
The more general errors for chmod() are listed below:
EACCES Search permission is denied on a component of the path prefix.
(See also path_resolution(7).)
EFAULT pathname points outside your accessible address space.
EIO An I/O error occurred.
ELOOP Too many symbolic links were encountered in resolving pathname.
ENAMETOOLONG
pathname is too long.
ENOENT The file does not exist.
ENOMEM Insufficient kernel memory was available.
ENOTDIR
A component of the path prefix is not a directory.
EPERM The effective UID does not match the owner of the file, and the
process is not privileged (Linux: it does not have the
CAP_FOWNER capability).
EROFS The named file resides on a read-only filesystem.
The general errors for fchmod() are listed below:
EBADF The file descriptor fd is not valid.
EIO See above.
EPERM See above.
EROFS See above.
The same errors that occur for chmod() can also occur for fchmodat().
The following additional errors can occur for fchmodat():
EBADF dirfd is not a valid file descriptor.
EINVAL Invalid flag specified in flags.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring to
a file other than a directory.
ENOTSUP
flags specified AT_SYMLINK_NOFOLLOW, which is not supported.
VERSIONS
fchmodat() was added to Linux in kernel 2.6.16; library support was
added to glibc in version 2.4.
CONFORMING TO
chmod(), fchmod(): 4.4BSD, SVr4, POSIX.1-2001i, POSIX.1-2008.
5、chown fchown lchown
NAME
chown, fchown, lchown, fchownat - change ownership of a file
SYNOPSIS
#include <unistd.h>
int chown(const char *pathname, uid_t owner, gid_t group);
int fchown(int fd, uid_t owner, gid_t group);
int lchown(const char *pathname, uid_t owner, gid_t group);
DESCRIPTION
These system calls change the owner and group of a file. The chown(),
fchown(), and lchown() system calls differ only in how the file is
specified:
* chown() changes the ownership of the file specified by pathname,
which is dereferenced if it is a symbolic link.
* fchown() changes the ownership of the file referred to by the open
file descriptor fd.
* lchown() is like chown(), but does not dereference symbolic links.
Only a privileged process (Linux: one with the CAP_CHOWN capability)
may change the owner of a file. The owner of a file may change the
group of the file to any group of which that owner is a member. A
privileged process (Linux: with CAP_CHOWN) may change the group arbi‐
trarily.
If the owner or group is specified as -1, then that ID is not changed.
When the owner or group of an executable file are changed by an unpriv‐
ileged user the S_ISUID and S_ISGID mode bits are cleared. POSIX does
not specify whether this also should happen when root does the chown();
the Linux behavior depends on the kernel version. In case of a non-
group-executable file (i.e., one for which the S_IXGRP bit is not set)
the S_ISGID bit indicates mandatory locking, and is not cleared by a
chown().
RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is
set appropriately.
ERRORS
Depending on the filesystem, errors other than those listed below can
be returned.
The more general errors for chown() are listed below.
EACCES Search permission is denied on a component of the path prefix.
(See also path_resolution(7).)
EFAULT pathname points outside your accessible address space.
ELOOP Too many symbolic links were encountered in resolving pathname.
ENAMETOOLONG
pathname is too long.
ENOENT The file does not exist.
ENOMEM Insufficient kernel memory was available.
ENOTDIR
A component of the path prefix is not a directory.
EPERM The calling process did not have the required permissions (see
above) to change owner and/or group.
EROFS The named file resides on a read-only filesystem.
The general errors for fchown() are listed below:
EBADF The descriptor is not valid.
EIO A low-level I/O error occurred while modifying the inode.
ENOENT See above.
EPERM See above.
EROFS See above.
The same errors that occur for chown() can also occur for fchownat().
The following additional errors can occur for fchownat():
EBADF dirfd is not a valid file descriptor.
EINVAL Invalid flag specified in flags.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring to
a file other than a directory.
VERSIONS
fchownat() was added to Linux in kernel 2.6.16; library support was
added to glibc in version 2.4.
CONFORMING TO
chown(), fchown(), lchown(): 4.4BSD, SVr4, POSIX.1-2001, POSIX.1-2008.
The 4.4BSD version can be used only by the superuser (that is, ordinary
users cannot give away files).
6、link ulink
NAME
link, linkat - make a new name for a file
SYNOPSIS
#include <unistd.h>
int link(const char *oldpath, const char *newpath);
#include <fcntl.h> /* Definition of AT_* constants */
#include <unistd.h>
int linkat(int olddirfd, const char *oldpath,
int newdirfd, const char *newpath, int flags);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
linkat():
Since glibc 2.10:
_XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
Before glibc 2.10:
_ATFILE_SOURCE
DESCRIPTION
link() creates a new link (also known as a hard link) to an existing
file.
If newpath exists, it will not be overwritten.
This new name may be used exactly as the old one for any operation;
both names refer to the same file (and so have the same permissions and
ownership) and it is impossible to tell which name was the "original".
linkat()
The linkat() system call operates in exactly the same way as link(),
except for the differences described here.
If the pathname given in oldpath is relative, then it is interpreted
relative to the directory referred to by the file descriptor olddirfd
(rather than relative to the current working directory of the calling
process, as is done by link() for a relative pathname).
If oldpath is relative and olddirfd is the special value AT_FDCWD, then
oldpath is interpreted relative to the current working directory of the
calling process (like link()).
If oldpath is absolute, then olddirfd is ignored.
The interpretation of newpath is as for oldpath, except that a relative
pathname is interpreted relative to the directory referred to by the
file descriptor newdirfd.
The following values can be bitwise ORed in flags:
AT_EMPTY_PATH (since Linux 2.6.39)
If oldpath is an empty string, create a link to the file refer‐
enced by olddirfd (which may have been obtained using the
open(2) O_PATH flag). In this case, olddirfd can refer to any
type of file, not just a directory. This will generally not
work if the file has a link count of zero (files created with
O_TMPFILE and without O_EXCL are an exception). The caller must
have the CAP_DAC_READ_SEARCH capability in order to use this
flag. This flag is Linux-specific; define _GNU_SOURCE to obtain
its definition.
AT_SYMLINK_FOLLOW (since Linux 2.6.18)
By default, linkat(), does not dereference oldpath if it is a
symbolic link (like link()). The flag AT_SYMLINK_FOLLOW can be
specified in flags to cause oldpath to be dereferenced if it is
a symbolic link. If procfs is mounted, this can be used as an
alternative to AT_EMPTY_PATH, like this:
linkat(AT_FDCWD, "/proc/self/fd/<fd>", newdirfd,
newname, AT_SYMLINK_FOLLOW);
Before kernel 2.6.18, the flags argument was unused, and had to be
specified as 0.
See openat(2) for an explanation of the need for linkat().
RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is
set appropriately.
ERRORS
EACCES Write access to the directory containing newpath is denied, or
search permission is denied for one of the directories in the
path prefix of oldpath or newpath. (See also path_resolu‐
tion(7).)
EDQUOT The user's quota of disk blocks on the filesystem has been
exhausted.
EEXIST newpath already exists.
EFAULT oldpath or newpath points outside your accessible address space.
EIO An I/O error occurred.
ELOOP Too many symbolic links were encountered in resolving oldpath or
newpath.
EMLINK The file referred to by oldpath already has the maximum number
of links to it.
ENAMETOOLONG
oldpath or newpath was too long.
ENOENT A directory component in oldpath or newpath does not exist or is
a dangling symbolic link.
ENOMEM Insufficient kernel memory was available.
ENOSPC The device containing the file has no room for the new directory
entry.
ENOTDIR
A component used as a directory in oldpath or newpath is not, in
fact, a directory.
EPERM oldpath is a directory.
EPERM The filesystem containing oldpath and newpath does not support
the creation of hard links.
EPERM (since Linux 3.6)
The caller does not have permission to create a hard link to
this file (see the description of /proc/sys/fs/pro‐
tected_hardlinks in proc(5)).
EROFS The file is on a read-only filesystem.
EXDEV oldpath and newpath are not on the same mounted filesystem.
(Linux permits a filesystem to be mounted at multiple points,
but link() does not work across different mount points, even if
the same filesystem is mounted on both.)
The following additional errors can occur for linkat():
EBADF olddirfd or newdirfd is not a valid file descriptor.
EINVAL An invalid flag value was specified in flags.
ENOENT AT_EMPTY_PATH was specified in flags, but the caller did not
have the CAP_DAC_READ_SEARCH capability.
ENOENT An attempt was made to link to the /proc/self/fd/NN file corre‐
sponding to a file descriptor created with
open(path, O_TMPFILE | O_EXCL, mode);
See open(2).
ENOENT oldpath is a relative pathname and olddirfd refers to a direc‐
tory that has been deleted, or newpath is a relative pathname
and newdirfd refers to a directory that has been deleted.
ENOTDIR
oldpath is relative and olddirfd is a file descriptor referring
to a file other than a directory; or similar for newpath and
newdirfd
EPERM AT_EMPTY_PATH was specified in flags, oldpath is an empty
string, and olddirfd refers to a directory.
VERSIONS
linkat() was added to Linux in kernel 2.6.16; library support was added
to glibc in version 2.4.
CONFORMING TO
link(): SVr4, 4.3BSD, POSIX.1-2001 (but see NOTES), POSIX.1-2008.
linkat(): POSIX.1-2008.
- unlink
NAME
unlink, unlinkat - delete a name and possibly the file it refers to
SYNOPSIS
#include <unistd.h>
int unlink(const char *pathname);
#include <fcntl.h> /* Definition of AT_* constants */
#include <unistd.h>
int unlinkat(int dirfd, const char *pathname, int flags);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
unlinkat():
Since glibc 2.10:
_XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
Before glibc 2.10:
_ATFILE_SOURCE
DESCRIPTION
unlink() deletes a name from the filesystem. If that name was the last
link to a file and no processes have the file open, the file is deleted
and the space it was using is made available for reuse.
If the name was the last link to a file but any processes still have
the file open, the file will remain in existence until the last file
descriptor referring to it is closed.
If the name referred to a symbolic link, the link is removed.
If the name referred to a socket, FIFO, or device, the name for it is
removed but processes which have the object open may continue to use
it.
unlinkat()
The unlinkat() system call operates in exactly the same way as either
unlink() or rmdir(2) (depending on whether or not flags includes the
AT_REMOVEDIR flag) except for the differences described here.
If the pathname given in pathname is relative, then it is interpreted
relative to the directory referred to by the file descriptor dirfd
(rather than relative to the current working directory of the calling
process, as is done by unlink() and rmdir(2) for a relative pathname).
If the pathname given in pathname is relative and dirfd is the special
value AT_FDCWD, then pathname is interpreted relative to the current
working directory of the calling process (like unlink() and rmdir(2)).
If the pathname given in pathname is absolute, then dirfd is ignored.
flags is a bit mask that can either be specified as 0, or by ORing
together flag values that control the operation of unlinkat(). Cur‐
rently only one such flag is defined:
AT_REMOVEDIR
By default, unlinkat() performs the equivalent of unlink() on
pathname. If the AT_REMOVEDIR flag is specified, then performs
the equivalent of rmdir(2) on pathname.
See openat(2) for an explanation of the need for unlinkat().
RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is
set appropriately.
ERRORS
EACCES Write access to the directory containing pathname is not allowed
for the process's effective UID, or one of the directories in
pathname did not allow search permission. (See also path_reso‐
lution(7).)
EBUSY The file pathname cannot be unlinked because it is being used by
the system or another process; for example, it is a mount point
or the NFS client software created it to represent an active but
otherwise nameless inode ("NFS silly renamed").
EFAULT pathname points outside your accessible address space.
EIO An I/O error occurred.
EISDIR pathname refers to a directory. (This is the non-POSIX value
returned by Linux since 2.1.132.)
ELOOP Too many symbolic links were encountered in translating path‐
name.
ENAMETOOLONG
pathname was too long.
ENOENT A component in pathname does not exist or is a dangling symbolic
link, or pathname is empty.
ENOMEM Insufficient kernel memory was available.
ENOTDIR
A component used as a directory in pathname is not, in fact, a
directory.
EPERM The system does not allow unlinking of directories, or unlinking
of directories requires privileges that the calling process
doesn't have. (This is the POSIX prescribed error return; as
noted above, Linux returns EISDIR for this case.)
EPERM (Linux only)
The filesystem does not allow unlinking of files.
EPERM or EACCES
The directory containing pathname has the sticky bit (S_ISVTX)
set and the process's effective UID is neither the UID of the
file to be deleted nor that of the directory containing it, and
the process is not privileged (Linux: does not have the
CAP_FOWNER capability).
EROFS pathname refers to a file on a read-only filesystem.
The same errors that occur for unlink() and rmdir(2) can also occur for
unlinkat(). The following additional errors can occur for unlinkat():
EBADF dirfd is not a valid file descriptor.
EINVAL An invalid flag value was specified in flags.
EISDIR pathname refers to a directory, and AT_REMOVEDIR was not speci‐
fied in flags.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring to
a file other than a directory.
VERSIONS
unlinkat() was added to Linux in kernel 2.6.16; library support was
added to glibc in version 2.4.
CONFORMING TO
unlink(): SVr4, 4.3BSD, POSIX.1-2001, POSIX.1-2008.
unlinkat(): POSIX.1-2008.
7、 remove(标准库函数)
NAME
remove - remove a file or directory
SYNOPSIS
#include <stdio.h>
int remove(const char *pathname);
DESCRIPTION
remove() deletes a name from the filesystem. It calls unlink(2) for
files, and rmdir(2) for directories.
If the removed name was the last link to a file and no processes have
the file open, the file is deleted and the space it was using is made
available for reuse.
If the name was the last link to a file, but any processes still have
the file open, the file will remain in existence until the last file
descriptor referring to it is closed.
If the name referred to a symbolic link, the link is removed.
If the name referred to a socket, FIFO, or device, the name is removed,
but processes which have the object open may continue to use it.
RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is
set appropriately.
ERRORS
The errors that occur are those for unlink(2) and rmdir(2).
ATTRIBUTES
For an explanation of the terms used in this section, see
attributes(7).
┌──────────┬───────────────┬─────────┐
│Interface │ Attribute │ Value │
├──────────┼───────────────┼─────────┤
│remove() │ Thread safety │ MT-Safe │
└──────────┴───────────────┴─────────┘
CONFORMING TO
POSIX.1-2001, POSIX.1-2008, C89, C99, 4.3BSD.
8、rename(标准库函数)
NAME
rename, renameat, renameat2 - change the name or location of a file
SYNOPSIS
#include <stdio.h>
int rename(const char *oldpath, const char *newpath);
#include <fcntl.h> /* Definition of AT_* constants */
#include <stdio.h>
int renameat(int olddirfd, const char *oldpath,
int newdirfd, const char *newpath);
int renameat2(int olddirfd, const char *oldpath,
int newdirfd, const char *newpath, unsigned int flags);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
renameat():
Since glibc 2.10:
_XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
Before glibc 2.10:
_ATFILE_SOURCE
DESCRIPTION
rename() renames a file, moving it between directories if required.
Any other hard links to the file (as created using link(2)) are unaf‐
fected. Open file descriptors for oldpath are also unaffected.
If newpath already exists, it will be atomically replaced (subject to a
few conditions; see ERRORS below), so that there is no point at which
another process attempting to access newpath will find it missing.
If oldpath and newpath are existing hard links referring to the same
file, then rename() does nothing, and returns a success status.
If newpath exists but the operation fails for some reason, rename()
guarantees to leave an instance of newpath in place.
oldpath can specify a directory. In this case, newpath must either not
exist, or it must specify an empty directory.
However, when overwriting there will probably be a window in which both
oldpath and newpath refer to the file being renamed.
If oldpath refers to a symbolic link, the link is renamed; if newpath
refers to a symbolic link, the link will be overwritten.
renameat()
The renameat() system call operates in exactly the same way as
rename(), except for the differences described here.
If the pathname given in oldpath is relative, then it is interpreted
relative to the directory referred to by the file descriptor olddirfd
(rather than relative to the current working directory of the calling
process, as is done by rename() for a relative pathname).
If oldpath is relative and olddirfd is the special value AT_FDCWD, then
oldpath is interpreted relative to the current working directory of the
calling process (like rename()).
If oldpath is absolute, then olddirfd is ignored.
The interpretation of newpath is as for oldpath, except that a relative
pathname is interpreted relative to the directory referred to by the
file descriptor newdirfd.
See openat(2) for an explanation of the need for renameat().
renameat2()
renameat2() has an additional flags argument. A renameat2() call with
a zero flags argument is equivalent to renameat().
The flags argument is a bit mask consisting of zero or more of the fol‐
lowing flags:
RENAME_EXCHANGE
Atomically exchange oldpath and newpath. Both pathnames must
exist but may be of different types (e.g., one could be a non-
empty directory and the other a symbolic link).
RENAME_NOREPLACE
Don't overwrite newpath of the rename. Return an error if new‐
path already exists.
RENAME_NOREPLACE can't be employed together with
RENAME_EXCHANGE.
RENAME_WHITEOUT (since Linux 3.18)
This operation makes sense only for overlay/union filesystem
implementations.
Specifying RENAME_WHITEOUT creates a "whiteout" object at the
source of the rename at the same time as performing the rename.
The whole operation is atomic, so that if the rename succeeds
then the whiteout will also have been created.
A "whiteout" is an object that has special meaning in
union/overlay filesystem constructs. In these constructs, mul‐
tiple layers exist and only the top one is ever modified. A
whiteout on an upper layer will effectively hide a matching file
in the lower layer, making it appear as if the file didn't
exist.
When a file that exists on the lower layer is renamed, the file
is first copied up (if not already on the upper layer) and then
renamed on the upper, read-write layer. At the same time, the
source file needs to be "whiteouted" (so that the version of the
source file in the lower layer is rendered invisible). The
whole operation needs to be done atomically.
When not part of a union/overlay, the whiteout appears as a
character device with a {0,0} device number.
RENAME_WHITEOUT requires the same privileges as creating a
device node (i.e., the CAP_MKNOD capability).
RENAME_WHITEOUT can't be employed together with RENAME_EXCHANGE.
RENAME_WHITEOUT requires support from the underlying filesystem.
Among the filesystems that provide that support are shmem (since
Linux 3.18), ext4 (since Linux 3.18), and XFS (since Linux 4.1).
RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is
set appropriately.
ERRORS
EACCES Write permission is denied for the directory containing oldpath
or newpath, or, search permission is denied for one of the
directories in the path prefix of oldpath or newpath, or oldpath
is a directory and does not allow write permission (needed to
update the .. entry). (See also path_resolution(7).)
EBUSY The rename fails because oldpath or newpath is a directory that
is in use by some process (perhaps as current working directory,
or as root directory, or because it was open for reading) or is
in use by the system (for example as mount point), while the
system considers this an error. (Note that there is no require‐
ment to return EBUSY in such cases—there is nothing wrong with
doing the rename anyway—but it is allowed to return EBUSY if the
system cannot otherwise handle such situations.)
EDQUOT The user's quota of disk blocks on the filesystem has been
exhausted.
EFAULT oldpath or newpath points outside your accessible address space.
EINVAL The new pathname contained a path prefix of the old, or, more
generally, an attempt was made to make a directory a subdirec‐
tory of itself.
EISDIR newpath is an existing directory, but oldpath is not a direc‐
tory.
ELOOP Too many symbolic links were encountered in resolving oldpath or
newpath.
EMLINK oldpath already has the maximum number of links to it, or it was
a directory and the directory containing newpath has the maximum
number of links.
ENAMETOOLONG
oldpath or newpath was too long.
ENOENT The link named by oldpath does not exist; or, a directory compo‐
nent in newpath does not exist; or, oldpath or newpath is an
empty string.
ENOMEM Insufficient kernel memory was available.
ENOSPC The device containing the file has no room for the new directory
entry.
ENOTDIR
A component used as a directory in oldpath or newpath is not, in
fact, a directory. Or, oldpath is a directory, and newpath
exists but is not a directory.
ENOTEMPTY or EEXIST
newpath is a nonempty directory, that is, contains entries other
than "." and "..".
EPERM or EACCES
The directory containing oldpath has the sticky bit (S_ISVTX)
set and the process's effective user ID is neither the user ID
of the file to be deleted nor that of the directory containing
it, and the process is not privileged (Linux: does not have the
CAP_FOWNER capability); or newpath is an existing file and the
directory containing it has the sticky bit set and the process's
effective user ID is neither the user ID of the file to be
replaced nor that of the directory containing it, and the
process is not privileged (Linux: does not have the CAP_FOWNER
capability); or the filesystem containing pathname does not sup‐
port renaming of the type requested.
EROFS The file is on a read-only filesystem.
EXDEV oldpath and newpath are not on the same mounted filesystem.
(Linux permits a filesystem to be mounted at multiple points,
but rename() does not work across different mount points, even
if the same filesystem is mounted on both.)
The following additional errors can occur for renameat() and
renameat2():
EBADF olddirfd or newdirfd is not a valid file descriptor.
ENOTDIR
oldpath is relative and olddirfd is a file descriptor referring
to a file other than a directory; or similar for newpath and
newdirfd
The following additional errors can occur for renameat2():
EEXIST flags contains RENAME_NOREPLACE and newpath already exists.
EINVAL An invalid flag was specified in flags.
EINVAL Both RENAME_NOREPLACE and RENAME_EXCHANGE were specified in
flags.
EINVAL Both RENAME_WHITEOUT and RENAME_EXCHANGE were specified in
flags.
EINVAL The filesystem does not support one of the flags in flags.
ENOENT flags contains RENAME_EXCHANGE and newpath does not exist.
EPERM RENAME_WHITEOUT was specified in flags, but the caller does not
have the CAP_MKNOD capability.
VERSIONS
renameat() was added to Linux in kernel 2.6.16; library support was
added to glibc in version 2.4.
renameat2() was added to Linux in kernel 3.15.
CONFORMING TO
rename(): 4.3BSD, C89, C99, POSIX.1-2001, POSIX.1-2008.
renameat(): POSIX.1-2008.
renameat2() is Linux-specific.
9、symlink
NAME
symlink, symlinkat - make a new name for a file
SYNOPSIS
#include <unistd.h>
int symlink(const char *target, const char *linkpath);
#include <fcntl.h> /* Definition of AT_* constants */
#include <unistd.h>
int symlinkat(const char *target, int newdirfd, const char *linkpath);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
symlink():
_BSD_SOURCE || _XOPEN_SOURCE >= 500 ||
_XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED ||
_POSIX_C_SOURCE >= 200112L
symlinkat():
Since glibc 2.10:
_XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
Before glibc 2.10:
_ATFILE_SOURCE
DESCRIPTION
symlink() creates a symbolic link named linkpath which contains the
string target.
Symbolic links are interpreted at run time as if the contents of the
link had been substituted into the path being followed to find a file
or directory.
Symbolic links may contain .. path components, which (if used at the
start of the link) refer to the parent directories of that in which the
link resides.
A symbolic link (also known as a soft link) may point to an existing
file or to a nonexistent one; the latter case is known as a dangling
link.
The permissions of a symbolic link are irrelevant; the ownership is
ignored when following the link, but is checked when removal or renam‐
ing of the link is requested and the link is in a directory with the
sticky bit (S_ISVTX) set.
If linkpath exists, it will not be overwritten.
symlinkat()
The symlinkat() system call operates in exactly the same way as sym‐
link(), except for the differences described here.
If the pathname given in linkpath is relative, then it is interpreted
relative to the directory referred to by the file descriptor newdirfd
(rather than relative to the current working directory of the calling
process, as is done by symlink() for a relative pathname).
If linkpath is relative and newdirfd is the special value AT_FDCWD,
then linkpath is interpreted relative to the current working directory
of the calling process (like symlink()).
If linkpath is absolute, then newdirfd is ignored.
RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is
set appropriately.
ERRORS
EACCES Write access to the directory containing linkpath is denied, or
one of the directories in the path prefix of linkpath did not
allow search permission. (See also path_resolution(7).)
EDQUOT The user's quota of resources on the filesystem has been
exhausted. The resources could be inodes or disk blocks,
depending on the filesystem implementation.
EEXIST linkpath already exists.
EFAULT target or linkpath points outside your accessible address space.
EIO An I/O error occurred.
ELOOP Too many symbolic links were encountered in resolving linkpath.
ENAMETOOLONG
target or linkpath was too long.
ENOENT A directory component in linkpath does not exist or is a dan‐
gling symbolic link, or target or linkpath is an empty string.
ENOMEM Insufficient kernel memory was available.
ENOSPC The device containing the file has no room for the new directory
entry.
ENOTDIR
A component used as a directory in linkpath is not, in fact, a
directory.
EPERM The filesystem containing linkpath does not support the creation
of symbolic links.
EROFS linkpath is on a read-only filesystem.
The following additional errors can occur for symlinkat():
EBADF newdirfd is not a valid file descriptor.
ENOENT linkpath is a relative pathname and newdirfd refers to a direc‐
tory that has been deleted.
ENOTDIR
linkpath is relative and newdirfd is a file descriptor referring
to a file other than a directory.
VERSIONS
symlinkat() was added to Linux in kernel 2.6.16; library support was
added to glibc in version 2.4.
CONFORMING TO
symlink(): SVr4, 4.3BSD, POSIX.1-2001, POSIX.1-2008.
symlinkat(): POSIX.1-2008.
10、readlink
NAME
readlink, readlinkat - read value of a symbolic link
SYNOPSIS
#include <unistd.h>
ssize_t readlink(const char *pathname, char *buf, size_t bufsiz);
#include <fcntl.h> /* Definition of AT_* constants */
#include <unistd.h>
ssize_t readlinkat(int dirfd, const char *pathname,
char *buf, size_t bufsiz);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
readlink():
_BSD_SOURCE || _XOPEN_SOURCE >= 500 ||
_XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED ||
_POSIX_C_SOURCE >= 200112L
readlinkat():
Since glibc 2.10:
_XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
Before glibc 2.10:
_ATFILE_SOURCE
DESCRIPTION
readlink() places the contents of the symbolic link pathname in the
buffer buf, which has size bufsiz. readlink() does not append a null
byte to buf. It will truncate the contents (to a length of bufsiz
characters), in case the buffer is too small to hold all of the con‐
tents.
readlinkat()
The readlinkat() system call operates in exactly the same way as read‐
link(), except for the differences described here.
If the pathname given in pathname is relative, then it is interpreted
relative to the directory referred to by the file descriptor dirfd
(rather than relative to the current working directory of the calling
process, as is done by readlink() for a relative pathname).
If pathname is relative and dirfd is the special value AT_FDCWD, then
pathname is interpreted relative to the current working directory of
the calling process (like readlink()).
If pathname is absolute, then dirfd is ignored.
Since Linux 2.6.39, pathname can be an empty string, in which case the
call operates on the symbolic link referred to by dirfd (which should
have been obtained using open(2) with the O_PATH and O_NOFOLLOW flags).
See openat(2) for an explanation of the need for readlinkat().
RETURN VALUE
On success, these calls return the number of bytes placed in buf. On
error, -1 is returned and errno is set to indicate the error.
ERRORS
EACCES Search permission is denied for a component of the path prefix.
(See also path_resolution(7).)
EFAULT buf extends outside the process's allocated address space.
EINVAL bufsiz is not positive.
EINVAL The named file is not a symbolic link.
EIO An I/O error occurred while reading from the filesystem.
ELOOP Too many symbolic links were encountered in translating the
pathname.
ENAMETOOLONG
A pathname, or a component of a pathname, was too long.
ENOENT The named file does not exist.
ENOMEM Insufficient kernel memory was available.
ENOTDIR
A component of the path prefix is not a directory.
The following additional errors can occur for readlinkat():
EBADF dirfd is not a valid file descriptor.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring to
a file other than a directory.
VERSIONS
readlinkat() was added to Linux in kernel 2.6.16; library support was
added to glibc in version 2.4.
CONFORMING TO
readlink(): 4.4BSD (readlink() first appeared in 4.2BSD), POSIX.1-2001,
POSIX.1-2008.
readlinkat(): POSIX.1-2008.
- utime
NAME
utime, utimes - change file last access and modification times
SYNOPSIS
#include <sys/types.h>
#include <utime.h>
int utime(const char *filename, const struct utimbuf *times);
#include <sys/time.h>
int utimes(const char *filename, const struct timeval times[2]);
DESCRIPTION
Note: modern applications may prefer to use the interfaces described in
utimensat(2).
The utime() system call changes the access and modification times of
the inode specified by filename to the actime and modtime fields of
times respectively.
If times is NULL, then the access and modification times of the file
are set to the current time.
Changing timestamps is permitted when: either the process has appropri‐
ate privileges, or the effective user ID equals the user ID of the
file, or times is NULL and the process has write permission for the
file.
The utimbuf structure is:
struct utimbuf {
time_t actime; /* access time */
time_t modtime; /* modification time */
};
The utime() system call allows specification of timestamps with a reso‐
lution of 1 second.
The utimes() system call is similar, but the times argument refers to
an array rather than a structure. The elements of this array are
timeval structures, which allow a precision of 1 microsecond for speci‐
fying timestamps. The timeval structure is:
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds */
};
times[0] specifies the new access time, and times[1] specifies the new
modification time. If times is NULL, then analogously to utime(), the
access and modification times of the file are set to the current time.
RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is
set appropriately.
ERRORS
EACCES Search permission is denied for one of the directories in the
path prefix of path (see also path_resolution(7)).
EACCES times is NULL, the caller's effective user ID does not match the
owner of the file, the caller does not have write access to the
file, and the caller is not privileged (Linux: does not have
either the CAP_DAC_OVERRIDE or the CAP_FOWNER capability).
ENOENT filename does not exist.
EPERM times is not NULL, the caller's effective UID does not match the
owner of the file, and the caller is not privileged (Linux: does
not have the CAP_FOWNER capability).
EROFS path resides on a read-only filesystem.
CONFORMING TO
utime(): SVr4, POSIX.1-2001. POSIX.1-2008 marks utime() as obsolete.
utimes(): 4.3BSD, POSIX.1-2001.
11、 mkdir rmdir
NAME
mkdir, mkdirat - create a directory
SYNOPSIS
#include <sys/stat.h>
#include <sys/types.h>
int mkdir(const char *pathname, mode_t mode);
#include <fcntl.h> /* Definition of AT_* constants */
#include <sys/stat.h>
int mkdirat(int dirfd, const char *pathname, mode_t mode);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
mkdirat():
Since glibc 2.10:
_XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
Before glibc 2.10:
_ATFILE_SOURCE
DESCRIPTION
mkdir() attempts to create a directory named pathname.
The argument mode specifies the mode for the new directory (see
stat(2)). It is modified by the process's umask in the usual way: in
the absence of a default ACL, the mode of the created directory is
(mode & ~umask & 0777). Whether other mode bits are honored for the
created directory depends on the operating system. For Linux, see
NOTES below.
The newly created directory will be owned by the effective user ID of
the process. If the directory containing the file has the set-group-ID
bit set, or if the filesystem is mounted with BSD group semantics
(mount -o bsdgroups or, synonymously mount -o grpid), the new directory
will inherit the group ownership from its parent; otherwise it will be
owned by the effective group ID of the process.
If the parent directory has the set-group-ID bit set, then so will the
newly created directory.
mkdirat()
The mkdirat() system call operates in exactly the same way as mkdir(),
except for the differences described here.
If the pathname given in pathname is relative, then it is interpreted
relative to the directory referred to by the file descriptor dirfd
(rather than relative to the current working directory of the calling
process, as is done by mkdir() for a relative pathname).
If pathname is relative and dirfd is the special value AT_FDCWD, then
pathname is interpreted relative to the current working directory of
the calling process (like mkdir()).
If pathname is absolute, then dirfd is ignored.
See openat(2) for an explanation of the need for mkdirat().
RETURN VALUE
mkdir() and mkdirat() return zero on success, or -1 if an error
occurred (in which case, errno is set appropriately).
ERRORS
EACCES The parent directory does not allow write permission to the
process, or one of the directories in pathname did not allow
search permission. (See also path_resolution(7).)
EDQUOT The user's quota of disk blocks or inodes on the filesystem has
been exhausted.
EEXIST pathname already exists (not necessarily as a directory). This
includes the case where pathname is a symbolic link, dangling or
not.
EFAULT pathname points outside your accessible address space.
ELOOP Too many symbolic links were encountered in resolving pathname.
EMLINK The number of links to the parent directory would exceed
LINK_MAX.
ENAMETOOLONG
pathname was too long.
ENOENT A directory component in pathname does not exist or is a dan‐
gling symbolic link.
ENOMEM Insufficient kernel memory was available.
ENOSPC The device containing pathname has no room for the new direc‐
tory.
ENOSPC The new directory cannot be created because the user's disk
quota is exhausted.
ENOTDIR
A component used as a directory in pathname is not, in fact, a
directory.
EPERM The filesystem containing pathname does not support the creation
of directories.
EROFS pathname refers to a file on a read-only filesystem.
The following additional errors can occur for mkdirat():
EBADF dirfd is not a valid file descriptor.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring to
a file other than a directory.
VERSIONS
mkdirat() was added to Linux in kernel 2.6.16; library support was
added to glibc in version 2.4.
CONFORMING TO
mkdir(): SVr4, BSD, POSIX.1-2001, POSIX.1-2008.
mkdirat(): POSIX.1-2008.
rmdir
NAME
rmdir - delete a directory
SYNOPSIS
#include <unistd.h>
int rmdir(const char *pathname);
DESCRIPTION
rmdir() deletes a directory, which must be empty.
RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is
set appropriately.
ERRORS
EACCES Write access to the directory containing pathname was not
allowed, or one of the directories in the path prefix of path‐
name did not allow search permission. (See also path_resolu‐
tion(7).
EBUSY pathname is currently in use by the system or some process that
prevents its removal. On Linux this means pathname is currently
used as a mount point or is the root directory of the calling
process.
EFAULT pathname points outside your accessible address space.
EINVAL pathname has . as last component.
ELOOP Too many symbolic links were encountered in resolving pathname.
ENAMETOOLONG
pathname was too long.
ENOENT A directory component in pathname does not exist or is a dan‐
gling symbolic link.
ENOMEM Insufficient kernel memory was available.
ENOTDIR
pathname, or a component used as a directory in pathname, is
not, in fact, a directory.
ENOTEMPTY
pathname contains entries other than . and .. ; or, pathname has
.. as its final component. POSIX.1 also allows EEXIST for this
condition.
EPERM The directory containing pathname has the sticky bit (S_ISVTX)
set and the process's effective user ID is neither the user ID
of the file to be deleted nor that of the directory containing
it, and the process is not privileged (Linux: does not have the
CAP_FOWNER capability).
EPERM The filesystem containing pathname does not support the removal
of directories.
EROFS pathname refers to a directory on a read-only filesystem.
CONFORMING TO
POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD.
BUGS
Infelicities in the protocol underlying NFS can cause the unexpected
disappearance of directories which are still being used.
12、 opendir readdir
DIR *opendir(const char *name);
struct dirent *readdir(DIR *dirp);
NAME
opendir, fdopendir - open a directory
SYNOPSIS
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
DIR *fdopendir(int fd);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
fdopendir():
Since glibc 2.10:
_XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
Before glibc 2.10:
_GNU_SOURCE
DESCRIPTION
The opendir() function opens a directory stream corresponding to the
directory name, and returns a pointer to the directory stream. The
stream is positioned at the first entry in the directory.
The fdopendir() function is like opendir(), but returns a directory
stream for the directory referred to by the open file descriptor fd.
After a successful call to fdopendir(), fd is used internally by the
implementation, and should not otherwise be used by the application.
RETURN VALUE
The opendir() and fdopendir() functions return a pointer to the direc‐
tory stream. On error, NULL is returned, and errno is set appropri‐
ately.
ERRORS
EACCES Permission denied.
EBADF fd is not a valid file descriptor opened for reading.
EMFILE The per-process limit on the number of open file descriptors has
been reached.
ENFILE The system-wide limit on the total number of open files has been
reached.
ENOENT Directory does not exist, or name is an empty string.
ENOMEM Insufficient memory to complete the operation.
ENOTDIR
name is not a directory.
VERSIONS
fdopendir() is available in glibc since version 2.4.
ATTRIBUTES
For an explanation of the terms used in this section, see
attributes(7).
┌───────────────────────┬───────────────┬─────────┐
│Interface │ Attribute │ Value │
├───────────────────────┼───────────────┼─────────┤
│opendir(), fdopendir() │ Thread safety │ MT-Safe │
└───────────────────────┴───────────────┴─────────┘
CONFORMING TO
opendir() is present on SVr4, 4.3BSD, and specified in POSIX.1-2001.
fdopendir() is specified in POSIX.1-2008.
readdir
NAME
readdir, readdir_r - read a directory
SYNOPSIS
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
readdir_r():
_POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _BSD_SOURCE ||
_SVID_SOURCE || _POSIX_SOURCE
DESCRIPTION
The readdir() function returns a pointer to a dirent structure repre‐
senting the next directory entry in the directory stream pointed to by
dirp. It returns NULL on reaching the end of the directory stream or
if an error occurred.
On Linux, the dirent structure is defined as follows:
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* not an offset; see NOTES */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file; not supported
by all filesystem types */
char d_name[256]; /* filename */
};
The only fields in the dirent structure that are mandated by POSIX.1
are: d_name[], of unspecified size, with at most NAME_MAX characters
preceding the terminating null byte ('\0'); and (as an XSI extension)
d_ino. The other fields are unstandardized, and not present on all
systems; see NOTES below for some further details.
The data returned by readdir() may be overwritten by subsequent calls
to readdir() for the same directory stream.
The readdir_r() function is a reentrant version of readdir(). It reads
the next directory entry from the directory stream dirp, and returns it
in the caller-allocated buffer pointed to by entry. (See NOTES for
information on allocating this buffer.) A pointer to the returned item
is placed in *result; if the end of the directory stream was encoun‐
tered, then NULL is instead returned in *result.
RETURN VALUE
On success, readdir() returns a pointer to a dirent structure. (This
structure may be statically allocated; do not attempt to free(3) it.)
If the end of the directory stream is reached, NULL is returned and
errno is not changed. If an error occurs, NULL is returned and errno
is set appropriately.
The readdir_r() function returns 0 on success. On error, it returns a
positive error number (listed under ERRORS). If the end of the direc‐
tory stream is reached, readdir_r() returns 0, and returns NULL in
*result.
ERRORS
EBADF Invalid directory stream descriptor dirp.
ATTRIBUTES
For an explanation of the terms used in this section, see
attributes(7).
┌────────────┬───────────────┬──────────────────────────┐
│Interface │ Attribute │ Value │
├────────────┼───────────────┼──────────────────────────┤
│readdir() │ Thread safety │ MT-Unsafe race:dirstream │
├────────────┼───────────────┼──────────────────────────┤
│readdir_r() │ Thread safety │ MT-Safe │
└────────────┴───────────────┴──────────────────────────┘
CONFORMING TO
POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD.
13 rewinddir seekdir telldir
- rewinddir
NAME
rewinddir - reset directory stream
SYNOPSIS
#include <sys/types.h>
#include <dirent.h>
void rewinddir(DIR *dirp);
DESCRIPTION
The rewinddir() function resets the position of the directory stream
dirp to the beginning of the directory.
RETURN VALUE
The rewinddir() function returns no value.
ATTRIBUTES
For an explanation of the terms used in this section, see
attributes(7).
┌────────────┬───────────────┬─────────┐
│Interface │ Attribute │ Value │
├────────────┼───────────────┼─────────┤
│rewinddir() │ Thread safety │ MT-Safe │
└────────────┴───────────────┴─────────┘
CONFORMING TO
POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD.
- seekdir
NAME
seekdir - set the position of the next readdir() call in the directory
stream.
SYNOPSIS
#include <dirent.h>
void seekdir(DIR *dirp, long loc);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
seekdir(): _BSD_SOURCE || _SVID_SOURCE || _XOPEN_SOURCE
DESCRIPTION
The seekdir() function sets the location in the directory stream from
which the next readdir(2) call will start. The loc argument should be
a value returned by a previous call to telldir(3).
RETURN VALUE
The seekdir() function returns no value.
ATTRIBUTES
For an explanation of the terms used in this section, see
attributes(7).
┌──────────┬───────────────┬─────────┐
│Interface │ Attribute │ Value │
├──────────┼───────────────┼─────────┤
│seekdir() │ Thread safety │ MT-Safe │
└──────────┴───────────────┴─────────┘
CONFORMING TO
POSIX.1-2001, POSIX.1-2008, 4.3BSD.
- telldir
NAME
telldir - return current location in directory stream
SYNOPSIS
#include <dirent.h>
long telldir(DIR *dirp);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
telldir(): _BSD_SOURCE || _SVID_SOURCE || _XOPEN_SOURCE
DESCRIPTION
The telldir() function returns the current location associated with the
directory stream dirp.
RETURN VALUE
On success, the telldir() function returns the current location in the
directory stream. On error, -1 is returned, and errno is set appropri‐
ately.
ERRORS
EBADF Invalid directory stream descriptor dirp.
ATTRIBUTES
For an explanation of the terms used in this section, see
attributes(7).
┌──────────┬───────────────┬─────────┐
│Interface │ Attribute │ Value │
├──────────┼───────────────┼─────────┤
│telldir() │ Thread safety │ MT-Safe │
└──────────┴───────────────┴─────────┘
CONFORMING TO
POSIX.1-2001, POSIX.1-2008, 4.3BSD.
14、 closedir
closedir
NAME
closedir - close a directory
SYNOPSIS
#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);
DESCRIPTION
The closedir() function closes the directory stream associated with
dirp. A successful call to closedir() also closes the underlying file
descriptor associated with dirp. The directory stream descriptor dirp
is not available after this call.
RETURN VALUE
The closedir() function returns 0 on success. On error, -1 is
returned, and errno is set appropriately.
ERRORS
EBADF Invalid directory stream descriptor dirp.
ATTRIBUTES
For an explanation of the terms used in this section, see
attributes(7).
┌───────────┬───────────────┬─────────┐
│Interface │ Attribute │ Value │
├───────────┼───────────────┼─────────┤
│closedir() │ Thread safety │ MT-Safe │
└───────────┴───────────────┴─────────┘
CONFORMING TO
POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD.
15、 进程当前目录 getcwd chdir/fchdir
- 获取当前目录
NAME
getcwd, getwd, get_current_dir_name - get current working directory
SYNOPSIS
#include <unistd.h>
char *getcwd(char *buf, size_t size);
char *getwd(char *buf);
char *get_current_dir_name(void);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
get_current_dir_name():
_GNU_SOURCE
getwd():
Since glibc 2.12:
_BSD_SOURCE ||
(_XOPEN_SOURCE >= 500 ||
_XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED) &&
!(_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700)
Before glibc 2.12:
_BSD_SOURCE || _XOPEN_SOURCE >= 500 ||
_XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED
DESCRIPTION
These functions return a null-terminated string containing an absolute
pathname that is the current working directory of the calling process.
The pathname is returned as the function result and via the argument
buf, if present.
If the current directory is not below the root directory of the current
process (e.g., because the process set a new filesystem root using
chroot(2) without changing its current directory into the new root),
then, since Linux 2.6.36, the returned path will be prefixed with the
string "(unreachable)". Such behavior can also be caused by an unpriv‐
ileged user by changing the current directory into another mount names‐
pace. When dealing with paths from untrusted sources, callers of these
functions should consider checking whether the returned path starts
with '/' or '(' to avoid misinterpreting an unreachable path as a rela‐
tive path.
The getcwd() function copies an absolute pathname of the current work‐
ing directory to the array pointed to by buf, which is of length size.
If the length of the absolute pathname of the current working direc‐
tory, including the terminating null byte, exceeds size bytes, NULL is
returned, and errno is set to ERANGE; an application should check for
this error, and allocate a larger buffer if necessary.
As an extension to the POSIX.1-2001 standard, glibc's getcwd() allo‐
cates the buffer dynamically using malloc(3) if buf is NULL. In this
case, the allocated buffer has the length size unless size is zero,
when buf is allocated as big as necessary. The caller should free(3)
the returned buffer.
get_current_dir_name() will malloc(3) an array big enough to hold the
absolute pathname of the current working directory. If the environment
variable PWD is set, and its value is correct, then that value will be
returned. The caller should free(3) the returned buffer.
getwd() does not malloc(3) any memory. The buf argument should be a
pointer to an array at least PATH_MAX bytes long. If the length of the
absolute pathname of the current working directory, including the ter‐
minating null byte, exceeds PATH_MAX bytes, NULL is returned, and errno
is set to ENAMETOOLONG. (Note that on some systems, PATH_MAX may not
be a compile-time constant; furthermore, its value may depend on the
filesystem, see pathconf(3).) For portability and security reasons,
use of getwd() is deprecated.
RETURN VALUE
On success, these functions return a pointer to a string containing the
pathname of the current working directory. In the case getcwd() and
getwd() this is the same value as buf.
On failure, these functions return NULL, and errno is set to indicate
the error. The contents of the array pointed to by buf are undefined
on error.
ERRORS
EACCES Permission to read or search a component of the filename was
denied.
EFAULT buf points to a bad address.
EINVAL The size argument is zero and buf is not a null pointer.
EINVAL getwd(): buf is NULL.
ENAMETOOLONG
getwd(): The size of the null-terminated absolute pathname
string exceeds PATH_MAX bytes.
ENOMEM Out of memory.
ENOENT The current working directory has been unlinked.
ERANGE The size argument is less than the length of the absolute path‐
name of the working directory, including the terminating null
byte. You need to allocate a bigger array and try again.
ATTRIBUTES
For an explanation of the terms used in this section, see
attributes(7).
┌───────────────────────┬───────────────┬─────────────┐
│Interface │ Attribute │ Value │
├───────────────────────┼───────────────┼─────────────┤
│getcwd(), getwd() │ Thread safety │ MT-Safe │
├───────────────────────┼───────────────┼─────────────┤
│get_current_dir_name() │ Thread safety │ MT-Safe env │
└───────────────────────┴───────────────┴─────────────┘
CONFORMING TO
getcwd() conforms to POSIX.1-2001. Note however that POSIX.1-2001
leaves the behavior of getcwd() unspecified if buf is NULL.
getwd() is present in POSIX.1-2001, but marked LEGACY. POSIX.1-2008
removes the specification of getwd(). Use getcwd() instead.
POSIX.1-2001 does not define any errors for getwd().
get_current_dir_name() is a GNU extension.
- 修改当前目录
NAME
chdir, fchdir - change working directory
SYNOPSIS
#include <unistd.h>
int chdir(const char *path);
int fchdir(int fd);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
fchdir():
_BSD_SOURCE || _XOPEN_SOURCE >= 500 ||
_XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED
|| /* Since glibc 2.12: */ _POSIX_C_SOURCE >= 200809L
DESCRIPTION
chdir() changes the current working directory of the calling process to
the directory specified in path.
fchdir() is identical to chdir(); the only difference is that the
directory is given as an open file descriptor.
RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is
set appropriately.
ERRORS
Depending on the filesystem, other errors can be returned. The more
general errors for chdir() are listed below:
EACCES Search permission is denied for one of the components of path.
(See also path_resolution(7).)
EFAULT path points outside your accessible address space.
EIO An I/O error occurred.
ELOOP Too many symbolic links were encountered in resolving path.
ENAMETOOLONG
path is too long.
ENOENT The file does not exist.
ENOMEM Insufficient kernel memory was available.
ENOTDIR
A component of path is not a directory.
The general errors for fchdir() are listed below:
EACCES Search permission was denied on the directory open on fd.
EBADF fd is not a valid file descriptor.
CONFORMING TO
POSIX.1-2001, POSIX.1-2008, SVr4, 4.4BSD.