#include <iostream>
#include <fstream>
int main() {
// 打开文件,使用ofstream进行写操作
std::ofstream outFile;
outFile.open("example.txt");
if (outFile.is_open()) {
// 如果文件成功打开,写入一些内容
outFile << "Hello, C++ file handling!" << std::endl;
outFile.close(); // 关闭文件
std::cout << "File written successfully." << std::endl;
} else {
// 如果文件打开失败,输出错误信息
std::cerr << "Unable to open file." << std::endl;
}
// 打开文件,使用ifstream进行读操作
std::ifstream inFile;
inFile.open("example.txt");
if (inFile.is_open()) {
// 如果文件成功打开,读取内容并输出到控制台
std::string line;
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
inFile.close(); // 关闭文件
} else {
// 如果文件打开失败,输出错误信息
std::cerr << "Unable to open file." << std::endl;
}
return 0;
}
#include <iostream> 和 #include <fstream> 分别用于标准输入输出和文件流操作。std::ofstream 创建一个文件输出流对象 outFile,用于写入文件;使用 std::ifstream 创建一个文件输入流对象 inFile,用于读取文件。open 方法打开文件。如果文件成功打开,则可以进行读写操作;否则输出错误信息。outFile << "..." 向文件中写入内容。close 方法关闭文件,确保所有数据都被正确写入或读取。std::getline 逐行读取文件内容,并将其输出到控制台。以上代码展示了如何在 C++ 中打开、写入和读取文件的基本操作。
上一篇:c++ substring
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站