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

这是我现在的代码:

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

我正在尝试写一些validation我写入文件,然后从文件中读取并validation我从文件中读取。 这样做有多好? 我还需要找到一种方法将相同的东西写入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; 

问候

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

请记住,您必须知道要读取的缓冲区有多大,并且有一些正确大小的内存可以接收它