Reputation: 1794
So I'm given a /path/to/a/directory/
and should check if index.php
exists therein. If it does I should return /path/to/a/directory/index.php
. If index.html
exists instead i should return that, else NULL
Currently I am using fopen(file, 'r')
but I dont think it does what I want it to do. I have also been looking into the functions stat()
and scandir()
but I am clueless on how I can use these... (even after reading the MAN pages over and over again ^^ )
/**
* 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;
}
My main problem that I see here is that I dont think that my functions looks for the files to fopen()
inside the desired path. Where exactly does they look for the files? My root folder?
Any input would be greatly appriciated.
Upvotes: 0
Views: 666
Reputation: 4877
What about 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 ;
}
Here you open the directory entry and scan it with readdir
that returns a structure identifying each file inside (for more details see man page for opendir
and readdir
).
The use of fopen
is to be discouraged because is heavy for the system that will try to open each file, and when the directory contains thousands or more file it will be very slow.
Upvotes: 2
Reputation: 31
your basic idea seen to be ok. Before you call fopen() construct the path/file name for each file. Allocate memory for the longest element and use it for e.g sprintf() to get your path. When fopen() succeeds you can return that pointer, if not don't forget to free() the memory.
Upvotes: 1