2012-11-04 81 views
0

這基本上是我用來存儲整個文件的代碼的一部分,並且效果很好......但是當我嘗試存儲大於120的整數時就像程序寫入似乎是一堆垃圾,而不是我想要的整數。有小費嗎 ?我是一名大學生,不知道發生了什麼。無法將整數寫入二進制文件C++

int* temp 

    temp = (int*) malloc (sizeof(int)); 

    *temp = atoi(it->valor[i].c_str()); 

    //Writes the integer in 4 bytes 
    fwrite(temp, sizeof (int), 1, arq); 

    if(ferror(arq)){ 
     printf("\n\n Error \n\n"); 
     exit(1); 
    } 

    free(temp); 

我已經檢查了atoi一部分,它確實返回我想寫的數量。

+2

如何驗證是否寫入了正確的數字? –

+0

如果你想得到不僅僅是野蠻猜測的幫助,你需要發佈一個完整的(希望最小的)例子。您目前顯示的代碼看起來不錯。你確定'it-> valor [i]'總是一個有效的字符串嗎? – jrok

+1

沒有理由給'malloc',只是創建一個'int temp',並將它的地址傳遞給''fwrite',就像'fwrite(&temp,sizeof(temp),1,arq);' – Collin

回答

2

我改變,並添加一些代碼,它工作正常:

#include <iostream> 

using namespace std; 

int main() 
{ 

    int* temp; 
    FILE *file; 
    file = fopen("file.bin" , "rb+"); // Opening the file using rb+ for writing 
             // and reading binary data 
    temp = (int*) malloc (sizeof(int)); 

    *temp = atoi("1013");   // replace "1013" with your string 

    //Writes the integer in 4 bytes 
    fwrite(temp, sizeof (int), 1, file); 

    if(ferror(file)){ 
     printf("\n\n Error \n\n"); 
     exit(1); 
    } 

    free(temp); 
} 

確保您打開用正確的參數的文件,你給ATOI(STR)的字符串是正確的。

我檢查使用十六進制編輯器的二進制文件,輸入1013

+0

請不要在答案中提倡錯誤的C++代碼(請參閱我的答案,原因)。 –

+0

謝謝你的回答羅伊!這是奇怪的部分,我的程序和你的完全一樣,當我用十六進制編輯器打開文件後寫1001例如他顯示這個:十六進制4D 00 00 00十進制077 000 000 000八進制115 000 000 000二進制01001101 00000000 00000000 00000000.我使用Linux的Ubuntu的X64和G + + – user1270116

+0

@Konrad魯道夫:是的,甚至沒有注意到它,謝謝你的評論。我通常用C++編寫,但我猜,他的原始代碼包含C語法讓我困惑。 –

1
int i = atoi("123"); 
std::ofstream file("filename", std::ios::bin); 
file.write(reinterpret_cast<char*>(&i), sizeof(i)); 
  • 這裏不要使用指針數之後。
  • 從不在C++中使用malloc/free
  • 使用C++文件流,而不是C流。