You are not logged in.

#1 2012-12-13 14:29:27

kdar
Member
From: Sweet home Alabama!
Registered: 2009-06-27
Posts: 356

Write output to binary file in C/C++?

How can I write output to a file in binary format instead of ascii?

Or... if I am using a buffer.. to write a buffer to binary format instead of ascii?

I am writing a lot of data to a text file and I would like to reduce the size by writing it all into a binary file instead of ascii?

Last edited by kdar (2012-12-13 14:36:41)

Offline

#2 2012-12-13 14:53:42

mhd
Member
Registered: 2008-02-06
Posts: 21

Re: Write output to binary file in C/C++?

Basic I/O?

char buffer[100];

// C++ style
ofstream file;
file.open ("data.bin", ios::out | ios::binary);
file.write(buffer, sizeof buffer);

/* C style */
FILE* file2 = fopen("data2.bin", "wb");
fwrite(buffer, sizeof buffer, 1, file2);

A lot of people prefer the old C style functions for binary i/o even in C++ (and iostream for formatted i/o). Writing and readong more complex structures requires some castin, in C++ usually done with reinterpret_cast<char*>(someStructure).

Offline

#3 2012-12-13 17:16:05

kdar
Member
From: Sweet home Alabama!
Registered: 2009-06-27
Posts: 356

Re: Write output to binary file in C/C++?

Strange... doing C++ style returns me "error: 'flowC' does not name a type'.
What is this about?

Also.. Do you know how to write the buffer only when its full? I saw somewhere I can use something like this...

char buffer[2048];
flowC.rdbuff()->pubsetbuf(buffer, 2048);
.......
flowC << ValOne <<< ", " << ValTwo << endl;

Last edited by kdar (2012-12-13 17:16:59)

Offline

#4 2012-12-14 12:09:42

drobole
Member
From: Norway
Registered: 2012-07-23
Posts: 125

Re: Write output to binary file in C/C++?

Is flowC decalred in a different namespace?

Offline

#5 2012-12-15 17:09:31

Lux Perpetua
Member
From: The Local Group
Registered: 2009-02-22
Posts: 69

Re: Write output to binary file in C/C++?

kdar wrote:

Strange... doing C++ style returns me "error: 'flowC' does not name a type'.
What is this about?

This sounds like a simple problem, but you're not providing enough information.  Write up a complete but minimal code example that illustrates the problem you're talking about, and post it here.

Offline

Board footer

Powered by FluxBB