C++文件处理使用标准库:fstream 。它的三个类型:ifstream, ofstream, fstream.
ifstream作用 | 从文件读取数据 |
ofstream作用 | 向文件写入数据 |
fstream作用 | 读写文件 |
如上图所示:如果只需要从文件中读取数据,可以使用ifstream;如果需要向文件中写入数据,则需要使用ofstream;而如果需要读写操作,则可以使用fstream。
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream inputFile;
std::string line;
inputFile.open("example.txt");
if (inputFile.is_open()) {
while (getline(inputFile, line)) {
std::cout << line << std::endl;
}
inputFile.close();
} else {
std::cout << "Unable to open file!" << std::endl;
}
return 0;
}
在这里导入了fstreamC++库,使其可以使用ifstream类型定义一个变量,名为inputFile.可以用getline函数来逐行读取。以及使用close()函数关闭文件,与其相反的是open()函数。它可以打开文件。