Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1501004
  • 博文数量: 218
  • 博客积分: 6394
  • 博客等级: 准将
  • 技术积分: 2563
  • 用 户 组: 普通用户
  • 注册时间: 2008-02-08 15:33
个人简介

持之以恒

文章分类

全部博文(218)

文章存档

2013年(8)

2012年(2)

2011年(21)

2010年(55)

2009年(116)

2008年(16)

分类: C/C++

2010-03-26 02:17:17

根据文件的大小建立相应的缓冲,将文件读到内存中来

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sys/stat.h>
int get_filesize(const char *filename)
{
    struct stat f_stat;
    if (stat(filename, &f_stat) == -1)
    {
        return -1;
    }
    return f_stat.st_size;
}


int _tmain(int argc, _TCHAR* argv[])
{
    //获得文件的大小,开辟相应的缓冲区
    std::string fileName = "reponse-news.xml";
    int fileSize = get_filesize(fileName.c_str());
    int readBytes = 0;
    std::ifstream inputStream;
    char * szBuf = NULL;//数据缓冲
    if (fileSize > 0)
    {
        inputStream.open(fileName.c_str(),std::ios::ios_base::binary |std::ios::ios_base::in);
        if(inputStream.fail())
        {
            std::cerr<<"打开文件出错!";
            inputStream.clear();
            inputStream.close();
            return -1;
        }
        else
        {
            //开辟相应的缓冲区
            szBuf = new char[fileSize];
            if (szBuf != NULL)
            {
                while(!inputStream.eof() && readBytes < fileSize)
                {
                    inputStream.read(szBuf + readBytes,fileSize -
readBytes);
                    if (inputStream.fail())
                    {
                        delete szBuf;
                        break;
                    }
                    readBytes += inputStream.gcount();
                }
                std::cout<<"读取字符数:"<<readBytes<<"字节"<<std::endl;
                std::cout<<"内容为:"<<std::endl;
                std::cout<<szBuf;
            }
            inputStream.clear();
            inputStream.close();
        }
    }
    if (szBuf != NULL)
    {
        delete szBuf;
        szBuf = NULL;
    }
    getchar();
    return 0;
}

结果:

阅读(12428) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~