【发布时间】: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