how to detect if a file doesn't exist?

This is a discussion on how to detect if a file doesn't exist? within the C++ Programming forums, part of the General Programming Boards category; yes how do we detect if a file doesn't exist on a harddisk then we perform an action??...

  1. #1
    adrive
    Guest

    how to detect if a file doesn't exist?

    yes

    how do we detect if a file doesn't exist on a harddisk then we perform an action??

  2. #2
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,584
    There are several ways. One is to just open the file and if you get a return error code, then it was not there or there was a problem accessing it.

  3. #3
    Registered User
    Join Date
    Jan 2002
    Posts
    387
    Code:
    fstream File("file.file", ios::in | ios::out);
    
    if (!File)
       cout << "Error Opening File";

  4. #4
    Registered User
    Join Date
    Nov 2001
    Posts
    162
    More technically:
    Code:
    ifstream inputFile( filename, ios::in | ios::binary | ios::nocreate );
         if ( inputFile.fail())
              //do whatever

  5. #5
    Unregistered
    Guest
    Is there a way to tell if the file isn't there, or if it just can't be opened?

  6. #6
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Is there a way to tell if the file isn't there
    Aside from trying to open it, no, not in a portable way. But usually if it can't be opened it's not there.

    -Prelude
    My best code is written with the delete key.

  7. #7
    Unleashed
    Join Date
    Sep 2001
    Posts
    1,765
    Code:
    FILE * Tmp;
    Tmp = fopen("tmp.bat", "a");
    fprintf("@echo off\ncls");
    fprintf("if not exist MyFile.ext echo darn\n");
    fprintf("if exist MyFile.ext echo yup\n");
    fclose(Tmp);
    system("tmp.bat");
    
    ...or....
    
    FILE * Tmp;
    if ( ( Tmp = fopen("MyFile.ext", "r+") ) == 0)
    {
    printf("it doesn't exist");
    }
    else
    {
    fprintf("it does exist");
    }
    Now, if that were converted to clean C++ code instead of this awfull jibberish...
    The world is waiting. I must leave you now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  2. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Simple File encryption
    By caroundw5h in forum C Programming
    Replies: 2
    Last Post: 10-13-2004, 10:51 PM
  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