C语言 读取和写入二进制文件中的缓冲区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7749134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:53:16  来源:igfitidea点击:

Reading and writing a buffer in binary file

cfopen

提问by Questioneer

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;
}

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?

我正在尝试编写一些验证我写入文件的内容,然后从文件中读取并验证我从文件中读取的内容。如何最好地做到这一点?我还需要想办法将相同的内容写入 2 个不同的文件。这甚至可能吗?

回答by César Ortiz

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;

Regards

问候

回答by Martin Beckett

The program to read a buffer is almost the same except "rb" for read binary and fread()instead of fwrite()

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

Remember you will have to know how big the buffer you are going to read is and have some memory of the right size ready to receive it

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