how do i check if a file exist?
without using if (fopen(....));
how do i check if a file exist?
without using if (fopen(....));
Im not sure if there is a function that does this. But this would work using fopen.
fopen returns NULL on error, and a FILE pointer on success. So in this case if fopen returns NULL you know that there is no file, otherwise fopens returns a FILE pointer and nothing happens. If your still confused you can read here to learn more about fopen and about how it works.Code:#include <stdio.h> int main(void) { if (fopen("filename.txt", "r") == NULL) { printf("You know the file doesn't exist\n"); } else { printf("File exists\n"); } return (0); }
>how do i check if a file exist?
The only portable way is to try and open it for reading. If the operation fails then it's a good bet that the file doesn't exist.
>without using if (fopen(....));
In that case, it depends on your operating system and compiler, for example, this would work if your system supports it:
-PreludeCode:#include <sys/stat.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> int main ( void ) { struct stat buf; errno = 0; if ( stat ( "somefilename", &buf ) != 0 && errno == ENOENT ) { fprintf ( stderr, "File or file path does not exist\n" ); exit ( EXIT_FAILURE ); } return EXIT_SUCCESS; }
My best code is written with the delete key.