Search code examples
cfopen

fopen with path stored in variable


I have saved paths in a text file and would like to read them out. With these paths I want to read new text files, but if I call fopen () with a variable, the program only crashes. The paths I save are absolute. I have already tried to read the files without variables, which also worked.

FILE *fp;
FILE *variable;
char file[256];

fp = fopen("C:\\Example\\Example.txt","r");

if(fp != NULL)
{
    while(fgets(file, 256, fp) != NULL)
    {
         variable = fopen(("%s", file), "r");
         // another while loop which reads out the content of the variablefile 
         fclose(variable);
    }
    fclose(fp);
}

Solution

  • There are two problems in your code. The first is this line

    variable = fopen(("%s", file), "r");
    

    I don't know where you found this notation, but fopen requires two parameters. From man: FILE *fopen(const char *pathname, const char *mode). Basically two string, one for the path and the other for the opening mode So the correct call to fopen would be:

    variable = fopen(file, "r");
    

    Also, fgets stores any newline read into the buffer. Simply remove this newline before opening the file:

    char *newline = strchr(Name, '\n');
    if (newline)
        /*if a newline is found, we remove it*/
        *pos = '\0';
    else
        /*error: input too long for buffer */