Reputation: 19
Open a file with keyboard input Write a C program that asks to the user a name of a file (the name might contain the directory path as well) and tries to open the file. The program displays a message “File open !” or “Error opening the file” (the program does not read the file, just tries to open it). Use gets() to get user’s input
So using the code below I tried to read in a file directory path and then copy this file directory path into fopen() then confirming whether or not the file had been opened or not. The file directory path is entered in by the user using gets().
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char directory[100];
printf("Please enter the directory path of the file you wish to open.\n");
gets(directory);
fp = fopen("%s,directory","r");
if(fp==NULL)
{
printf("\nCannot open file.");
}
else
{
printf("\nFile open!");
}
return 0;
}
No matter what I put in it doesn't work and I've copied file directory paths directly from other programs that I've created and I know work. Any ideas?
Upvotes: 0
Views: 467
Reputation: 28654
fp = fopen("%s,directory","r");
This is really confusing. Why are you using %s
and ""? Just use directory
as parameter directly. e.g.
fopen(directory, "r"); // make sure _directory_ refers to file for this function to succeed
gets
is also considered dangerous.
Upvotes: 1