读文件
与写文件对应,读文件也有如下过程
- 创建读文件流对象。
- 设置文件路径。
- 设置读文件打开方式。
- 读文件。
- 关闭文件。
读文件有多种方式,此处介绍如下几种:
方式一:
创建文件使用流对象直接输出到 buffer 内。
//读文件方式一 void test0() { cout << "方式一" << endl; ifstream ifs; ifs.open("test.txt", ios::in); if (!ifs.is_open()) { cout << "文件打开失败。" << endl; return; } else { char* buf = new char[1024]; while (ifs >> buf) // 使用流对象将文件内容读入缓冲区 { cout << buf << endl; } } ifs.close(); }
方式二:
使用流对象的方法 getline
//读文件方式二 void test1() { cout << "方式二" << endl; ifstream ifs; ifs.open("test.txt", ios::in); if (!ifs.is_open()) { cout << "文件打开失败。" << endl; return; } else { char buf[1024] = { 0 }; while (ifs.getline(buf, sizeof(buf))) { cout << buf << endl; } } ifs.close(); }
方式三:
传入string缓冲对象
//方式三 void test2() { cout << "方式二" << endl; ifstream ifs; ifs.open("test.txt", ios::in); if (!ifs.is_open()) { cout << "文件打开失败。" << endl; return; } else { string buf; while (getline(ifs, buf)) //使用string对象直接调用 getline 读入 buf 中 { cout << buf << endl; } } ifs.close(); }
写个 anchor 后面寻找答案:
与方式二相比,方式三 getline 的调用类似于全局函数的调用方式,而方式二中 getline 则是作为 ifstream 的成员函数调用的。