How do you open a file in C++?

后端 未结 9 866
-上瘾入骨i
-上瘾入骨i 2021-02-01 15:41

I want to open a file for reading, the C++ way. I need to be able to do it for:

  • text files, which would involve some sort of read line function.

9条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-01 15:49

    #include 
    #include 
    using namespace std;
    
    void main()
    {
        ifstream in_stream; // fstream command to initiate "in_stream" as a command.
        char filename[31]; // variable for "filename".
        cout << "Enter file name to open :: "; // asks user for input for "filename".
        cin.getline(filename, 30); // this gets the line from input for "filename".
        in_stream.open(filename); // this in_stream (fstream) the "filename" to open.
        if (in_stream.fail())
        {
            cout << "Could not open file to read.""\n"; // if the open file fails.
            return;
        }
        //.....the rest of the text goes beneath......
    }
    

提交回复
热议问题