1.ofstream,open,close写入文件
#include<iostream>
#include<fstream>
using namespace std;
//通过ofstream的方式实现写入文件 open,close
int main()
{
ofstream fout; //ofstream输出文件
// ofstream fout("number.txt"); 自动创建一个文件
fout.open("../pose.txt");//打开文件
fout << "1234abcdef";//写入文件
fout.close();
}
通过这些代码向文件1.txt中输入文件,但是会覆盖原来的文件。
2.ifstream,fin从文件中读取文件并打印输出到屏幕
#include<iostream>
#include<fstream>
using namespace std;
//通过ifstream流读取文件,并将文件写入str中
int main()
{
ifstream fin("../pose.txt");//创建读取文件的流
char str[50] = { 0 };
fin >> str;//读取
fin.close();
cout << str;
cin.get();
}
由于之前对pose.txt进行修改,pose的内容是:123456abcdef
2的输出是:123456abcdef
3.按照行来读取数据
#include<iostream>
#include<fstream>
using namespace std;
//按照行来读取
int main()
{
//按照行来读取
ifstream fin("../pose.txt");
//读取4行数据
for (int i = 0; i < 4;i++)
{
char str[50] = { 0 };
fin.getline(str, 50);
cout << str << endl;
}
fin.close();
cin.get();
}
转自:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/toto1297488504/article/details/38948391