Reading and writing to a binary file in c
Binary streams are primarily used for non-textual data, where the appearance of the content inside the file is nor important it does not care if they are not seen as plain text.
A buffer is a memory area that is temporarily used to store data before it is sent to its destination. Since the smallest object that can be represented in C is a character, access to a file is permitted at any character or byte boundary. Any number of characters can be read or written from a movable point, known as the file position indicator.
The characters are read, or written, in sequence from this point, and the position indicator moved accordingly. The position indicator is initially set to the beginning of a file when it is opened, but can also be moved explicitly not just because a read or write has been performed. This section focuses on how to open and close a disk data file and how to interpret the error messages that can be returned by these two functions. The FILE structure is the structure that controls files and it is defined in the header file stdio.
The following defines a file pointer:. In the FILE structure there is a member which represents the file position indicator. The function fopen opens a file and associates a stream with that opened file. You need to specify the method of opening the file and the filename as arguments. Here filename is a char pointer that references a string containing a filename.
The fopen function returns a pointer of type FILE. If an error occurs during the procedure to open the file, the fopen function returns NULL. When you use the a character and the file already exists, the contents of the file will be preserved and new data that you write will be added to the end.
If the file does not already exist, it will be created. This is in contrast to w ; this mode discards any data that may already be in the file if the file does not exist, it creates a new one.
When you use r , the file must already exist; if it does not, the call will fail and returns NULL. After a disk file is read, written, or appended with some new data, you have to disassociate the file from the specified stream. This is done by calling the fclose function:. If fclose closes a file successfully, it returns 0.
Otherwise, the function returns EOF. Normally, this function fails only when the disk is removed before the function is called or there is no more space left on the disk. Otherwise, the data saved in the file may be lost. In addition, failing to close a file when you are done with it may prevent other programs from accessing the file later. The next program shows how to open and close a text file, checking the values returned from the functions:.
In order to open a file using its file descriptor fd , you must use the fdopen function. This function behaves as fopen , but instead of opening a file using its name or path, it uses the file descriptor:. A way to get a file descriptor is with mkstemp:. This function generates a unique temporary file name from template string.
The last six characters of template must be "XXXXXX" and these are replaced with a string that makes the filename unique. The file is then created for reading or writing. Since the string will be modified, template must not be a string constant, but should be declared as a character array.
The mkstemp function returns the file descriptor of the temporary file or -1 on error. Read or write one character or byte at a time, with functions like fgetc and fputc. Read or write one line of text that is, one character line at a time, with functions like fgets and fputs.
Read or write one block of characters or bytes at a time, with fread and fwrite. In this course we are going to focus in the last way, block reading and writing, which is quite useful both for text and binary files. Here ptr is an array in which the data is stored.
The fread function returns the number of elements that are actually read during the attempt, if an error occurs or an EOF is encountered. If we get an error, as the fread function does not distinguish between end-of-file and another type of error, you must use feof and ferror to determine what happened we will see it in a moment.
The syntax for the fwrite function is:. The function returns the number of elements actually written; therefore, if no error has occurred, the value returned by fwrite should equal the third argument in the function.
The return value may be less than the specified value if an error occurs. As we have seen before, we have the feof function to determine when the end of a file is encountered.
This function returns 0 if the end of the file has not been reached; otherwise, it returns a nonzero integer. It returns 0 if no error has occurred; otherwise, it returns a nonzero integer. The following program read one block of characters at a time and write it in another file.
The reason is that you append a null character in line 35 after the last character read so that you ensure the block of characters saved in buffer is treated as a string and can be printed out on the screen properly by the printf function. In the last section you have learned how to read or write data sequentially to an opened disk file.
However, in some other cases, you need to access particular data somewhere in the middle of a disk file. The fseek function offers you the possibility to move the file position indicator to the spot you want to access in a file.
After reading the structure the pointer is moved to point at the next structure. A write operation will write to the currently pointed-to structure. After the write operation the file position indicator is moved to point at the next structure.
Remember that you keep track of things, because the file position indicator can not only point at the beginning of a structure, but can also point to any byte in the file. Only one block is requested. Changing the one into ten will read in ten blocks of x bytes at once. In this example we declare a structure rec with the members x,y and z of the type integer.
In the main function we open fopen a file for writing w. Then we check if the file is open, if not, an error message is displayed and we exit the program. Then we write the record to the file. We do this ten times, thus creating ten records. Take a look at the example:. With the fread we read-in the records one by one. After we have read the record we print the member x of that record.
The only thing we need to explain is the fseek option. The function fseek must be declared like this:. The fseek function sets the file position indicator for the stream pointed to by the stream. The new position, measured in characters from the beginning of the file, is obtained by adding offset to the position specified by whence.
Three macros are declared in stdio. Using negative numbers it is possible to move from the end of the file. In this example we are using fseek to seek the last record in the file. This counter is then used in the fseek statement to set the file pointer at the desired record. The result is that we read-in the records in the reverse order. The function rewind can be used like this:. With the fseek statement in this example we go to the end of the file. Then we rewind to first position in the file.
Then read-in all records and print the value of member x. Without the rewind you will get garbage. The int types must contain at least 16 bits to hold the required range of values. But it also can vary per compiler and the platform you are compiling for. On compilers for 8 and 16 bit processors including Intel x86 processors executing in 16 bit mode, such as under MS-DOS , an int is usually 16 bits and has exactly the same representation as a short.
On compilers for 32 bit and larger processors including Intel x86 processors executing in 32 bit mode, such as Win32 or Linux an int is usually 32 bits long and has exactly the same representation as a long. A int holds 32 bits thus you see 01 00 00 00 in your hex-editor. Try the following example to see the sizeof variable types for your target platform: So if you want to see only one byte in your hex editor, change the program to this: If you open the file test.
Or if you want to use int, accept that 4 bytes are written in the binary file but at least you know now why this is. Hi, after piratical and try to understanding write and read, my write is perfect what i want, but i can not read my bin file, i need some help please,.
I have tested them and they work, so good luck! Hi, Tanks for your help and support, my last message with my binary writer test, is perfect for me, because i can write a hex value directly in file , 00 to FF anywhere i want in file, but i cant read it with fread after, i want practice this with a small file i have create because my true application i want manage.
Is this the right declaration of a binary file Binary files should have b in the mode e. You are right, if you only look at the syntax. But if you open test. But to keep the syntax correct, we have changed the source code examples. The modes you can use are as follows: Is there a possibility to deal with data packing of the compiler in the structure, because due to this structure members are not necessarily continuous in the memory.
And mention that you get garbage without the rewind. If you seek to the end of file and then offset beyond the end of the file, you will be reading garbage, you need a negative offset. The search for the end of the file is only done, so we that we can rewind. I want to dump some memory into a file, a complex structure which contains pointers to list etc, and again want to set the same memory from this file. I want to store a character array data 89 bytes to a binary file. Please send the fwrite function code for this.
Is it possible to store current PC time to same binary file?