Search code examples
cfilepathfopen

Can't pass a char array (file name) to fopen(file,r)


I want users to enter their own file name they want into the program, then the program opens it. I don't know why it doesn't work, please help. It just works if I define the path directly on the code.

This works.

FILE *file;
file = fopen("C:\\Users\\Test\\text.txt", "r");
if (file) {
    index = 0;
    while ((c = getc(file)) != EOF) {
        printf("ok");
    }
    fclose(file);
} else {
    printf("Can't open file");
}

This doesn't work.

char inputFile[100];

printf("Enter file name: ");
scanf("%s", inputFile);

FILE *file;
file = fopen(inputFile, "r");
if (file) {
    index = 0;
    while ((c = getc(file)) != EOF) {
        printf("ok");
    }
    fclose(file);
} else {
    printf("Can't open file");
}

Solution

  • When reading in from code, you need to escape your "\", but scanf isn't as smart. You just need to enter the text as is!

    C:\Users\Test\text.txt

    Also, note that scanf ("%s", inputFile) won't handle spaces in the file name path, so "My Documents" won't work.