读文件

读文件与写文件步骤相似,但是读取方式相对于比较多
读文件步骤如下:

  1. 包含头文件
    #include
  2. 创建流对象
    ifstream ifs;
  3. 打开文件并判断文件是否打开成功
    ifs.open(“文件路径”,打开方式);
  4. 读数据
    四种方式读取
  5. 关闭文件
    ifs.close();
    1. /*
    2. * First Way to read a text file.
    3. */
    4. void Read1(){
    5. ifstream ifs;
    6. ifs.open("test.txt", ios::in);
    7. if (!ifs.is_open()) {
    8. cout << "File Open Failed!" << endl;
    9. }
    10. char buf[1024] = { 0 };
    11. while (ifs >> buf) {
    12. cout << buf << endl;
    13. }
    14. ifs.close();
    15. }
    16. /*
    17. * Second Way to read a text file.
    18. * Use Member function getline.
    19. */
    20. void Read2(){
    21. ifstream ifs;
    22. ifs.open("test.txt", ios::in);
    23. if (!ifs.is_open()) {
    24. cout << "File Open Failed!" << endl;
    25. }
    26. char buf[1024] = { 0 };
    27. while (ifs.getline(buf,sizeof(buf))) {
    28. cout << buf << endl;
    29. }
    30. ifs.close();
    31. }
    ```cpp

    include

    include

    include

    using namespace std; /*
    • First Way to read a text file. / void Read1(){ ifstream ifs; ifs.open(“test.txt”, ios::in); if (!ifs.is_open()) { cout << “File Open Failed!” << endl; } char buf[1024] = { 0 }; while (ifs >> buf) { cout << buf << endl; } ifs.close(); } /
    • Second Way to read a text file.
    • Use Member function getline. / void Read2(){ ifstream ifs; ifs.open(“test.txt”, ios::in); if (!ifs.is_open()) { cout << “File Open Failed!” << endl; } char buf[1024] = { 0 }; while (ifs.getline(buf,sizeof(buf))) { cout << buf << endl; } ifs.close(); } /
    • Thired Way to read a text file.
    • Use globe function getline. / void Read3() { ifstream ifs; ifs.open(“test.txt”, ios::in); if (!ifs.is_open()) { cout << “File Open Failed!” << endl; } string buf; while (getline(ifs,buf)) { cout << buf << endl; } ifs.close(); } /
  • Fouth to use member function get() */ void Read4() { ifstream ifs; ifs.open(“test.txt”, ios::in); if (!ifs.is_open()) {
    1. cout << "File Open Failed!" << endl;
    } char c; while ((c = ifs.get())!=EOF) {
    1. cout << c;
    } ifs.close(); } int main() { Read@@@@(); return 0; } ```
  • 读文件可以利用 ifstream ,或者fstream类
  • 利用is_open函数可以判断文件是否打开成功
  • close 关闭文件