C++按行读取和写入文件

按行读取:

假设有一个文本文件,如下所示:

1 2 3
2 3 4
3 4 5
5 6 7
7 8 9

文件名为split.txt

目的:按照行读取数据,并一个个的显示出来。

代码如下:

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
int main(int args, char **argv)
{
std::ifstream fin("split.txt", std::ios::in);
char line[1024]={0};
std::string x = "";
std::string y = "";
std::string z = "";
while(fin.getline(line, sizeof(line)))
{
std::stringstream word(line);
word >> x;
word >> y;
word >> z;
std::cout << "x: " << x << std::endl;
std::cout << "y: " << y << std::endl;
std::cout << "z: " << z << std::endl;
}
fin.clear();
fin.close();
return 0;
}

下面一行一行解读代码:

首先说明一下头文件,头文件中<iostream>, <string>的作用就不用说了,<fstream>是定义文件的需要的头文件,而<sstream>是字符串流stringstream所需要的头文件。

第8行: std::ifstream fin("split.txt", std::ios::in); 定义读取的文本文件。

第9行: char line[1024] = {0}; 用于定义读取一行的文本的变量。

第10--12行,定义了 x y z 三个字符串变量,用于存放读取一行数据后,分别存放每行的三个数据。

第13--22行,用一个循环读取每行数据,读取行的函数是getline()函数,然后利用stringstream将每行文本自动按照空格分列,并分别存放到对应的三个字符串变量中。

23、24行代码,就是刷新缓存,并关闭文件。

运行结果:

 

按行写入:

目的:向文件中追加文本内容。

代码如下:

#include   <iostream> 
#include   <fstream> 
#include   <string> 
using namespace std;
int main()
{
ofstream   ofresult( "result.txt ",ios::app); 
ofresult<<"123"<<"你是好孩子"<<endl;
ofresult<<"第二次写文件"<<endl;
return 0;
}

 

posted @ 2017-07-05 13:11  DarrenChan陈驰  阅读(22043)  评论(0编辑  收藏  举报
Live2D