Thread: checking files

    #1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2003
    Posts
    19
    Rep Power
    0

    checking files


    what is the easiest way to check if a file already exists?
  2. #2
  3. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2003
    Location
    Toronto, Canada
    Posts
    1
    Rep Power
    0
    I am fairly new to C/C++, but one alternative would be to check if you can open the file or not.

    Sample code:
    int checkFile(char filename[]) {
    FILE* fp; // file pointer
    int retval; // return value

    fp=fopen(filname, "r"); // open file for reading

    if (fp) // check if file was opened successfully or not
    retval=1;
    else
    retval=0;

    return retval; // return 1 or 0
    }

    Basically, if the file already exists, then you will be able to open it. If it doesn't exist, then opening will "fail".
    Hope this helps

    Cools
    Last edited by coolman0stress; April 20th, 2003 at 10:23 PM.
  4. #3
  5. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2003
    Posts
    19
    Rep Power
    0
    i don't know how to use that library, is there any easy way w/ fstream?
  6. #4
  7. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,607
    Rep Power
    4247
    You could always try opening the file for reading and call the fail() method to check if it failed or not.
    Code:
    ifstream file;
    
    file.open("filename.txt");
    if (file.fail()) {
       cerr << "file does not exist";
    }

IMN logo majestic logo threadwatch logo seochat tools logo