我正在寻找一种方法来检查并确保文件可读、可写并且存在,如果不是,我想打印一条消息说明这一点。我相信我正在寻找的信息可以使用 fstat() 找到,我只是不知道获取它的正确方法。
如果我尝试使用 O_RDRW 打开不可读、不可写或不存在的文件,则 open 设置了特定的 errno,我认为这将是理想的解决方案。
这是我尝试过的:
//function to open the file
int f_open(const char *filename){
int fid;
if ((fid = open (filename, O_RDWR)) < -1){
return -1;
}
struct stat fileStat;
if (fstat(fid, &fileStat) < 0){
return -1;
}
//check write permission
if (!S_IWUSR(fileStat.st_mode)){
printf("Not writeable\n");
return -1;
}
//check read permissions
if (!S_IRUSR(fileStat.st_mode)){
printf("Not readable\n");
return -1;
}
return fid;
}
我在尝试编译时收到以下错误:
tester.c: In function 'f_open':
tester.c:56:14: error: called object '128' is not a function
tester.c:60:14: error: called object '256' is not a function