c write binary file


To write a binary file in C++ use write method. It is used to write a given number of bytes on the given stream, starting at the position of the «put» pointer. The file is extended if the put pointer is currently at the end of the file. If this pointer points into the middle of the file, characters in the file are overwritten with the new data.

If any error has occurred during writing in the file, the stream is placed in an error state.

Syntax of write method


To read a binary file in C++ use read method. It extracts a given number of bytes from the given stream and place them into the memory, pointed to by the first parameter. If any error is occurred during reading in the file, the stream is placed in an error state, all future read operation will be failed then.

gcount() can be used to count the number of characters has already read. Then clear() can be used to reset the stream to a usable state.

Write Binary Data

A way to store data in C# is to write to a binary file. A binary file allows developers to write data types such as int, bool, string, etc to a file. A binary file can then be read to retrieve those values.

Binary files are useful for saving application settings for example in a settings file. They can also save and load data entered by the user during runtime.

FileStream and BinaryWriter

Before you even start writing code, add the System.IO namespace to the top. All file writing operations come from that .NET namespace. More specifically, you will be using the FileStream and BinaryWriter classes.

FileStream is the class that either creates or opens a file. In the case of writing binary files, you want to use this to create a new file. Of course FileStream has several options when creating files.

BinaryWriter wraps around FileStream and as you can probably guess, it will write to the stream of that file. BinaryWriter is helpful because it allows programmers to write different C# data types to a file without having to worry about the specific bits. For example, a BinaryWriter can write a string or an uint with the same Write function.

To write more complex data structures to a binary file in C#, you have to convert the data structure to a simpler data type supported by the BinaryWriter. Another way is to write a structure of data in simple data type parts.

Here is a very simple code example:

The source code avo >using statements, these automatically let the developer know that FileStream and BinaryWriter are disposable objects. This way we do not have to explicitly dispose the objects.

Also notice that we still closed the file stream, which is a must whenever working with file or memory streams. But if that is the case, how come stream isn’t closed? Take a close look at the code and you will realize that writer wraps around stream . The BinaryWriter stream is the FileStream stream, thus closing writer automatically closes reader .

The last thing to notice is how flexible the Write function is. The function has a ton of overloads to let C# developers directly write a wide range of types into the file. With these basic building blocks, we can write and read some fairly complex files.

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.

6 Answers 6

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

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:

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

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:

Now compare that to your output:

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

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

I’m quite happy with my «make a weak pin storage program» solution. Maybe it will help people who need a very simple binary file IO example to follow.

This is an example to read and write binary jjpg or wmv video file. FILE *fout; FILE *fin;

this questions is linked with the question How to write binary data file on C and plot it using Gnuplot by CAMILO HG. I know that the real problem have two parts: 1) Write the binary data file, 2) Plot it using Gnuplot.

The first part has been very clearly answered here, so I do not have something to add.

For the second, the easy way is send the people to the Gnuplot manual, and I sure someone find a good answer, but I do not find it in the web, so I am going to explain one solution (which must be in the real question, but I new in stackoverflow and I can not answer there):

After write your binary data file using fwrite() , you should create a very simple program in C, a reader. The reader only contains the same structure as the writer, but you use fread() instead fwrite() . So it is very ease to generate this program: copy in the reader.c file the writing part of your original code and change write for read (and «wb» for «rb»). In addition, you could include some checks for the data, for example, if the length of the file is correct. And finally, your program need to print the data in the standard output using a printf() .

For be clear: your program run like this

Okey, with this program, in Gnuplot you only need to pipe the standard output of the reader to the Gnuplot, something like this:

This line, run the program reader, and the output is connected with Gnuplot and it plot the data.

*Because Gnuplot is going to read the output of the program, you must know what can Gnuplot read and plot and what can not.

I really struggled to find a way to read a binary file into a byte array in C++ that would output the same hex values I see in a hex editor. After much trial and error, this seems to be the fastest way to do so without extra casts. By default it loads the entire file into memory, but only prints the first 1000 bytes.

There are a few ways to do it. If I want to read and write binary I usually use open(), read(), write(), close(). Which are completely different than doing a byte at a time. You work with integer file descriptors instead of FILE * variables. fileno will get an integer descriptor from a FILE * BTW. You read a buffer full of data, say 32k bytes at once. The buffer is really an array which you can read from really fast because it’s in memory. And reading and writing many bytes at once is faster than one at a time. It’s called a blockread in Pascal I think, but read() is the C equivalent.

I looked but I don’t have any examples handy. OK, these aren’t ideal because they also are doing stuff with JPEG images. Here’s a read, you probably only care about the part from open() to close(). fbuf is the array to read into, sb.st_size is the file size in bytes from a stat() call.

Here’s a write: (here pix is the byte array, jwidth and jheight are the JPEG width and height so for RGB color we write height * width * 3 color bytes). It’s the # of bytes to write.

Look at man 2 open, also read, write, close. Also this old-style jpeg example.c: https://github.com/LuaDist/libjpeg/blob/master/example.c I’m reading and writing an entire image at once here. But they’re binary reads and writes of bytes, just a lot at once.

«But when I try to read from a file it is not outputting correctly.» Hmmm. If you read a number 65 that’s (decimal) ASCII for an A. Maybe you should look at man ascii too. If you want a 1 that’s ASCII 0x31. A char variable is a tiny 8-bit integer really, if you do a printf as a %i you get the ASCII value, if you do a %c you get the character. Do %x for hexadecimal. All from the same number between 0 and 255.

Понравилась статья? Поделиться с друзьями:
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: