读取文件内容并保存到string中

本文介绍如何使用C++将文件内容读取并保存到std::string对象中,通过示例代码展示了读取文件的完整过程,并讨论了std::string的最大容量。
摘要由CSDN通过智能技术生成
(最近在调整生物钟,晚上9点半前睡觉,早晨很早就醒了,利用早晨充足的时间可以读英语和写代码,感觉很好。)
不知道你是否考虑过这个问题:std::string究竟可以存储多大的字符串呢?
理论上std::string可以存储 std::string::max_size大小的内容。 
我在Visual studio 2008上运行的结果是:max_size:4294967294

#include <iostream>     // std::cout
#include <fstream>      // std::ifstream
#include <string>

using namespace std;

bool readFileToString(string file_name, string& fileData)
{
    bool ret = false;
    ifstream file(file_name.c_str(),  std::ifstream::binary);
    
    if(file)
    {
        // Calculate the file's size, and allocate a buffer of that size.
        file.seekg(0, file.end);
        const int file_size = file.tellg();
        char* file_buf = new char [file_size+1];
        //make sure the end tag '\0' of string.
        memset(file_buf, 0, file_size+1);
        
        // Read the entire file into the buffer.
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值