/* obtaining the metadata of a file */ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> int stat (const char *path, struct stat *buf); int fstat (int fd, struct stat *buf); int lstat (const char *path, struct stat *buf);
注意:lstat函數能夠獲取 符號連接的文件元數據,lstat() returns information about the link itself and not the target filenode
struct stat { dev_t st_dev; /* ID of device containing file */ ino_t st_ino; /* inode number */ mode_t st_mode; /* permissions */ 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 blocks allocated */ time_t st_atime; /* last access time */ time_t st_mtime; /* last modification time */ time_t st_ctime; /* last status change time */ };
/* creates a directory stream representing the directory given by name */ #include <sys/types.h> #include <dirent.h> DIR * opendir (const char *name);
/* returns the next entry in the directory represented by dir */ #include <sys/types.h> #include <dirent.h> struct dirent * readdir (DIR *dir);
/* closes the directory stream represented by dir */ #include <sys/types.h> #include <dirent.h> int closedir (DIR *dir);
/* * find_file_in_dir - searches the directory 'path' for a * file named 'file'. * * Returns 0 if 'file' exists in 'path' and a nonzero * value otherwise. */ int find_file_in_dir (const char *path, const char *file) { struct dirent *entry; int ret = 1; DIR *dir; dir = opendir (path); errno = 0; while ((entry = readdir (dir)) != NULL) { if (strcmp(entry->d_name, file) == 0) { ret = 0; break; } } if (errno && !entry) perror ("readdir"); closedir (dir); return ret; }
/* creates a new link under the path newpath for the existing file oldpath */ #include <unistd.h> int link (const char *oldpath, const char *newpath);
/* creates the symbolic link newpath pointing at the target oldpath */ #include <unistd.h> int symlink (const char *oldpath, const char *newpath);
解鏈:數據結構
#include <unistd.h> int unlink (const char *pathname);
1). Open src. 2). Open dst, creating it if it does not exist, and truncating it to zero length if it does exist. 3). Read a chunk of src into memory. 4). Write the chunk to dst. 5). Continue until all of src has been read and written to dst. 6). Close dst. 7). Close src.