Fopen returns an invalid argument in C

I searched the forum and cannot find the answer to this problem. This seems common, but none of the fixes mentioned apply.

This is my code to open the 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 file name I want to open, but fopen always returns an invalid argument. I also tried using the path pointer in fopen, but this always causes the program to crash.

+5
source share
2 answers

You get path with fgets . \n is considered a valid character on fgets . You need to delete it manually.

 fgets(path, 200, stdin); path[strlen(path) - 1] = '\0'; 
+6
source

Probably your problem is that fgets does not remove the trailing '\n' from the input line before returning it. fopen fun trying to open a file whose name contains '\n' , but (assuming your code suggests that you use Windows), the operating system does not allow file names to contain this character, so you get the message "Invalid argument". On a Unix-type system, where the kernel sets much less restrictions on file names, instead you would get "There is no such file or directory." Perhaps that is why you did not find any previous answers to this question; I know I saw options before.

Try the following:

 ... 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 .

+5
source

Source: https://habr.com/ru/post/1203943/


All Articles