繁体   English   中英

检查文件是否匹配的程序

[英]program that checks if the files match

我的程序检查两个文件(具有不同的路径/名称)是否匹配。 遵循文件之间的硬链接和符号链接来确定它。

如果我要比较的文件是设备文件,我如何修改程序以查看会发生什么? 还是目录? 两者似乎都是有效的用途。 同时检查设备

#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>

void printUsage()
{
    printf("Use: ./leg <name_file1> <name_file2>.\n");
}

int createStat(const char *file, struct stat *fileStat)
{
    if (stat(file, fileStat) < 0)
    {
        fprintf(stderr,"Error! File %s does not exist.\n", file);
        return 0;
    }
    return 1;
}

int main(int argc, char **argv)
{
    if (argc < 3)
    {    
        printf("Insufficient number of parameters.\n");
        printUsage();
        return -1;
    }

    struct stat fileStat1;
    struct stat fileStat2;
    if (createStat(argv[1], &fileStat1) == 0)
    {
        return -1;
    }
    if (createStat(argv[2], &fileStat2) == 0)
    {
        return -1;
    }
    if (S_ISREG(fileStat1.st_mode) && S_ISREG(fileStat2.st_mode)) {
        if ((fileStat1.st_dev == fileStat2.st_dev) && (fileStat1.st_ino == fileStat2.st_ino)) {
            printf("Files '%s' and '%s' coincide.\n", argv[1], argv[2]);
        } else
            printf("Files '%s' and '%s' do not match.\n", argv[1], argv[2]);
    } else
        fprintf(stderr,"'%s' and '%s' there are no files.\n", argv[1], argv[2]);

    return 0;
}

对于常规文件和目录,比较st_devst_ino字段就足够了。

对于表示字符或块设备的路径,比较st_devst_ino字段将告诉您它们是否是同一个文件,即:指向同一目录条目的不同路径,包括符号链接间接。 比较st_rdev字段将判断它们是否代表相同的设备,这也很有用,但有所不同。

还要注意fprintf(stderr,"Error! File %s does not exist.\n", file); 可能会产生误导信息: access失败可能是由其他原因引起的。 以这种方式生成正确的消息既简单又高效:

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int createStat(const char *file, struct stat *fileStat) {
    if (stat(file, fileStat) < 0) {
        fprintf(stderr, "Cannot stat file %s: %s\n", file, strerror(errno));
        return 0;
    }
    return 1;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM