C++ 打印文件内容到屏幕:无需 getline 函数
以下是一个使用C++标准库函数的示例程序,通过读取文件并将其内容打印到屏幕。
#include <iostream>
#include <fstream>
#include <string>
void printFileContent(std::string fileName)
{
std::ifstream file(fileName);
if (file.is_open())
{
char c;
while (file.get(c))
{
std::cout << c;
}
file.close();
}
else
{
std::cout << 'Unable to open file' << std::endl;
}
}
int main()
{
std::string fileName = "example.txt";
printFileContent(fileName);
return 0;
}
此代码通过使用 ifstream 对象打开文件,然后使用 file.get(c) 函数逐字符读取文件内容,并将其打印到屏幕。
优点:
- 不使用
getline函数,避免了读取整行带来的性能开销,尤其是在处理大型文件时效果更明显。 - 代码简洁易懂,易于理解和维护。
缺点:
- 不支持读取包含换行符的文本,因为
file.get(c)函数只读取单个字符。
注意:
- 确保
example.txt文件存在于程序的运行目录中,或指定文件的完整路径。 - 可以根据需要修改
printFileContent函数的名称和参数。
原文地址: https://www.cveoy.top/t/topic/ozNY 著作权归作者所有。请勿转载和采集!