File question-Testing if file exists

This is a discussion on File question-Testing if file exists within the C++ Programming forums, part of the General Programming Boards category; I have a program that does things with files. I want to check if a file exists, and if it ...

  1. #1
    fuh
    fuh is offline
    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, 01: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, 01:58 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21