2011-10-13 94 views
0

這裏是我的代碼截至目前:讀取和寫入二進制文件的緩衝區

#include <stdio.h> 
#include "readwrite.h" 

int main() 
{ FILE* pFile; 
    char buffer[] = {'x' ,'y','z',0}; 
    pFile = fopen("C:\\Test\\myfile.bin","wb"); 

    if (pFile){ 
     fwrite(buffer,1,sizeof(buffer),pFile); 

    printf("The buffer looks like: %s",buffer); 
    } 
    else 
    printf("Can't open file"); 


    fclose(pFile); 
    getchar(); 
    return 0; 
} 

我想寫點東西驗證我寫的文件,然後從文件中讀取和驗證我讀出文件。如何做到這一點最好?我還需要找出一種方法將相同的東西寫入2個不同的文件。這甚至有可能嗎?

回答

3

我認爲你正在尋找的東西是這樣的:

FILE* pFile; 
char* yourFilePath = "C:\\Test.bin"; 
char* yourBuffer = "HelloWorld!"; 
int yorBufferSize = strlen(yourBuffer) + 1; 

/* Reserve memory for your readed buffer */ 
char* readedBuffer = malloc(yorBufferSize); 

if (readedBuffer==0){ 
    puts("Can't reserve memory for Test!"); 
} 

/* Write your buffer to disk. */ 
pFile = fopen(yourFilePath,"wb"); 

if (pFile){ 
    fwrite(yourBuffer, yorBufferSize, 1, pFile); 
    puts("Wrote to file!"); 
} 
else{ 
    puts("Something wrong writing to File."); 
} 

fclose(pFile); 

/* Now, we read the file and get its information. */ 
pFile = fopen(yourFilePath,"rb"); 

if (pFile){ 
    fread(readedBuffer, yorBufferSize, 1, pFile); 
    puts("Readed from file!"); 
} 
else{ 
    puts("Something wrong reading from File.\n"); 
} 

/* Compare buffers. */ 
if (!memcmp(readedBuffer, yourBuffer, yorBufferSize)){ 
    puts("readedBuffer = yourBuffer"); 
} 
else{ 
    puts("Buffers are different!"); 
} 

/* Free the reserved memory. */ 
free(readedBuffer); 

fclose(pFile); 
return 0; 

問候

+0

優秀!!!我會如何做到這一點,而不是我會用數字而不是字符串和字母? – Questioneer

+0

數字,結構,字符串...全部是具有存儲器地址的存儲器塊。所以你可以把這塊內存塊轉換成一個字節緩衝區,然後寫入/讀取到一個沒有問題的文件。嘗試像(char *)&myIntegerVariable類似的方式獲取myIntegerVariable的地址和sizeof(int)來獲得變長。祝你好運。 –

1

讀取緩存的程序幾乎是除「RB」同爲讀取的二進制和fread()代替fwrite()

記住,你必須知道你要讀取緩衝區有多大,並有一定的記憶大小合適準備好接受它

+0

我是否可以將緩衝區大小包裝在#define中並以此方式進行更改?我在緩衝區之後需要0,所以當我編譯和運行時我不會看到「垃圾」。例如,當我使用上面的代碼進行printf時,我看到了x y和z,但之後我看到了垃圾,因爲它搜索了null。 – Questioneer

+0

@Questioneer,簡單的測試是最簡單的 - 稍後您可以檢測文件大小並瞭解malloc。你需要在c後面標記字符串結尾的零結果,你打印一個字符串 - 你也可以遍歷緩衝區並打印單個字符 –

+0

我知道這一點?!?! – Questioneer

相關問題