Thread: Help with opening files

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    92

    Question Help with opening files

    Hey all,
    I need to open a file for reading. I know that usually you would declare an object like so:
    Code:
    fstream InputFile; // declaring a stream object
    InputFile.open("myfile", ios::in);
    Only problem is I need to declare the filename I need to open at a prompt. In other words, 'myfile' is the filename that needs to be opened but its a variable. How would I go about doing that? Thank you.

  2. #2
    Used Registerer jdinger's Avatar
    Join Date
    Feb 2002
    Posts
    1,065
    Code:
    #include <string>
    
    string Filename;
    
    cin<<Filename;
    //of course, you want to put some error checking after the cin
    
    ifstream ifs;
    ifs.open(Filename.c_str(),ios::in);

  3. #3
    Registered User
    Join Date
    Sep 2002
    Posts
    92

    One more thing(a sentinel-check)

    How about if you want to check if the user entered an escape sentinel like 0 to exit out of the program. Would your code look something like this?
    Code:
    if (Filename.c_str() == '0'){
        cerr << "Thank  you for using this program";
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Opening ASCII files in C?
    By Mavix in forum C Programming
    Replies: 6
    Last Post: 04-25-2007, 02:23 PM
  2. Need help opening a series of files
    By ramparts in forum C Programming
    Replies: 9
    Last Post: 11-14-2006, 05:49 PM
  3. Opening files with UNICODE file names
    By decohk in forum Linux Programming
    Replies: 2
    Last Post: 11-09-2006, 05:25 AM
  4. opening files
    By angelic79 in forum C Programming
    Replies: 3
    Last Post: 10-19-2004, 06:52 AM
  5. Opening files - Giving options?
    By wwwGazUKcom in forum C++ Programming
    Replies: 3
    Last Post: 09-18-2001, 07:06 AM