当您使用stat或fstat时,您需要声明一个struct stat变量,如 struct stat var . stat 结构有一个名为 st_mode 的成员,它具有哪种文件的信息 .
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 file system I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
};
1
目录也是Unix *中的文件,如果要避免通过 open() 打开目录,则可能需要检查文件类型 . 正如@nayabbashasayed所说,您可以使用 stat 来检查文件类型和更多信息 .
以下是通过 stat 检查类型的示例代码:
const char *filePath;
struct stat fileStatBuf;
if(stat(filePath,&fileStatBuf) == -1){
perror("stat");
exit(1);
}
/*
*You can use switch to check all
*the types you want, now i just use
*if to check one.
*/
if((fileStatBuf.st_mode & S_IFMT) == S_IFDIR){
printf("This type is directory\n");
}
3 回答
目录也是一个文件(就Unix / Linux而言) . 所以一般来说你不会得到错误 . 您可以使用stat或fstat函数来跟踪普通或特殊文件 .
当您使用stat或fstat时,您需要声明一个struct stat变量,如
struct stat var
.stat
结构有一个名为st_mode
的成员,它具有哪种文件的信息 .目录也是Unix *中的文件,如果要避免通过
open()
打开目录,则可能需要检查文件类型 . 正如@nayabbashasayed所说,您可以使用stat
来检查文件类型和更多信息 .以下是通过
stat
检查类型的示例代码:希望能帮到你 .
我不想使用其他任何东西作为读写,我发现使用 read() 而不是open()返回错误