How to check if a file exists in C with user input

I am a complete noob for C, and I was wondering why, if I take user input, why it won’t find the file, but when I use it with hard code:

const char * fn = "/Users/james/Documents/test.rtf"; 

Does everything seem to be okay?

 char text[100]; fputs("File location: ", stdout); fflush(stdout); fgets(text, sizeof text, stdin); FILE *fp = fopen(text,"r"); if( fp ) { printf("\nFile Exists"); fclose(fp); } else { printf("\nFiles doesn't exist"); } 

Any help would be awesome or just a point for some online source that I obviously could not find. :)

+4
source share
2 answers

fgets reads the line and saves the final newline character. You will have to remove this with

 text[strlen(text) - 1] = '\0'; 

(Of course, after correctly checking for errors.)

+5
source

You can use access () to check if a file exists or not. To access you need to specify the file path and mode.

The access prototype is int access (const char * pathname, int mode);

access () returns zero if the file exists.

For more information, visit: http://linux.die.net/man/2/access

0
source

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


All Articles