How to see if a file exists

This is a discussion on How to see if a file exists within the C++ Programming forums, part of the General Programming Boards category; Hello, I'm beyond a newbie for "C/C++" ...but I've worked with dos/bash/novell login scripts etc. a little over the years. ...

  1. #1
    Registered User
    Join Date
    Dec 2006
    Posts
    4

    How to see if a file exists

    Hello,

    I'm beyond a newbie for "C/C++" ...but I've worked with dos/bash/novell login scripts etc. a little over the years. Basically it boils down to this.

    I need my simple little C app to check if a file exists and if so EXIT.
    If not then continue running the rest of the program.

    Thank you for any info.

  2. #2
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Portugal
    Posts
    7,487
    Check the tutorials on this website (Cprogramming.com) for file access. It's all there.
    The programmer’s wife tells him: “Run to the store and pick up a loaf of bread. If they have eggs, get a dozen.”
    The programmer comes home with 12 loaves of bread.


    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >I need my simple little C app to check if a file exists and if so EXIT.
    >If not then continue running the rest of the program.
    That's simple enough, just open the file:
    Code:
    ifstream in ( "myfile" );
    
    if ( in )
      exit ( status );
    Granted, that's making a few assumptions about permissions and such, but for the most part it's a solid and trivial way to check for the existence of a file.
    My best code is written with the delete key.

  4. #4
    Registered User
    Join Date
    Dec 2006
    Posts
    4

    over my head

    I tried the following and all I get is compile errors.
    I applogize for my ignorance in the syntax/understanding of C, it seems this won't be as easy as I thought. I don't want to ask someone to write the code

    Thank you for trying to help though.

    Here's what I tried.

    // Begin File Check
    ifstream in ( "c:\test.txt" );
    if ( in )
    exit ( status );
    // End File Check

    The errors I get are.

    'ifstream' does not name a type
    expected unqualified-id defore "if"
    expected '; or '; before "if"

    Im using Dev-C++ 4.9.9.2

  5. #5
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    1. include fstream class library
    2. qualify it with std.

  6. #6
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    To use ifstream, add the following at the top of your program:
    Code:
    #include <fstream>
    using namespace std;
    Also:
    >ifstream in ( "c:\test.txt" );
    To include a backslash in a string, you must use two, as a backslash is the escape character in a string (for example \n for newline):
    Code:
    ifstream in ( "c:\\test.txt" );

  7. #7
    Registered User
    Join Date
    Dec 2006
    Posts
    4
    Thank you for the replies, this board has some wonderful people. I've never had such great willingness to help out.

    Here's what I have now.

    #include <fstream>
    using namespace std;

    // Begin File Check
    ifstream in ( "c:\\test.txt" );
    if ( in )
    exit ( status );
    // End File Check

    I now only get the following errors.
    expected unqualified-id defore "if"
    expected '; or '; before "if"

    I'll dig around on those when I get back.
    Once again thank you for all the help.

    Take care.

  8. #8
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,592
    It's because you seem to be writing code outside of functions.

    Like so
    Code:
    #include <fstream>
    using namespace std;
    int main ( ) {
      // Begin File Check
      ifstream in ( "c:\\test.txt" );
      if ( in )
        exit ( status );
      // End File Check 
      return 0;
    }
    Notice how neat the code looks - use [code][/code] tags.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  9. #9
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    It would also be a good idea to define status:
    Code:
    #include <fstream>
    
    using namespace std;
    
    namespace {
      int status = 0; // Default to success
    }
    
    int main()
    {
      // Begin File Check
      ifstream in ( "c:\\test.txt" );
    
      if ( in )
        exit ( status );
      // End File Check 
    }
    My best code is written with the delete key.

  10. #10
    Registered User
    Join Date
    Dec 2006
    Posts
    60
    Quote Originally Posted by Prelude
    >I need my simple little C app to check if a file exists and if so EXIT.
    >If not then continue running the rest of the program.
    That's simple enough, just open the file:
    Code:
    ifstream in ( "myfile" );
    
    if ( in )
      exit ( status );
    Granted, that's making a few assumptions about permissions and such, but for the most part it's a solid and trivial way to check for the existence of a file.
    Is the above "if" statement similar to the following?
    Code:
    if(in.is_open())
    Are there any differences?

  11. #11
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Is the above "if" statement similar to the following?
    Pretty much.

    >Are there any differences?
    None that are likely to cause you any problems.
    My best code is written with the delete key.

  12. #12
    Registered User
    Join Date
    Dec 2006
    Posts
    4

    almost got it?

    Ok....it's now compiling without errors....however it's not moving to the next section. Seems to exit no matter what.

    Basically I want it to check for the file and if it's there stop all execution, if the file isn't there....then run the next part of the code.

    Let me give you a sample of the code. Everything works as it should when complied. (just not with the new part "Added/End Added")

    Code:
    #include <windows.h>
    --------------------------- Added -------------------------------------
    #include <fstream>
    
    // Begin File Check
    using namespace std;
     namespace {
      int status = 0; // Default to success
     }
    int main()
    {
      // Begin File Check
      ifstream in ( "c:\\Program Files\\test\\test-test\\test.exe" );
      if ( in )
        exit ( status );
    }
    // End File Check
    -------------------------- End Added -------------------------------
    
    DWORD BeQuiet(char* strFunct, char* strstrParams); 
    
    int WINAPI WinMain (HINSTANCE hThisInstance,
                        HINSTANCE hPrevInstance,
                        LPSTR lpszArgument,
                        int nFunsterStil)
                        {
    
      //XP installer for test server
    
        BeQuiet("cscript.exe", "testinstall\\test\\testreg.vbs");
        BeQuiet("testinstall\\test\\test.exe", "");
        BeQuiet("testinstall\\testdir\\testsetup.exe", "");
        BeQuiet("cscript.exe", "testinstall\\testrem\\testcleanreg.vbs");
    and so on........


    Thank you.

  13. #13
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Seems to exit no matter what.
    That's because when the program's execution falls off the end of the main function, it exits. Keep in mind that we're giving you minimal code to show the technique of a solution, not a complete working solution. You have to add what we left out.
    My best code is written with the delete key.

  14. #14
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    And also - seeing WinMain in your code I thinkg you are creating GUI application

    In this case you don't need main function

    create another function with the code that tests the existence of the file
    return true if it exists and false - otherwise
    Call it for each file you need to check and decide if you want to continue based on the return value
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  15. #15
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    >>Let me give you a sample of the code. Everything works as it should when complied. (just not with the new part "Added/End Added")

    That's because you didn't indicate you had a running program using Windows API already. The solution(s) provided were focused on console applications, not Windows. Each program should have only 1 entry point, that being a function called main(). In C and C++ console programs that syntax is:

    int main()

    but in Windows API its:

    int WINAPI WinMain()

    This might work a little better for you:
    Code:
    #include <windows.h>
    #include <fstream>
    
    // Begin File Check
    using namespace std;
    
     namespace {
      int status = 0; // Default to success
     }
      
    DWORD BeQuiet(char* strFunct, char* strstrParams); 
    
    int WINAPI WinMain (HINSTANCE hThisInstance,
                        HINSTANCE hPrevInstance,
                        LPSTR lpszArgument,
                        int nFunsterStil)
    {
      //. . . . . 
      // Begin File Check within WinMain()
      ifstream in ( "c:\\Program Files\\test\\test-test\\test.exe" );
      if ( in )
        exit ( status );
    
    
        BeQuiet("cscript.exe", "testinstall\\test\\testreg.vbs");
        //. . . . .
    }
    Unfortunately, even that may not provide what you want, though without more code it's not possible to say what you need.

    You should be aware that the native WinAPI functions are written in C and C uses pointers to type FILE to access files, not streams, though you can use streams as long as you compile the code using a C++ compiler rather than a C compiler. (You compiler can probably compile code using either C or C++ criteria based on which you tell it to do).

    Also, it's not easy to code using WinAPI, particular for newbies. I'd stick to console programming for a while before venturing into programming with WinAPI if you want to understand what's going on besides just learning what to do. Alternatively, if you want to write Windows applications with a quicker learning curve, (for most people anyway), then there's always Visual Basic or one of the other languages that allows you to write Windows apps, too.
    You're only born perfect.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. sequential file program
    By needhelpbad in forum C Programming
    Replies: 80
    Last Post: 06-08-2008, 01:04 PM
  3. 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
  4. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM

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