学习如何从文件读取流和向文件写入流。
fstream标准库 中定义了三个新的数据类型:
从文件读取信息或者向文件写入信息之前,必须先打开文件。
ofstream和fstream对象都可以用来打开文件进行读写操作,如果只需要打开文件进行读操作,则使用ifstream对象。
下面是open()函数的标准语法,open()函数是fstream、ifstream和ofstream对象的一个成员。
void open(const cha *filename, ios::openmode mode);
在这里,open()成员函数的第一参数指定要打开的文件的名称和位置,第二个参数定义文件被打开的模式。
模式选择:
可以将上述俩种或俩种以上的模式结合使用,例如你想要以写入模式打开文件,并希望截断文件,以防止文件已存在,那么可以使用下面的语法:
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc);
类似的如果想要打开一个文件用于读写,可以使用:
ifstream afile;
afile.open("file.dat", ios::out | ios::in);
当C++程序终止时,它会自动刷新所有流,释放所有分配的内存,并关闭所有打开的文件。但程序员应该养成一个好习惯,在程序终止前关闭所有打开的文件。
下面是close()函数的标准语法,close()函数也是fstream、ifstream和ofstream对象的一个成员。
void close();
在C++编程中,我们使用**流插入运算符(<<)**向文件写入信息。
outputFile << "This is some data that I'm writing to the file." << std::endl;
在C++编程中,我们使用**流提取运算符(>>)**从文件读取信息。
// 从输入文件中读取整数并计算他们的和
while (inputFile >> number){
sum += number;
}
在C++中可以使用文件流对象的方法和标志来进行文件检查以确保文件操作的正确性。
std::ifstream inFile("example.txt");
if (inFile.is_open()) {
// 文件已成功打开,可以进行读取操作
} else {
// 文件打开失败,进行错误处理
}
std::ifstream inFile("example.txt");
if (inFile.good()) {
// 文件流处于有效状态,可以进行读取操作
} else {
// 文件流处于无效状态,进行错误处理
}
std::ifstream inFile("example.txt");
if (inFile.fail()) {
// 文件操作失败,进行错误处理
} else {
// 文件操作成功,可以进行读取操作
}
#include
#include
int main(){
//打开输入文件以读取数据
std::ifstream inputFile("input.txt");
if (!inputFile.is_open()){
std::cerr << "Failed to open the input file."<< std::endl;
return 1;
}
int sum = 0;
int number;
// 从输入文件中读取整数并计算他们的和
while (inputFile >> number){
sum += number;
}
inputFile.close();
//打开输出文件以写入结果
std::ofstream outputFile("output.txt");
if (!outputFile.is_open()){
std::cerr << "Failed to open the output file." << std::endl;
return 1;
}
// 将计算结果写入输出文件
outputFile << "Sum of numbers in the input file: " << sum << std::endl;
outputFile.close(); //关闭输出文件
std::cout << "Sum has been written to the output file." << std::endl;
return 0;
}