C++一次性读取文件所有内容

C++一次性读取文件所有内容要利用到stringstream类,需要加入头文件

#include<sstream>

以及ifstream的rdbuf()方法。

完整代码

#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;

int main()
{
    ifstream fin("xly2016I.txt");   // filename: xly2016I.txt
    stringstream buffer;            // stringstream object
    buffer << fin.rdbuf();          // read file content in stringstream object
    string str(buffer.str());       // store file content in a string
    cout << str;                    // output file content
    return 0;
}

 

  • 11
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
可以使用C++中的文件流来读取文件内容。下面是一个简单的例子: ```c++ #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream myfile("example.txt"); // 创建一个文件输入流对象并打开文件 string line; if (myfile.is_open()) { // 判断文件是否成功打开 while (getline(myfile, line)) { // 从文件中逐行读取内容 cout << line << endl; // 输出每一行的内容 } myfile.close(); // 关闭文件 } else { cout << "Unable to open file." << endl; } return 0; } ``` 上述代码将打开名为example.txt的文件,并逐行输出其内容。在代码中,我们使用了`ifstream`类来创建一个文件输入流对象。我们将文件名作为参数传递给构造函数,该构造函数将打开文件并返回一个可以用于读取文件内容的流对象。在代码的主循环中,我们使用`getline`函数逐行读取文件内容,并将其存储在一个字符串变量`line`中。最后,我们将每一行的内容输出到控制台中,并在循环结束后关闭文件流对象。 如果您想一次性读取整个文件内容,可以使用以下代码: ```c++ #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream myfile("example.txt"); // 创建一个文件输入流对象并打开文件 string content; if (myfile.is_open()) { // 判断文件是否成功打开 // 获取文件长度 myfile.seekg(0, ios::end); int length = myfile.tellg(); myfile.seekg(0, ios::beg); // 分配足够的内存来存储文件内容 content.resize(length); // 从文件读取内容 myfile.read(&content[0], length); myfile.close(); // 关闭文件 } else { cout << "Unable to open file." << endl; } cout << content << endl; // 输出文件内容 return 0; } ``` 在上述代码中,我们首先创建了一个`ifstream`对象并打开了文件。然后,我们使用`seekg`和`tellg`函数获取文件长度,并分配足够的内存来存储文件内容。最后,我们使用`read`函数从文件读取内容,并将其存储在字符串变量`content`中。最后,我们将整个文件内容输出到控制台中,并在循环结束后关闭文件流对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值