我可以检查两个FILE *或文件描述符号是否指向同一个文件?
我有一个程序从文件读取并写入文件。 我想阻止用户为两者指定相同的文件(出于显而易见的原因)。 让我们说第一个路径在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"); }
编辑:
我不想比较文件名,因为人们很容易通过/asdf/./asdf
或使用符号链接等路径来/asdf/./asdf
。 最终,我不想将我的输出写入我正在阅读的文件中(可能会导致严重的问题)。
是 – 比较文件设备ID和inode。 根据
规范 :
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); }