0

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?

giotto1
  • 49
  • 5
  • 2
    You are opening a relative path file name. But you are not in that directory. `chdir` to the directory first or construct the absolute path name. – kaylum Oct 16 '22 at 20:29
  • Write to that path, create a file there, to see which path the program actually accesses. – Yunnosch Oct 16 '22 at 20:30
  • See also [Directories being found but not recognized as directories](https://stackoverflow.com/q/74062431/15168). It is this same problem. The name retrieved from `readdir()` is a name relative to the directory being scanned. If that isn't your current directory, you have to use one of about 3 techniques to fix the trouble: (1) create a complete pathname by prefixing the directory name to the file name, (2) change directory to the directory you're scanning, or (3) use the `*at()` functions to avoid the need to do either (1) or (2). If they're available, option (3) is the best choice. – Jonathan Leffler Oct 16 '22 at 20:50
  • Take a look at `errno` like the manual says. – Cheatah Oct 16 '22 at 21:03

0 Answers0