我有一个程序从文件读取并写入文件.我想阻止用户为两者指定相同的文件(出于显而易见的原因).让我们说第一条路径在char* path1,第二条路径在char* path2.我可以fopen()两个路径,fileno()每个呼叫,并得到相同的号码?
为了更清楚地解释:
char* path1 = "/asdf"
char* path2 = "/asdf"
FILE* f1 = fopen(path1, "r");
FILE* f2 = fopen(path2, "w");
int fd1 = fileno(f1);
int fd2 = fileno(f2);
if(fd1 == fd2) {
printf("These are the same file, you really shouldn't do this\n");
}
Run Code Online (Sandbox Code Playgroud)
我不想比较文件名,因为人们很容易通过类似路径/asdf/./asdf或使用符号链接来破坏它们.最终,我不想将我的输出写入我正在阅读的文件中(可能会导致严重的问题).
nne*_*neo 22
是 - 比较文件设备ID和inode.根据<sys/stat.h>规格:
st_ino和st_dev字段一起唯一标识系统中的文件.
使用
int same_file(int fd1, int fd2) {
struct stat stat1, stat2;
if(fstat(fd1, &stat1) < 0) return -1;
if(fstat(fd2, &stat2) < 0) return -1;
return (stat1.st_dev == stat2.st_dev) && (stat1.st_ino == stat2.st_ino);
}
Run Code Online (Sandbox Code Playgroud)