Reading and writing a buffer in binary file
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?
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
The program to read a buffer is almost the same except "rb" for read binary and fread()
instead of 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
精彩评论