How to input and output files in C++?
In C++, you can utilize ifstream and ofstream for file input and output operations.
Example of file input operation:
#include <iostream>
#include <fstream>
int main() {
std::ifstream inputFile("input.txt"); // 打开输入文件
if (inputFile.is_open()) {
std::string line;
while (std::getline(inputFile, line)) {
std::cout << line << std::endl; // 输出文件内容
}
inputFile.close(); // 关闭文件
} else {
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
Example of file output operations:
#include <iostream>
#include <fstream>
int main() {
std::ofstream outputFile("output.txt"); // 打开输出文件
if (outputFile.is_open()) {
outputFile << "Hello, world!" << std::endl; // 写入文件
outputFile.close(); // 关闭文件
} else {
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
The above examples demonstrate how to open, read, and write files. In practical applications, file operations need to be performed according to specific requirements, and it is important to remember to close file streams promptly.