2011-06-03 76 views
2

我想一個基本的輸入,輸出(及附加)在C++中,這裏是我的代碼二進制文件的輸入,輸出和追加C++

#include <iostream> 
#include <fstream> 
#include <stdio.h> 
#include <stdlib.h> 

using namespace std; 



void escribir(const char *); 
void leer(const char *); 

int main() 
{ 
    escribir("example.bin"); 
    leer("example.bin"); 
    system("pause"); 
    return 0; 
} 

void escribir(const char *archivo) 
{ 
    ofstream file (archivo,ios::app|ios::binary|ios::ate); 
    if (file.is_open()) 
    { 
     file<<"hello"; 
     cout<<"ok"<<endl; 
    } 
    else 
    { 
     cout<<"no ok"<<endl; 
    } 
    file.close(); 


} 

void leer(const char *archivo) 
{ 
    ifstream::pos_type size; 
    char * memblock; 

    ifstream file (archivo,ios::in|ios::binary|ios::ate); 
    if (file.is_open()) 
    { 
     size = file.tellg(); 
     memblock = new char [size]; 
     file.seekg (0, ios::beg); 
     file.read (memblock, size); 
     file.close(); 

     cout<< memblock<<endl; 

     delete[] memblock; 
    } 
    else 
    { 
     cout << "no ok"<<endl; 
    } 
} 

它運行良好的第一次,但是當我運行它第二次將「hello」和一些extrange字符添加到文件中。

你能幫我弄清楚有什麼問題嗎?

在此先感謝

+0

我不能重現此:我得到完全 「hellohello」'68 1207 6C 6C 6F 68 6C 6F 6C 6f'與VC10 。你能發佈文件的十六進制內容嗎? – 2011-06-03 02:39:05

+0

Argh。沒有看到滾動條。 – 2011-06-03 03:04:56

回答

5

似乎問題並不與文件,而是閱讀和顯示它,即在這裏:

memblock = new char [size]; 
file.seekg (0, ios::beg); 
file.read (memblock, size); 
file.close(); 
cout<< memblock<<endl; 

與COUT顯示預期字符串以null結尾。但是,您只爲文件內容分配了足夠的空間,而不是終結器。添加以下應使其工作:

memblock = new char [size+1]; // add one more byte for the terminator 
file.seekg (0, ios::beg); 
file.read (memblock, size); 
file.close(); 
memblock[size] = 0; // assign the null terminator 
cout<< memblock<<endl; 
1

我認爲你的錯誤輸出:

memblock = new char [size]; 
    file.seekg (0, ios::beg); 
    file.read (memblock, size); 
    file.close(); 

    cout<< memblock<<endl; 

是否cout << memblock << endl知道寫準確size字節輸出流?或者是char foo[]被認爲是C風格的字符串,它必須以ascii NUL結尾?

如果必須用ASCII NUL被終止,試試這個:

memblock = new char [size + 1]; 
    file.seekg (0, ios::beg); 
    file.read (memblock, size); 
    file.close(); 
    memblock[size]='\0'; 

    cout<< memblock<<endl;