The @CaiqueRomero response attacked the problem on the one hand that I consider unexpected, but very good. He also talks about all the other things about 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 that means. The function says that it will print in stream
passed% with% elements of size count
pointed to size_t
.
If you want to print ten integers of a ptr
vector in the v
file, you could do:
fwrite(v, sizeof(int), 10, f);
Where:
-
f
is the vector, so it can be worked as a pointer
-
v
is the size of the vector unit; could also be sizeof(int)
or sizeof(*v)
, but I'd rather pass the type
-
sizeof(v[0])
is the number of elements
-
10
is the file open for writing
Some comments:
-
f
writes bytes, literally
-
fwrite
writes the textual representation
- It is possible to open the file in binary mode when knowing that
fprintf
is going to be used, and it usually opens in textual mode to fwrite
for performance issues
- to open for binary reading,
fprintf
as argument of rb
; write is with fopen
- If you try to textically open a file filled with
wb
, you'll get a result like this (credits to @ CaiqueRomero by print):