aki
aki

Reputation: 155

Need to convert txt file into binary file in C++

I have a txt file with numbers like 541399.531 261032.266 16.660 (first line) 541400.288 261032.284 16.642 (2nd line)........hundred of points. i want to convert this file into binary format. Any one can help me?

Upvotes: 2

Views: 30219

Answers (8)

daouzli
daouzli

Reputation: 15328

There is binmake an open source C++ tool allowing to convert text data to binary data. It currently manages several number representations and raw text (hexa, octal, floats..).

I think it is interesting to mention it here as the title deals with text to binary file in C++ what binmake can do.

It can be used as a standalone binary but also included in your C++ code.

Using as a standalone program

With stdin/stdout:

$ echo '32 decimal 32 %x61 61' | ./binmake | hexdump -C
00000000  32 20 61 3d                                       |2 a=|
00000004

With files:

$ ./binmake exemple.txt exemple.bin

(see below for a sample view)

Including in C++ code

There's some examples of use:

#include <fstream>
#include "BinStream.h"

using namespace std;
using namespace BS;

int main()
{
    BinStream bin;
    bin << "'hello world!'"
            << "00112233"
            << "big-endian"
            << "00112233";
    ofstream f("test.bin");
    bin >> f;
    return 0;
}

Or

#include <fstream>
#include "BinStream.h"

using namespace std;

int main()
{
    BS::BinStream bin;
    ifstream inf("example.txt");
    ofstream ouf("example.bin");
    bin << inf >> ouf;
    return 0;
}

Or

#include <iostream>
#include "BinStream.h"

using namespace std;
using namespace BS;

int main()
{
    BinStream bin;
    cin >> bin;
    cout << bin;
    return 0;
}

Example of input text file and the generated output

File exemple.txt:

# an exemple of file description of binary data to generate
# set endianess to big-endian
big-endian

# default number is hexadecimal
00112233

# man can explicit a number type: %b means binary number
%b0100110111100000

# change endianess to little-endian
little-endian

# if no explicit, use default
44556677

# bytes are not concerned by endianess
88 99 aa bb

# change default to decimal
decimal

# following number is now decimal
0123

# strings are delimited by " or '
"this is some raw string"

# explicit hexa number starts with %x
%xff

The generated binary output:

$ ./binmake exemple.txt | hexdump -C
00000000  00 11 22 33 4d e0 77 66  55 44 88 99 aa bb 7b 74  |.."3M.wfUD....{t|
00000010  68 69 73 20 69 73 20 73  6f 6d 65 20 72 61 77 20  |his is some raw |
00000020  73 74 72 69 6e 67 ff                              |string.|
00000027

Upvotes: 0

Emthreex
Emthreex

Reputation: 21

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
        char buffer;
    ifstream in("text.txt");
    ofstream out("binaryfile.bin", ios::out|ios::binary);
    int nums[3];
    while (!in.eof())
    {
        in >> nums[0] >> nums[1] >> nums[2];

        out.write(reinterpret_cast<const char*>(nums), 3*sizeof(int));

    }
    return 0;
}

Upvotes: 2

Robᵩ
Robᵩ

Reputation: 168626

First and foremost, don't do it. You almost certainly don't need to store your data in binary format. There are many advantages to storing the data in text format. If you have a compelling reason to store them in binary format, rethink your reason.

But, you asked how to do it, not if you should. Here is how:

#include <iostream>
#include <fstream>

int main()
{
   std::ifstream in("in.txt");
   std::ofstream out("out.bin", std::ios::binary);

   double d;
   while(in >> d) {
      out.write((char*)&d, sizeof d);
   }
}

Note that this does not address any issues of portability between machine types. You may have to address that yourself. (I'll give you a hint: the best way to solve binary format portability problems is don't use binary format.)

Upvotes: 4

Thomas Matthews
Thomas Matthews

Reputation: 57698

I suggest avoid writing the binary representations to a file for a few hundred or thousand points. This is called a micro optimization and the development time outweighs any gain in performance of the executable.

Not Worth Saving for Size

In current computing, most platforms support huge (gigabyte) file sizes and computers have megabytes or gigabytes of memory for programs to use. So writing in binary for saving room (file size or memory size) doesn't gain any significant advantages compared to other bottlenecks in the development cycle.

Not Much Gain in performance.

The idea that loading a binary representation from a file is more efficient than translating a textual representation is true. However, most processors can translate an ASCII translation faster than the binary data can be read in. Summary: the time gained by removing the translation is overshadowed by bigger consumers of time such as file I/O, and context switches.

Reducing usefulness of data

More applications can process textual representation of floating point numbers than the binary representation. With a textual representation, the data can be easily used in spreadsheets, word processors and analysis tools. Files containing the binary representations require more effort. When was the last time you tried reading a file of binary floating point numbers into a spreadsheet? Don't under estimate the future potential for data files.

Profile Before Optimizing.

Changing data representation is a form of optimizing. The rules of optimizing (in order of importance) are:

  1. Don't.
  2. Only if the program doesn't fit on the target machine or Users complain about the speed.
  3. Optimize after the program is robust and runs correctly.
  4. Optimize the platform, if possible, before optimizing the program.
  5. If you need to optimize, Profile first.
  6. Optimize Requirements before optimizing code.
  7. Optimize Design & Algorithms before optimizing code.
  8. Optimize data before optimizing code.
  9. Optimize in high level language before writing in assembly.

Upvotes: 6

Kings
Kings

Reputation: 1591

In C++ just open the file for reading, then copy it to another file as a binary file.

FILE *pTextFile, *pBinaryFile;
char buffer;
pTextFile = fopen("textfile.txt", "r");
pBinaryFile = fopen("binaryfile.bin", "wb");
while (!pTextFile(EOF))
{
fread(buffer, 1, 1, pTextFile);
fwrite(buffer, 1, 1, pBinaryFile);
}
fclose(pTextFile);
fclose(pBinaryFile);

Upvotes: 1

Sriram
Sriram

Reputation: 10558

This is what you may want to do.

  1. Open the text file using ifstream.
  2. Open the target file using ofstream in binary mode.
  3. Read information from file1 and write to file2.

Some sample code (untested):

    ifstream ifile("file1.txt");  
    ofstream ofile("file2.txt", ios::binary);  
    string line;  
    while(!ifile.eof()) {  
    getline(ifile, line);  
    ofile.write(line.c_str(), line.length);  
   }

HTH,
Sriram

Upvotes: 0

Alex Darsonik
Alex Darsonik

Reputation: 587

Look for the stl classes istringstream and ofstream. The first one to automatically convert strings to doubles, the second one to have binary file output. In the example instream is an istringstream and os is an ofstream, the latter opened with the correct mode (ios_base::binary | ios_base::out).

while (getline(cin, s)) {
    instream.clear();     // Reset from possible previous errors.
    instream.str(s);      // Use s as source of input.
    if (instream >> myDouble)
       os << myDouble;
}

Upvotes: 0

Nick
Nick

Reputation: 25799

Have a look at std::ifstream and std::ofstream. They can be used for reading in values and writing out values.

Upvotes: 0

Related Questions