您好,登錄后才能下訂單哦!
這篇“C++怎么使用ifstream讀取文件內容”文章的知識點大部分人都不太理解,所以小編給大家總結了以下內容,內容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“C++怎么使用ifstream讀取文件內容”文章吧。
測試文件如下內容:myfile.txt
Fry: One Jillion dollars.
[Everyone gasps.]
Auctioneer: Sir, that's not a number.
數據讀取, 測試 。
C++中使用ifstream類實現讀文件操作,代碼如下:
實現了:
1、以行讀取文件
2、逐個詞讀取文件
3、文件名正確性檢測
#include <iostream> #include <fstream> #include <string> using namespace std; //讀取整個文件內容到char array數組中去 void fileReadAllToCharArray() { std::ifstream file; //以只讀方式打開文件 file.open("myfile.txt", std::ios::in); //指針定位到文件末尾 file.seekg(0, std::ios::end); int fileLength = file.tellg(); //指定定位到文件開始 file.seekg(0, std::ios::beg); cout << "fileLength:" << fileLength << endl; char* buffer = new char[fileLength + 1]; file.read(buffer, fileLength); buffer[fileLength] = '\0'; string contents = buffer; cout << "contents:" << contents << endl; if (buffer) { delete[] buffer; } file.close(); } //讀取方式:逐行讀取Line by Line, 將行讀入字符數組, 行之間用回車換行區分 void fileReadToCharArray() { std::ifstream file("myfile.txt"); constexpr int LINE_LENGTH = 100; char str[LINE_LENGTH]; int lineNum = 0; while (file.getline(str, LINE_LENGTH)) { cout << "Read from line[" << ++lineNum << "] :"<<str<<endl; } cout << "file has line:" << lineNum << endl; } //讀取方式:逐行讀取Line by Line, 將行讀入string, 行之間用回車換行區分 void fileReadToString() { std::ifstream file("myfile.txt"); int lineNum = 0; string str; while (getline(file, str)) { cout << "Read Data on Line:[" << ++lineNum<<"] :" << str <<endl; } cout << "file has line:" << lineNum << endl; } //讀取方式:逐詞讀取Word by Word,詞之間用空格劃分 void fileReadWbW() { std::ifstream file("myfile.txt"); string s; while (file >> s) { cout << "Read From File[" << s <<"]"<<endl; } } //帶檢測文件名功能 void fileReadWithErrCheck() { string fileName = "file .dat"; std::ifstream fin(fileName.c_str()); if (!fin) { cout << "Error Opening file:[" << fileName << "]" << " for input " << endl; exit(-1); } } int main() { #if 0 char data[100]; ofstream outfile; outfile.open("myfile.txt", ios::out | ios::trunc); cout << "enter your name: "; //cin.getline(data, 100); outfile << "hello world"<<endl; ifstream infile; infile.open("myfile.txt", ios::in); cout << "read file from myfile.txta" << endl; string readData; infile >> readData; std::cout << "data:" << readData << endl; outfile.close(); #endif //讀取整個文件內容到char array數組中去 fileReadAllToCharArray(); std::cout << "-----------------" << endl; //逐行讀取Line by Line fileReadToCharArray(); std::cout << "-----------------" << endl; //文件逐詞讀取Word by Word fileReadWbW(); std::cout << "-----------------" << endl; //逐行讀取Line by Line, 將行讀入string分 fileReadToString(); //帶檢測文件名功能 fileReadWithErrCheck(); std::cout << "-----------------" << endl; }
以上就是關于“C++怎么使用ifstream讀取文件內容”這篇文章的內容,相信大家都有了一定的了解,希望小編分享的內容對大家有幫助,若想了解更多相關的知識內容,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。