Thread: File question-Testing if file exists

  1. #1
    Attack hamster fuh's Avatar
    Join Date
    Dec 2002
    Posts
    176

    File question-Testing if file exists

    I have a program that does things with files. I want to check if a file exists, and if it doesn't, create it with a default message. I don't know how I'd check if it exists. Could you tell me?
    Stupid things pop singers say

    "I get to go to lots of overseas places, like Canada."
    - Britney Spears

    "I love what you've done with the place!"
    -Jessica Simpson upon meeting the Secretary of Interior during tour of the White House

  2. #2
    Registered User
    Join Date
    Sep 2002
    Posts
    1,640
    Code:
     filein.open("test.txt");
     if(fin.fail())
     {
        // do something
     }

  3. #3
    Registered User matheo917's Avatar
    Join Date
    Sep 2001
    Posts
    279
    Code:
    #include<iostream.h>
    #include<fstream.h>
    #include<stdlib.h>                  // uses exit() function...
    
    int main()
    {
          ifstream fin("test.txt");
    
          if( fin.fail() )
          {
              cout <<  "Can't find or open a given file!!! Exiting. \n";
    
              exit(1);          // terminates the program execution...
          }
    
          else
          {
                cout << "File exists and is open. Now will get closed. \n";
                fin.close();
           }
    
           return 0;
    }
    NOTE: keep in mind that in this particular case the file test.txt has to be in the same directory as you executable file, otherwise you would have to specify the entire path i.e.

    Code:
       ifstream fin("c:\\myfile\\someothercrap\\test.txt");


    hope that helps...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File being filled with NULLs
    By Tigers! in forum Windows Programming
    Replies: 2
    Last Post: 06-30-2009, 05:28 PM
  2. 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
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM