在二进制文件中读取和写入缓冲区

时间:2011-10-13 03:26:32

标签: c fopen

以下是我的代码:

#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个不同的文件。这甚至可能吗?

2 个答案:

答案 0 :(得分:6)

我认为你正在寻找这样的东西:

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;

此致

答案 1 :(得分:1)

读取缓冲区的程序几乎相同,除了读取二进制文件的“rb”和fread()而不是fwrite()

请记住,您必须知道要读取的缓冲区有多大,并准备好接收它的正确大小的内存