Outputting to file in the most compressed form (c++)

  • #1

Main Question or Discussion Point

Hi, I'm just wondering, usually when I output to file in C++ I just do like:

fout.open("output.txt",ios::eek:ut);
fout.precision(13);
fout << data1 << " " << data2 << " " << data3 << endl;

or something to that effect. i.e. I use c++'s file streams. However, for my current application minimizing space is an absolute must. Therefore, are there other ways of outputting this same data (columns of 3 doubles) to a file that will create a smaller file? I've experimented with fprintf and such but it seems to create the same sized file. Any help is greatly appreciated.
 

Answers and Replies

  • #2
chroot
Staff Emeritus
Science Advisor
Gold Member
10,226
34
Use zlib, probably the most common compression library on the planet.

If you want a C++ stream version of it, try gzstream

- Warren
 
Last edited:
  • #3
Use zlib, probably the most common compression library on the planet.

If you want a C++ stream version of it, try gzstream

- Warren
I can't actually use any third party libraries because I have no control over the implementation, or the compiler.
 
  • #4
Hurkyl
Staff Emeritus
Science Advisor
Gold Member
14,916
19
I can't actually use any third party libraries because I have no control over the implementation, or the compiler.
Are those really problems?



Anyways, if space really, really is a concern, then you shouldn't be writing anything in human readable text formats, because that is a huge waste of space. Use the C++ ostream::write or the fwrite functions to write raw bytes, e.g.

Code:
double x;
double y[3];
fout.write(static_cast<const char*>(&x), sizeof(double));
fout.write(static_cast<const char*>(y), sizeof(y));
and read similarly. If the file needs to be transferable between different computers that lay things out differently in memory, then you need to do a little more work to write things out in a portable format.
 

Related Threads on Outputting to file in the most compressed form (c++)

Replies
4
Views
2K
  • Last Post
Replies
4
Views
2K
  • Last Post
Replies
1
Views
5K
  • Last Post
Replies
9
Views
2K
Replies
1
Views
4K
Replies
6
Views
978
Replies
3
Views
2K
  • Last Post
Replies
5
Views
1K
  • Last Post
Replies
7
Views
40K
Top