2010-05-05 2 views
0

Я вмешивался в какой-то код, но я не могу правильно прочитать весь файл ... много мусора добавляется к выходу. Как это исправить?MFC: Чтение всего файла в буфер

// wmfParser.cpp : Defines the entry point for the console application. 
// 

#include "stdafx.h" 
#include "wmfParser.h" 
#include <cstring> 

#ifdef _DEBUG 
#define new DEBUG_NEW 
#endif 


// The one and only application object 

CWinApp theApp; 

using namespace std; 

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) 
{ 
    int nRetCode = 0; 

    // initialize MFC and print and error on failure 
    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) 
    { 
     // TODO: change error code to suit your needs 
     _tprintf(_T("Fatal Error: MFC initialization failed\n")); 
     nRetCode = 1; 
    } 
    else 
    { 
     // TODO: code your application's behavior here. 
     CFile file; 
     CFileException exp; 
     if(!file.Open(_T("c:\\sample.txt"), CFile::modeRead, &exp)){    
      exp.ReportError(); 
      cout<<'\n';   
      cout<<"Aborting..."; 
      system("pause"); 
      return 0; 
     } 

     ULONGLONG dwLength = file.GetLength(); 
     cout<<"Length of file to read = " << dwLength << '\n'; 
     /* 
     BYTE* buffer; 
     buffer=(BYTE*)calloc(dwLength, sizeof(BYTE)); 
     file.Read(buffer, 25); 
     char* str = (char*)buffer;  
     cout<<"length of string : " << strlen(str) << '\n';  
     cout<<"string from file: " << str << '\n'; 
     */ 

     char str[100]; 

     file.Read(str, sizeof(str)); 
     cout << "Data : " << str <<'\n'; 
     file.Close(); 
     cout<<"File was closed\n"; 

     //AfxMessageBox(_T("This is a test message box")); 
     system("pause"); 
    } 
    return nRetCode; 
} 

UPDATE: специально ищет руководства относительно комментировал кода ... также как будет услышать другие предложения тоже ...

ответ

0

Ваша строка не нулем. Вы должны инициализировать строку str с memset(str,0, sizeof(str));

+0

http://paste.bradleygill.com/index.php?paste_id=33780 > это не сработало ... – deostroll

0

Я думаю, что это может быть ближе к тому, что вы ищете:

/* first method */ 

    ULONGLONG dwLength = file.GetLength(); 
    cout << "Length of file to read = " << dwLength << '\n'; 

    // make room for whole file, plus null 
    BYTE *buffer = (BYTE *) malloc(dwLength + 1); 

    file.Read(buffer, dwLength); // read whole file 
    *(buffer + dwLength) = '\0'; // add null 

    cout << "length of string : " << strlen(buffer) << '\n';  
    cout << "string from file: " << buffer << '\n'; 

    free(buffer); 

    file.SeekToBegin(); // Back to the beginning 

    /* second method */ 
    char str[dwLength + 1]; 

    file.Read(str, dwLength + 1); 
    str[dwLength] = '\0'; 

    cout << "Data : " << str <<'\n'; 
    file.Close(); 

    cout << "File was closed\n"; 
Смежные вопросы