簡體   English   中英

在二進制文件中讀取和寫入緩沖區

[英]Reading and writing a buffer in binary file

到目前為止,這是我的代碼:

#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個不同文件的方法。 這有可能嗎?

我認為您正在尋找這樣的東西:

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;

問候

讀取緩沖區的程序幾乎相同,除了讀取二進制文件和fread()而不是fwrite() “ rb”

記住,您將必須知道要讀取的緩沖區有多大,並准備好一些合適大小的內存來接收它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM