检查文件、目录是否存在,检查文件是否为空

1 检查文件是否存在

int checkDirFile(char* path) {
    struct stat fStatus;
    memset(&fStatus, 0, sizeof(fStatus));
    int ret = stat(path, &fStatus);
    printf("retValue = %d\n", ret);
    if (0 != ret) { // file not exists
        printf("%s not exist\n", path);
        return -1;
    }
    printf("%s exist\n", path);
    return 0;
}

2 检查文件是否为空

int checkFileNull(char* filePath) {
    FILE *fp = fopen(filePath, "r");
    if (NULL == fp) {
        fprintf(stdout, "[%s]open file %s NG\n", __FUNCTION__, filePath);
        return -1;
    }
    /*判断文件是否为空*/
#if 1
    if (EOF == fgetc(fp)) {/*读取一个字符,判断是否是结束符号*/
        fprintf(stdout, "file1 [%s] is NULL \n", filePath);
        return -1;
    }
    fprintf(stdout, "file1 [%s] is not NULL \n", filePath);
    fseek(fp, 0, SEEK_SET); /*将文件指针指向开头*/
 #else
    /*判别文件是否为空,若文件指针指向文件开头时,此方法判断失败*/
    /*在读完文件的最后一个字符后,fp->flag仍然没有被置为_IOEOF,因而feof()仍然没有探测到文件结尾。
     直到再次调用fgetc()执行读操作,feof()才能探测到文件结尾。这样就多执行了一次。
     对于feof()这个函数, 它是先读再判断是否到文件尾, 也就是说在它之前一定要读一次才能做出判断。*/
    /*以下方法在判断新打开文件时,不能正确判断不建议使用以下方法*/
    if (EOF == feof(fp)) {
        fprintf(stdout, "file2 [%s] is NULL\n", filePath);
        return -1;
    }
    fprintf(stdout, "file2 [%s] is not NULL\n", filePath);
#endif
    fclose(fp);
    return 0;
}

 

转载于:https://www.cnblogs.com/Chris83/p/9523259.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值