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; } }