C++ 打印文件内容到屏幕 - 代码示例和解释
使用以下函数来实现:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void printFile(string filename) {
ifstream file(filename);
if (file.is_open()) {
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close();
} else {
cout << 'Unable to open file' << endl;
}
}
int main() {
printFile('example.txt');
return 0;
}
这个函数使用 fstream 库中的 ifstream 类来打开文件,并使用 getline 函数逐行读取文件内容并打印到屏幕上。如果文件无法打开,则输出错误信息。在 main 函数中,我们可以调用 printFile 函数来打印文件内容。
原文地址: https://www.cveoy.top/t/topic/ozNK 著作权归作者所有。请勿转载和采集!