Thread: File question-Testing if file exists

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

    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
        // do something

  3. #3
    Registered User matheo917's Avatar
    Join Date
    Sep 2001
    #include<stdlib.h>                  // uses exit() function...
    int main()
          ifstream fin("test.txt");
          if( )
              cout <<  "Can't find or open a given file!!! Exiting. \n";
              exit(1);          // terminates the program execution...
                cout << "File exists and is open. Now will get closed. \n";
           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.

       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