本文主要總結了C++中對文本文件的基本操作以及使用心得,第一部分中總結了C++對文本文件的基本操作,第二部分中會以csv文件為例,進行讀取存儲由逗號分隔的字符串的操作。
1. 文本讀取寫入基礎
要使用文件輸入輸出流,首先需要include相關庫 : iostream 以及fstream。istream類和ostream類分別是輸入輸出流類,用于鍵盤與程序的輸入,以及程序向顯示器的輸出。其中,istream和ostream分別有子類,ifstream和ofstream。ifstream類用于文件對程序的輸入(讀取文件),而ofstream類用于程序對文件的輸出(寫入文件)。下面列舉一個基本的文本讀取寫入的例子。
#include <iostream>
#include <fstream>
# include <string>
using namespace std;void test_fstream() {//ifstream if_file;//if_file.open("file1.txt", ios::in);ifstream if_file("file1.txt", ios::in);ofstream of_file("file2.txt", ios::app); // 使用append模式打開,寫入的字符會添加在文件的末尾string str_in;if (!if_file.is_open()) {cerr << "An error occurred when opening the file" << endl; return;}while (if_file.peek()!=EOF){getline(if_file, str_in); //讀取每一行字符串of_file << str_in << endl; //將字符串流入file2中cout << str_in << endl; }}int main()
{test_fstream();return 0;
}
上述代碼實現了,將file1中的文字拷貝到file2中的操作。由于我們使用的append模式打開file2.txt,因此會將新的字符添加到文件的末尾。
初始的file1.txt 和 file2.txt如下 :
程序運行一次后結果如下 :
2. csv文件的讀取以及對讀取數據的分類存儲
在第一部分中,我們主要列舉了對txt文本文件的讀取寫入方法。那么針對csv文件,或者類似的使用逗號分割字符串的文件,在第二部分中我會分享一個常用的分類存儲方式。
下面用一個簡單的csv文件為例子 :
下面的C++代碼主要實現了,分別讀取由逗號分割的幾部分的數據并存儲在對應的變量中。
void test_csv()
{ifstream if_csv("test_csv.csv", ios::in);if (!if_csv.is_open()) {cerr << "An error occurred when opening the file" << endl;return;}string linestring;getline(if_csv, linestring); //第一行存儲了每一列的類別,我們跳過這一行while (if_csv.peek() != EOF){getline(if_csv, linestring);uint64_t index_first_virgule = linestring.find(',' , 0); //找到第一個逗號的索引string country = linestring.substr(0, index_first_virgule); //使用substr方法分割出需要的字符串uint64_t index_second_virgule = linestring.find(',', index_first_virgule + 1);string capital = linestring.substr(index_first_virgule+1, index_second_virgule- index_first_virgule-1);uint64_t index_third_virgule = linestring.find(',', index_second_virgule + 1);string population = linestring.substr(index_second_virgule + 1, index_third_virgule - index_second_virgule - 1);cout << " country : " << country << " capital :" << capital << " population : " << population << endl;}
}
代碼運行結果如下 :
這個模式可以適用于所有標準的文本文件,csv文件。分隔符號不一定必須是逗號,可以是任何一致的符號,使用這個模板可以快速地讀取文件中每一行由逗號分隔的字符串,對于處理excel表格等數據非常實用。