Convert contents of ASCII to binary

Hello,

I am trying to convert the content of ASCII text files into binary. Below is what I came up so far but not solving the problem.

1
2
3
4
5
6
7
8
9
10
std::ifstream infile(inputfilename.c_str(), ios::binary);
std::ofstream outfile(outputfilename.c_str(), ios::binary|ios::trunc);

// get the size of inputfile in byte
streampos fsize = 0;
inputfile.seekg(0,ios::end);
fsize = inputfile.tellg();
inputfile.seekg(0);

outfile.write(reinterpret_cast<char *>(inputfile.rdbuf()) , sizeof(fsize));


Although it builds okay but it does not solve the problem correctly. Help will be appreciated :)
You need to be clear on what you mean by Convert contents of ASCII to binary.

ASCII is already binary code right? What do you want to appear in the output file?
Last edited on
I think I want it to be as raw data (binary data) oppose to formatted data.
Show us an example of your source and of your desired result.
What I am trying to achieve is to have my 3D xyz coordinate data as a PLY file format. PLY file format has a header information and data as binary little(or big) endian.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
int main(int argc, char * argv[])
{
    /// process command line arguments
    
    string input(argv[1]);
    string outputfile(argv[2]);
    
    //End of argument processing
    //****************************/
    
    size_t cols = 3;
    size_t rows = 0;
    size_t face = 0;
    
    ifstream inputfile(input.c_str(), ios::binary);
    
    // get the number of lines as # rows
    string line;
    while(getline(inputfile, line))
    {
        ++rows;
    }
    inputfile.clear();
    
    ofstream outfile(outputfile.c_str(), ios::binary|ios::trunc);
    
    // PLY header
    outfile << "ply" << std::endl
	<< "format binary_little_endian 1.0" << std::endl
	<< "comment Lee Seongjoo at Yonsei University" << std::endl
	<< "obj_info num_cols " << cols << std::endl
	<< "obj_info num_rows " << rows << std::endl
	<< "element vertex " << rows << std::endl
	<< "property float x\n"
	<< "property float y\n"
	<< "property float z\n"
	<< "element face " << face << std::endl
	<< "property list uchar int vertex_indices\n"
	<< "end_header\n";
    
    // get the size of inputfile
    streampos fsize=0;
    inputfile.seekg(0, ios::end);
    fsize = inputfile.tellg();
    inputfile.seekg(0);
    
    /* supposedly write the content of inputfile as raw binary 
        but not quite successful yet
    */
    outfile.write(reinterpret_cast<char *>(inputfile.rdbuf()), sizeof(fsize)); 
        
    inputfile.close();
    outfile.close();
    return 0; 
}



Why not use a library written to do what you want to do? (It will save you a lot of grief.)
http://w3.impa.br/~diego/software/rply/
Why not indeed! Thank you!
Topic archived. No new replies allowed.