binaryfiles - Read/Write int Binary File in C error -
i facing error reading/writing binary file in c. issue is: - write int (e.g. 2) file using fwrite - try read int file using fread - when read it, doesn't come out 2, rather long number e.g. 967899906 or 2071332354 or 1030372866 (always different).
i write binary file in c this:
file * writefile = fopen("test.bin","wb"); //test int vars int test1 = 1; int test2 = 2; int test3 = 3; //writing ints binary file fwrite(&test1,1,1, writefile); fwrite(&test2,1,1, writefile); fwrite(&test3,1,1, writefile); fclose(writefile);
i read file this:
file *readfile = fopen("test.bin","rb"); int data; while(fread(&data,1,1, readfile)==1){ printf("%d", data); //here output random number } fclose(readfile);
fwrite wants, second parameter, size of data write, in case sizeof(int)
same thing fread
#include <stdio.h> int main(void) { file * writefile = fopen("test.bin","wb"); if (writefile != null) { //test int vars int test1 = 1; int test2 = 2; int test3 = 3; //writing ints binary file fwrite(&test1,sizeof(test1),1, writefile); fwrite(&test2,sizeof(test2),1, writefile); fwrite(&test3,sizeof(test3),1, writefile); fclose(writefile); } else { perror("error opening file write: "); return 1; } file *readfile = fopen("test.bin","rb"); if (readfile != null) { int data; while(fread(&data,sizeof(data),1, readfile)==1){ printf("%d\n", data); } fclose(readfile); } else { perror("error opening file read: "); return 1; } return 0; }
hint: test if fopen
succeed.
edit
to use 1 byte variable, commented, use uint8_t
variables
#include <stdio.h> #include <stdint.h> int main(void) { file * writefile = fopen("test.bin","wb"); if (writefile != null) { //test int vars uint8_t test1 = 1; uint8_t test2 = 2; uint8_t test3 = 3; //writing ints binary file fwrite(&test1,sizeof(test1),1, writefile); fwrite(&test2,sizeof(test2),1, writefile); fwrite(&test3,sizeof(test3),1, writefile); fclose(writefile); } else { perror("error opening file write: "); return 1; } file *readfile = fopen("test.bin","rb"); if (readfile != null) { uint8_t data; while(fread(&data,sizeof(data),1, readfile)==1){ printf("%d\n", data); } fclose(readfile); } else { perror("error opening file read: "); return 1; } return 0; }
Comments
Post a Comment