读取和写入二进制文件缓冲 [英] Reading and writing a buffer in binary file

查看:185
本文介绍了读取和写入二进制文件缓冲的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的code截至目前:

Here is my code as of now:

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

I'm trying to write something verify i wrote to the file and then read from the file and verify i read from the file. How best is there to do this? I also need to figure out a way to write the same thing to 2 different files. Is this even possible?

推荐答案

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

I think you are looking for something like this:

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;

问候

这篇关于读取和写入二进制文件缓冲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆