一、打開文件
在C++標準庫中,讀取文件需要用到fstream頭文件中的ifstream類。首先需要打開文件,使用ifstream類的open函數。該函數需要傳遞一個文件名參數,用於指定要讀取的文件名。open函數執行成功後,會返回一個bool類型的值來表示文件是否打開成功。
#include<iostream> #include<fstream> int main() { std::ifstream ifs; ifs.open("test.txt"); if (!ifs) { std::cout << "Fail to open the file!" << std::endl; return -1; } std::cout << "File has opened successfully!" << std::endl; ifs.close(); return 0; }
二、讀取文件內容
成功打開文件後,就可以使用ifstream類的read函數或者getline函數進行文件內容的讀取。read函數是按位元組數讀取文件內容,getline函數則是按行讀取文件內容。這裡我們以getline函數為例,示例代碼如下:
#include<iostream> #include<fstream> #include<string> int main() { std::ifstream ifs; ifs.open("test.txt"); if (!ifs) { std::cout << "Fail to open the file!" << std::endl; return -1; } std::string line; while (getline(ifs, line)) { std::cout << line << std::endl; } ifs.close(); return 0; }
三、關閉文件
使用完畢後,需要將已打開的文件進行關閉,以便釋放資源。使用ifstream類的close函數可以實現。
#include<iostream> #include<fstream> #include<string> int main() { std::ifstream ifs; ifs.open("test.txt"); if (!ifs) { std::cout << "Fail to open the file!" << std::endl; return -1; } std::string line; while (getline(ifs, line)) { std::cout << line << std::endl; } ifs.close(); std::cout << "File has closed successfully!" << std::endl; return 0; }
四、二進位文件讀取
讀取二進位文件需要使用read函數。read函數需要傳遞兩個參數:緩衝區地址和讀取的位元組數。
#include<iostream> #include<fstream> int main() { std::ifstream ifs; ifs.open("test.bin", std::ios::binary); if (!ifs) { std::cout << "Fail to open the file!" << std::endl; return -1; } int data; ifs.read((char*)&data, sizeof(int)); std::cout << data << std::endl; ifs.close(); return 0; }
以上是對在C++程序中如何讀取文件內容的介紹,可以根據實際需求選擇合適的方法去實現。
原創文章,作者:QLNFU,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/325345.html