To reply from @Caiqueromero attacked the problem in a way that I consider unexpected, but very good. He also talks about the other things related to opening files and left great reading references.
I came here to talk about fwrite
.
The first thing is to see the function signature:
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
Okay, let’s understand what this means. The function says it will print on stream
past tense count
elements of size size_t
pointed out by ptr
.
If you want to print ten integers of a vector v
in the archive f
, you could do:
fwrite(v, sizeof(int), 10, f);
Where:
v
is the vector, so it can be worked as a pointer
sizeof(int)
is the size of the unit of the vector; it could also be sizeof(*v)
or sizeof(v[0])
, but I’d rather be the guy
10
is the amount of elements
f
is the open file for writing
Some remarks:
fwrite
writes the bytes, literally
fprintf
writes the textual representation
- It is appropriate to open the file in binary mode when knowing that the
fwrite
, and normally opens in textual mode to fprintf
for performance reasons
- to open for binary reading,
rb
as an argument from fopen
; writing is with wb
- if you try to open a textual file filled with
fwrite
, you will get a result like this (credits to @Caiqueromero by print):
I expected an answer with
fwrite
, in this certainly worth my +1– Jefferson Quesado
Me too , but it sure was worth my +1
– Allan Vinícius