Home > Back-end >  fopen(): no such file or directory when sending char pointer as the filename
fopen(): no such file or directory when sending char pointer as the filename

Time:07-20

I have searched for all the possible answers to this problem; however, I still get the error. I have a server.conf file it has some values and I assign the values in this file to variables in a structure. I want to use the path variable in the struct as the filename in fopen. I know this problem has been asked about several times, but I still couldn't recognize what's the problem after days.

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    char *path;

} MainStruct;


int parse_config(MainStruct *inf)
{

    FILE *file;
    char *line = NULL;
    char *path;
    size_t len = 0;
    ssize_t read;

    file = fopen("server.conf", "r");
    if (file != NULL)
    {

        while ((read = getline(&line, &len, file)) != -1)
        {

            if (strstr(line, "PATH") != NULL)
            {
            
                inf->path = strdup(line   5);
            }
        }
        fclose(file);
    }
    else
        return 0;

    return 1;
}


int main(int argc, char *argv[])
{
    MainStruct val;

    parse_config(&val);
    char *pt = val.path;
    printf("%s", pt);
    FILE *fp = fopen(pt, "r");

    if (fp == NULL) {
        fprintf(stderr, "fopen() failed in file %s at line # %d \n", __FILE__,__LINE__);
        return EXIT_FAILURE;
    }

    fclose(fp);

}

this is the content of the server.conf file where I defined the PATH:

PATH file.html

I have checked the value of pt with printf and it's exactly the string file.html.

CodePudding user response:

#include <stdio.h>
#include <string.h>

int main() {
    printf("%s\n", strdup("PATH \"file.html\""   5));
}
// output: "file.html"

If the value of pt is "file.html" then the fopen() will try to open a file that is named "file.html" instead of a file named file.html.

Unless there is a file where the filename itself includes the double quotes, fopen() will fail.

Edit: added example code

CodePudding user response:

man getline:

getline() reads an entire line from stream, storing the address of the buffer containing the text into *lineptr. The buffer is null-terminated and includes the newline character, if one was found.

So your path is likely to point to a buffer that contains file.html\n, not file.html. It could be rather confusing if you printf it and don't pay attention to how many newlines are printed at the end.

  •  Tags:  
  • c
  • Related