c++讀文件


FileFormatDefine.h

#ifndef _WIN32TOOLS_FILEFORMATDEFINE_H_ 
#define _WIN32TOOLS_FILEFORMATDEFINE_H_ 
  
const char FILE_END_CHAR    = 26; 
  
#endif _WIN32TOOLS_FILEFORMATDEFINE_H_ 

FileReader.h

#ifndef _WIN32TOOLS_FILEREADER_H_ 
#define _WIN32TOOLS_FILEREADER_H_ 
  
#include <string> 
#include "FileFormatDefine.h" 
  
namespace Win32Tools 
{ 
    class CFileReader 
    { 
    public: 
        static char* ReadBuffer(const std::string& aFileName); // 讀取文件至內存 
    }; 
}; 
  
#endif _WIN32TOOLS_FILEREADER_H_ 
#include "StdAfx.h" 
#include "Filereader.h" 
#include <stdio.h> 
  
using namespace std; 
  
namespace Win32Tools 
{ 
    char* CFileReader::ReadBuffer(const string& aFileName) 
    { 
        // 若要一個 byte 不漏地讀入整個文件,只能采用二進制方式打開 
        FILE* pFile = fopen (aFileName.c_str(), "rb"); 
        if(pFile == NULL) 
            return NULL; 
  
        // 獲取文件大小 
        fseek(pFile , 0 , SEEK_END); 
        long lSize = ftell (pFile); 
        rewind(pFile); 
        if(0 == lSize) 
            return NULL; 
  
        // 分配內存存儲整個文件 
        char* buffer = new char[lSize + 1]; 
        if(buffer == NULL) 
            return NULL; 
  
        /* 將文件拷貝到buffer中 */
        size_t result = fread(buffer, 1, lSize, pFile); 
        if(result != lSize) 
        { 
            delete buffer; 
            buffer = NULL; 
            return NULL; 
        } 
        buffer[lSize] = FILE_END_CHAR; 
  
        // 關閉文件並釋放內存 
        fclose (pFile); 
        return buffer;   
    } 
} 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM