【问题标题】:How to check if a file exists in a folder C [closed]如何检查文件夹C中是否存在文件[关闭]
【发布时间】:2014-02-19 11:10:41
【问题描述】:

我是一个 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;
}

【问题讨论】:

  • 首先你必须用谷歌搜索你的问题,如果你遇到任何错误,然后在你的问题中发布你的代码和错误列表。 stackoverflow.com/q/230062/3184380
  • 看看:Similar Question
  • 另外,您的目录内容迭代器很烂。在您的情况下,您还应该检查 direntp[i] 是否实际上是一个文件 - if (direntp[i]-&gt;d_type == DT_REG) {}。正如我前段时间建议的那样here

标签: c


【解决方案1】:
read about access

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

【讨论】:

  • int access(const char *path, int amode) - 因此第一个参数是整个文件路径。
【解决方案2】:

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

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

if(f is not empty)
  //file exits

【讨论】:

    【解决方案3】:
    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;
    }
    

    【讨论】:

    • 它也能识别目录。这实际上不是一回事,作者要求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 2010-12-10
    • 1970-01-01
    • 2012-02-05
    • 2013-03-12
    相关资源
    最近更新 更多