c++ 文件存取
一、将数据写入文件
void writeToFile()
{
std::ofstream outfile;
outfile.open("data.txt"); //创建、打开文件
for(unsigned int x = 0; x < N; x++)
{
for(unsigned int y = 0; y < M; y++)
{
outfile<<data[x * N + y]<<" "; //写入数据
}
outfile<<std::endl;
}
outfile.close(); //关闭文件
}二、从文件中读取数据
void readFormFile()
{
fstream in;
in.open("data.txt"); //打开文件
//逐字符读取
char c;
while(!in.eof())
{
in>>c;//读取字符
//其他操作
}
//逐行读取
string str;
while(getline(in,str))
{
//其他操作
}
in.close();//关闭文件
}
ps:
头文件#include <fstream>
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: c++文件打开和关闭
- 下一篇: c++文件操作总结
