【问题标题】:Given a path to a directory how do I check if a certain file exisits therein?给定目录的路径,我如何检查其中是否存在某个文件?
【发布时间】:2016-06-02 09:51:03
【问题描述】:

所以我得到了一个/path/to/a/directory/,应该检查其中是否存在index.php。如果是,我应该返回/path/to/a/directory/index.php。如果 index.html 存在,我应该返回它,否则 NULL 目前我正在使用fopen(file, 'r'),但我认为它并没有达到我想要的效果。我也一直在研究 stat()scandir() 的功能,但我对如何使用这些功能一无所知...(即使一遍又一遍地阅读 MAN 页面^^)

/**
 * Checks, in order, whether index.php or index.html exists inside of path.
 * Returns path to first match if so, else NULL.
 */
char* indexes(const char* path)
{
    char* newPath = malloc(strlen(path) + strlen("/index.html") + 1);
    strcpy(newPath, path);

    if(access( path, F_OK ) == 0 )
    {
        printf("access to path SUCCESS\n");
        if( fopen( "index.php", "r" ))
        {
            strcat( newPath, "index.php" );
        }
        else if( fopen( "index.html", "r"))
        {
            strcat( newPath, "index.html" );
        }
        else
        {
            return NULL;
        }
    }
    else
    {
        return NULL;
    }
    return newPath;
}

我在这里看到的主要问题是,我不认为我的函数会在所需路径内查找 fopen() 的文件。他们究竟在哪里寻找文件?我的根文件夹?

任何输入都会得到极大的赞赏。

【问题讨论】:

  • 检查“/some/location/with/file”是否存在不会自动将您移动到“/some/location/with”,因此您可以执行fopen("file", "r")。请改用fopen(path, "r")
  • 但是如果我使用fopen(path, "r"),它希望打开什么文件?
  • 与您使用的相同access

标签: c file path server


【解决方案1】:

你的基本想法看起来没问题。在调用 fopen() 之前,请为每个文件构造路径/文件名。为最长的元素分配内存并将其用于例如 sprintf() 以获取您的路径。当 fopen() 成功时,您可以返回该指针,如果没有,请不要忘记 free() 内存。

【讨论】:

    【解决方案2】:

    opendir 呢:

    char* indexes(const char* path)
    {
        DIR *dir;
        struct dirent *entry;
        char* newPath = NULL;
    
        dir = opendir(path);
        while ((entry = readdir(dir)) != NULL) {
            if (!strcmp(entry->d_name, "index.php") || !strcmp(entry->d_name, "index.html"))
            newPath = malloc(strlen(path) + strlen(entry->d_name) + 2);
            sprintf(newPath, "%s/%s", path, entry->d_name);
            break;
        }
        closedir(dir);
        return newPath ;
    }
    

    在这里,您打开目录条目并使用readdir 扫描它,它会返回一个识别内部每个文件的结构(有关更多详细信息,请参见opendirreaddir 的手册页)。
    不鼓励使用fopen,因为对于尝试打开每个文件的系统来说很重,当目录包含数千个或更多文件时,它会很慢。

    【讨论】:

    • 好的!不过,我对这种语言还是很陌生。好像您在这里调用了一个名为 DIR 的结构?你在entry->d_name 到底在做什么?谢谢!!
    • 欢迎您。查看答案更新。有关更多详细信息,您可以在手册页或网络上找到它们;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 2021-02-17
    • 2011-08-22
    • 2012-11-30
    • 1970-01-01
    相关资源
    最近更新 更多