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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM