如何检查文件夹C中是否存在文件

时间:2014-02-19 11:10:42

标签: c

我是C初学者,我对如何做到这一点感到有点困惑。我正在尝试使用readdirstrcmp函数,但它会给我带来很多错误。

#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <dirent.h>

int main(int argc, char *argv[])
{   
    DIR *dirp;
    struct dirent *direntp;

    dirp = opendir(argv[1]);
    if (dirp == NULL)
    {
        printf("File could not be open\n");

        return -1;
    }

    int i = 0;
    while((direntp[i]=readdir(dirp)) != NULL)
    {
        if(strcmp(direntp[i], argv[2]) == 0)
        {
            printf("The file %d is in directory %s my friend!", argv[2], dirp);
        }

        i++;
    }

    closedir(dirp);
    return 0;
}

3 个答案:

答案 0 :(得分:3)

read about access

if(access("myfile.txt", F_OK)) {
     // file exists
}

答案 1 :(得分:0)

尝试以这样的读取模式打开文件,

FILE *f;
f=fopen("file.txt","r");

if(f is not empty)
  //file exits

答案 2 :(得分:0)

int main(int argc, char *argv[]){
    DIR *dirp;
    struct dirent *direntp;

    dirp=opendir(argv[1]);
    if (dirp == NULL){
        printf("File could not be open\n");
        return -1;
    }

    while((direntp=readdir(dirp)) != NULL){
        if(strcmp(direntp->d_name,argv[2]) == 0){
            printf("The file %s is in directory %s my friend!", argv[2], argv[1]);
            break;
        }
    }

    closedir(dirp);
    return 0;
}