0
votes

I am trying to make a code that will open a file in a given mode using fopen, but I want the user to be able to tell the program the name or path of the file he wants to open, but the compiler shouts at me, the code I wrote is the one that follows:

printf("Path/Name of the file: \n");
char input_user = getchar();

filePointer = fopen(input_user, "r");

The error the compiler returns is this: "warning: passing argument 1 of ‘fopen’ makes pointer from integer without a cast [-Wint-conversion] filePointer = fopen(input_user, "r");"

and this: "note: expected ‘const char * restrict’ but argument is of type ‘char’ extern FILE *fopen (const char *__restrict __filename,"

1
fopen expects its first argument to be of type char *. You are passing a char.William Pursell
You pass a null-terminated string as the filename to open. A single character is not a string.Some programmer dude
so if I just write "char * input_user = getchar" it will work? (Thanks for the answer)User__1
On another related and very important note: Don't use user-input to open files without validation of the string. The user could be inputting anything which could lead to security problems in your program. Or best-case just a crash (denial of service).Some programmer dude
getchar reads a single character, you can't simply treat this single character as a string. You probably want something like char filename[128]; scanf("%127", filename);Some programmer dude

1 Answers

1
votes

As "some programmer dude" stated, fopen takes a char * (a pointer to char), not a single char. Using an array will do, as he also stated.

I will just compile his comments into an answer.

#include <stdio.h>

int main()
{
    printf("Path/Name of the file: \n");
    char filename[128];
    scanf("%127s", filename);

    FILE *filePointer = fopen(filename, "r");
    return 0;
}

I suggest you use this scanf syntax (%NUMBERs) to avoid an easy buffer overflow that could lead to a crash and a security flaw. Don't forget the additional \0 for your buffer size (I refer to the filename variable as your buffer), and be careful with user input in any real word application, especially when it is for something as important as accessing files. With an access to this program, one could just open any file even above this one in the file tree using ../ .

I also suggest you learn to read compiler output as it is very useful for problems like this one (don't worry you should naturally learn it over time after seeing similar errors often :) ).

In your case, the compiler explicitly tells you that the function wants a char * and you are giving it a char (it says const char * restrict but const and restrict are here to tell you that the pointer will not be modified in the function).

expected ‘const char * restrict’ but argument is of type ‘char’

I hope that you understand better what was wrong and that this was clear enough !