我可以检查两个FILE *或文件描述符数字指的是相同的文件? [英] Can I check if two FILE* or file descriptor numbers refer to the same file?

查看:140
本文介绍了我可以检查两个FILE *或文件描述符数字指的是相同的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,从文件中读取和写入文件。我想prevent从指定为同一个文件(原因很明显)用户。比方说第一条路径是的char *路径1 和第二条路径是的char *路径2 。我可以 fopen()函数两条路径,调用每个的fileno()并获得相同的号码?

I have a program that reads from a file and writes to a file. I'd like to prevent the user from specifying the same file for both (for obvious reasons). Lets say the first path is in char* path1 and the second path is in char* path2. can I fopen() both paths, call fileno() on each and get the same number?

要解释清楚:

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");
}

编辑:

我不希望比较的文件名,因为人们可以轻松击败了像 /航空自卫队航空自卫队/./ 或使用符号链接路径。最终,我不想写我的输出转换成我是从读文件(可能会导致严重的问题)。

I do not want to compare filenames because one could easily defeat that with paths like /asdf/./asdf or by using symlinks. Ultimately, I do not want to write my output into the file that I'm reading from (could cause serious issues).

推荐答案

是 - 比较文件的设备ID和inode。按照<一个href=\"http://pubs.opengroup.org/onlinepubs/009696699/basedefs/sys/stat.h.html\"><$c$c><sys/stat.h>规格:

Yes - compare the file device ID and inode. Per the <sys/stat.h> specification:

采取的st_ino中和st_dev字段一起唯一地标识系统内的文件

The st_ino and st_dev fields taken together uniquely identify the file within the system.

使用

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);
}

这篇关于我可以检查两个FILE *或文件描述符数字指的是相同的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆