Reputation: 7
I know that code will not run but how can i fix this? ( I am new to c)
char name[20]
printf("Ender the name of text file you want to open ex: word.txt");
scanf("%s", name);
ptr = fopen("name", "r"); // There is the problem
Upvotes: 0
Views: 86
Reputation: 170
char name[20]; //Missed the semi colon
printf("Ender the name of text file you want to open ex: word.txt");
scanf("%s", name);
ptr = fopen(name, "r"); // Remove the string literal.
Using "name" means you are looking for a file named "name" in your directory to open. If you use name instead (no quotes) then you are looking for the string literal that is stored in the variable named name.
Upvotes: 0
Reputation: 30136
By calling fopen("name","r")
, you are attempting to open a file called "name" for reading.
Assuming that you have FILE* ptr
declared somewhere up there...
Change this:
ptr = fopen("name","r");
To this:
ptr = fopen(name,"r");
Upvotes: 2
Reputation: 6707
For file I/O, you need a FILE
object, hence the code would be:
FILE* ptr;
ptr = fopen( name, "r" );
and also check the return value, that will be NULL
in case of failure.
Check out this link for more details.
Upvotes: 0
Reputation: 1467
Just simply pass name instead:
if ((ptr = fopen(name, "r")) == NULL)
{
fprintf(stderr, "We have a problem!\n");
return -1;
}
Also, do some error checking to ensure it is really open.
Upvotes: 0