Thread: check if the file exists

  1. #1
    Registered User
    Join Date
    Jan 2003

    check if the file exists

    how do i check if a file exist?

    without using if (fopen(....));

  2. #2
    Join Date
    Nov 2002
    Im not sure if there is a function that does this. But this would work using fopen.
    #include <stdio.h>
    	if (fopen("filename.txt", "r") == NULL) {
    		printf("You know the file doesn't exist\n");
    	else {
    		printf("File exists\n");
    	return (0);
    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.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    >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:
    #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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  2. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  3. How to check if a file exists
    By ElWhapo in forum C++ Programming
    Replies: 3
    Last Post: 12-29-2004, 05:16 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM