I'm writing a program to read the contents of a file within a directory. I've noticed that my program is reading the files correctly, but that the fopen is still resulting in a NULL result within my if-else loop. Here is my code:
int main(int argc, char *argv[])
{
DIR *folder;
struct dirent *point;
FILE *ptr;
argc = 2;
char filename[1000];
folder = opendir("/Users/user/test/");
if (folder == NULL)
{
fprintf(stderr, "Error: Failed to open input directory - %s\n", strerror(errno));
return (1);
}
while ((point = readdir(folder)))
{
printf("%s\n", point->d_name);
strncpy(filename, point->d_name, 254);
filename[254] = '\0';
ptr = fopen(filename, "r");
if (ptr == NULL)
{
printf("Error file missing\n");
}
else
{
printf("Success\n");
}
}
closedir(folder);
return (0);
}
For testing purposes, the directory "test" I'm opening only has one file inside called "apple.txt". Here is the output I receive when running my program:
.
Success
..
Success
.DS_Store
Error file missing
apple.txt
Error file missing
I do not understand why I get a "Success" at first, and then an "Error file missing" message twice after. I only have one file in the directory (folder), and the program seems to be reading the file correctly as it displays "apple.txt" in its output.
Can someone please help me explain where I'm going wrong and how to resolve this issue?