#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void test01() {
//1.包含头文件
//2.创建流对象
ofstream ofs;
//3.打开文件
ofs.open("test.txt", ios::out);
//4.对文件操作
ofs << "this is a test" << endl;
ofs << "我试试" << endl;
//5.关闭流对象
ofs.close();
ifstream ifs;
ifs.open("test.txt", ios::in);
if (!ifs.is_open()) {
cout << "error!" << endl;
return;
}
//读数据有四种方法
//1. 这种遇到一个空格就输出,然后输出一个换行符
/*cout<<"1"<<endl;
char buf[1024] = { 0 };
while (ifs >> buf) {//遇到空格或换行符就下一次
cout << buf << endl;
}*/
//2. 一次读一行,最多读1024个字符
/*cout<<"2"<<endl;
char buf[1024] = { 0 };
while (ifs.getline(buf, sizeof(buf))) {
cout << buf << endl;
}
*/
//3. 一次读一行,读到string中,没有行长度限制
/*cout << "3" << endl;
string buf;
while (getline(ifs, buf)) {
cout << buf << endl;
}
ifs.close();*/
//4. 一次读一个字符
/*cout << "4" << endl;
char c;
while ((c = ifs.get()) != EOF) {
cout << c;
}*/
}
int main() {
test01();
return 0;
}
11-10
1421
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交