Hi Experts, I am trying to figure out if a file exists or not in the current directory. if it is not present the program should exit. In shell i used : Code: #!/usr/bin/ksh if [ -f file1 ] ; then printf "ok\n" ; else exit ; fi What is equivalent in C , please advise, Like: #include <stdio.h> main () { .. if .. some logic using fopen("file,r) ... please help. Thanks,
Re: C program to check file condition : help! Multiple Ways. Code: if( access( filename, F_OK ) != -1 ) { // filename exists } else { // filename doesn't exist } But many other forums also recommend the following solution. Code: bool file_exists(const char * filename) { if (FILE * file = fopen(filename, "r")) //Open file for read only { fclose(file); return true; } return false; } Which is not very efficient one.
Shabbir, Thank you , I am getting error while compiling both the program , Please advise, Code: #include <stdio.h> main () { if( access( filename, F_OK ) != -1 ) { // filename exists } else { // filename doesn't exist } } Code: ubuntu:# cc filecheck.c -o filecheck filecheck.c: In function âmainâ: filecheck.c:4:13: error: âfilenameâ undeclared (first use in this function) filecheck.c:4:13: note: each undeclared identifier is reported only once for each function it appears in filecheck.c:4:23: error: âF_OKâ undeclared (first use in this function) # DO I have to declare something, Looks like I am missing something in the c program. Thanks,
Got it .. , Thanks.. Code: #include <stdio.h> #include <stdlib.h> #include <errno.h> main() { FILE *fp; if (( fp = fopen("test1.txt", "r")) == NULL) { perror("Can not open FILE!!! "); return EXIT_FAILURE ; } else { printf ("File opened for reading: [ OK ].\n"); fclose(fp); } return(0); }