Home>

I'm studying C language now. So I made a program to read the dat file with the following code, but fopen (".. \ input1.dat", "r")) == NULL and the file is not read. The path of the dat file is confirmed in visual studio 2019 and the path is posted. Entering either the displayed relative path or the absolute path did not load the file either.

#include<stdio.h>
#include<stdlib.h>
int main ()
{
    FILE * fp;
    double a = 10.0;
    if ((fp = fopen (".. \ input1.dat", "r")) == NULL)
    {
        printf ("File not found: input1.dat \ n");
        exit (1);
    }
    while (a>0)
    {
        fscanf (fp, "% lf",&a);
        printf ("a =% f \ n", a);
    }
    fclose (fp);
    return 0;
}
  • Answer # 1

    In c and c ++ in a string\ \Has a special meaning. If you search with the search word "C language escape sequence", various sites will be hit, so please refer to that for details.

    So, the problem this time is Windows path delimiter\ \Also means that it cannot be used as it is in a C language string.\ \To use it in a string\\I need to write.

    if ((fp = fopen (".. \\ input1.dat", "r")) == NULL)
    {
        printf ("File not found: input1.dat \ n");
        exit (1);
    }


    Please try.