dvds414
dvds414

Reputation: 153

How can I convert a text file with numbers in it into a binary file?

So I have made a program that opens up a text file using ifstream. Now I want to make it so it outputs this file in binary. I have tried ofstream and using .write() but when I do the program crashes. I set it up correctly when using .write() as I have seen online but I haven't seen anyone do it with what I was working with. Anybody have a solution to this? Also, I do not know why 'InputFile' and 'OutputFile' are both highlighted blue like that.

#include <iostream>
#include <fstream>
#include <string>
#include <bitset>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        cout << "Error 1";
        return 0;
    }
    else
    {
        int WIDTH, HEIGHT;
        ifstream InputFile;
        InputFile.open(argv[1], ios::in);
        ofstream OutputFile;
        OutputFile.open("OUTPUT.raw", ios::binary | ios::app);
        cout << "Enter Width" << endl;
        WIDTH = cin.get();
        HEIGHT = WIDTH;
        for (int x = 0; x < WIDTH; x++)
        {
            for (int y = 0; y < HEIGHT; y++)
            {
                OutputFile.write((char*)InputFile.get(), sizeof(InputFile));
            }
        }
    }
    //cout << bitset<8>(txt[i]);
    return 0;
};

Upvotes: 0

Views: 1290

Answers (2)

jrok
jrok

Reputation: 55395

OutputFile.write((char*)InputFile.get(), sizeof(InputFile));

First, istream::get() extracts one characters from the stream and returns its value casted to an integer. The result is a temporary, which you cast to a pointer to char! It compiles, because the C-style cast basically tells the compiler "shoosh, I know what I'm doing!", but it will certainly do weird things at run-time. You need to get an adress of some object where the value you want to write is stored in, and cast that adress.

The second thing, sizeof(InputFile) returns size of ifstream class that manages the file stream. It's not in any way related to how many data is in the stream's buffer.

If you open a stream in text mode, then the correct way to extract data from it is to use extraction operator (>>). Then it's pretty simple:

std::ifstream in_file("numbers.txt");
std::ofstream out_file("numbers.bin", std::ios::binary);

int i;

while (in_file >> i)
    out_file.write(reinterpret_cast<char*>(&i), sizeof(int));

The above snippet will work with an input text file like this: -4 21 1990 5425342 -3432 0 100.

Upvotes: 2

Alexander Sobolev
Alexander Sobolev

Reputation: 789

You will have to parse your text file to get int for every string in file and just create a new file and write your binary data with fputc() or fwrite() functions.

Upvotes: 0

Related Questions