Thread: Check if a file exists - C99 Standard

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    61

    Check if a file exists - C99 Standard

    What is the best way to see if a file exist ?

    I write this one but i canīt know if the file exist or if i canīt read it.

    I can only use C99 Standard

    Code:
       pFile = fopen(nomeFich, "rb");
    
    
        // File Exist
        if (pFile != NULL) {
    
                     // Doing my stuff here, create a list...     
    
            fclose(pFile);
            return list;
        } else {
            puts("The file donīt exist or canīt be open);
            return NULL;
        }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,402
    I think that's the best you can do given the standard I/O functions.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,602
    The errno variable (errno.h) and the strerror function (string.h) will tell you why the file could not be opened.
    Code:
    if ( fp == NULL ) {
      // or use the perror() function
      printf("why? %d %s\n", errno, strerror(errno));
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to check if a file exists?
    By elninio in forum C++ Programming
    Replies: 13
    Last Post: 07-31-2008, 02:20 PM
  2. How to check if file exists ?
    By jabka in forum C Programming
    Replies: 14
    Last Post: 10-14-2007, 09:21 PM
  3. Check If File Exists On FTP
    By stickman in forum C++ Programming
    Replies: 8
    Last Post: 05-08-2006, 05:06 PM
  4. How to check if a file exists
    By ElastoManiac in forum C++ Programming
    Replies: 10
    Last Post: 12-05-2005, 05:20 PM
  5. check if the file exists
    By ipe in forum C Programming
    Replies: 2
    Last Post: 03-15-2003, 09:18 AM

Tags for this Thread