Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and write to binary files in C?

Does anyone have an example of code that can write to a binary file. And also code that can read a binary file and output to screen. Looking at examples I can write to a file ok But when I try to read from a file it is not outputting correctly.

like image 522
user1257114 Avatar asked Jul 11 '13 16:07

user1257114


People also ask

What are the C function used to read and write a file in binary mode?

You can even use fputs(). Only strings can be read or write instead of integers, float or characters. 18) What are the C functions used to read or write a file in Binary Mode.? fwrite(pointer, size, count , filepointer);

What is binary file in C?

Binary fileIt contains 1's and 0's, which are easily understood by computers. The error in a binary file corrupts the file and is not easy to detect. In binary file, the integer value 1245 will occupy 2 bytes in memory and in file. A binary file always needs a matching software to read or write it.


1 Answers

Reading and writing binary files is pretty much the same as any other file, the only difference is how you open it:

unsigned char buffer[10]; FILE *ptr;  ptr = fopen("test.bin","rb");  // r for read, b for binary  fread(buffer,sizeof(buffer),1,ptr); // read 10 bytes to our buffer 

You said you can read it, but it's not outputting correctly... keep in mind that when you "output" this data, you're not reading ASCII, so it's not like printing a string to the screen:

for(int i = 0; i<10; i++)     printf("%u ", buffer[i]); // prints a series of bytes 

Writing to a file is pretty much the same, with the exception that you're using fwrite() instead of fread():

FILE *write_ptr;  write_ptr = fopen("test.bin","wb");  // w for write, b for binary  fwrite(buffer,sizeof(buffer),1,write_ptr); // write 10 bytes from our buffer 

Since we're talking Linux.. there's an easy way to do a sanity check. Install hexdump on your system (if it's not already on there) and dump your file:

mike@mike-VirtualBox:~/C$ hexdump test.bin 0000000 457f 464c 0102 0001 0000 0000 0000 0000 0000010 0001 003e 0001 0000 0000 0000 0000 0000 ... 

Now compare that to your output:

mike@mike-VirtualBox:~/C$ ./a.out  127 69 76 70 2 1 1 0 0 0 

hmm, maybe change the printf to a %x to make this a little clearer:

mike@mike-VirtualBox:~/C$ ./a.out  7F 45 4C 46 2 1 1 0 0 0 

Hey, look! The data matches up now*. Awesome, we must be reading the binary file correctly!

*Note the bytes are just swapped on the output but that data is correct, you can adjust for this sort of thing

like image 84
Mike Avatar answered Sep 28 '22 04:09

Mike