I searched the forum, and can't find the answer to this problem. It seems to be common, but none of the mentioned fixes are applicable.
This is my code for opening a file:
#include <stdio.h>
#include <string.h>
void main() {
FILE *input;
char path[200];
printf("Enter the full file path and file name in the following format:"
"\nC:\\Users\\Username\\etc......\\filename.extension\n");
fgets(path, 200, stdin);
printf("%s",path);
input=fopen(path,"r");
if (input==NULL) {
perror("The following errors were encountered");
return(-1);
}
}
printf(%s,path)
correctly displays the path and name of the file I want to open, but fopen always returns invalid argument. I have also tried using a pointer to path in fopen, but this always crashes the program.
You are getting path
with fgets
. \n
is considered a valid character by fgets
. You need to remove it manually.
fgets(path, 200, stdin);
path[strlen(path) - 1] = '\0';
Your problem is probably that fgets
does not remove the trailing '\n'
from the input line before returning it. fopen
cheerfully tries to open a file whose name contains '\n'
, but (assuming, as your code suggests, that you are using Windows) the operating system does not allow file names to contain that character, which is why you are getting an "Invalid argument" message. On a Unix-type system, where the kernel imposes far fewer constraints on file names, you would have instead gotten "No such file or directory". This may be why you didn't find any previous answers to this question; I know I've seen variations before.
Try this:
...
fgets(path, 200, stdin);
char *p = path + strlen(path) - 1;
while (isspace(*p)) p--;
*(p+1) = '\0';
printf("%s\n", path);
input = fopen(path, "r");
...
You will need #include <ctype.h>
for isspace
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With