Can I check if two FILE* or file descriptor numbers refer to the same file?

后端 未结 1 833
轻奢々
轻奢々 2021-01-12 01:29

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

相关标签:
1条回答
  • 2021-01-12 02:13

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

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

    Use

    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);
    }
    
    0 讨论(0)
提交回复
热议问题