C加加打开文件代码样例
下面是一个简单的 C++ 文件打开示例程序:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// 打开文件
ifstream file("example.txt");
// 检查文件是否打开成功
if (!file.is_open()) {
cout << "文件打开失败" << endl;
return 1;
}
// 读取文件内容
string line;
while (getline(file, line)) {
cout << line << endl;
}
// 关闭文件
file.close();
return 0;
}
在上面的示例中,我们使用 ifstream 类打开文件并读取其中的内容。is_open() 函数用于检查文件是否打开成功。当读取完文件内容后,需要使用 close() 函数关闭文件。
原文地址: https://www.cveoy.top/t/topic/Nam 著作权归作者所有。请勿转载和采集!