How do you open a file in C++?

后端 未结 9 879
-上瘾入骨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 16:00

    You need to use an ifstream if you just want to read (use an ofstream to write, or an fstream for both).

    To open a file in text mode, do the following:

    ifstream in("filename.ext", ios_base::in); // the in flag is optional
    

    To open a file in binary mode, you just need to add the "binary" flag.

    ifstream in2("filename2.ext", ios_base::in | ios_base::binary ); 
    

    Use the ifstream.read() function to read a block of characters (in binary or text mode). Use the getline() function (it's global) to read an entire line.

提交回复
热议问题