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

前端 未结 8 882
你的背包
你的背包 2021-01-06 23:32

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 i

相关标签:
8条回答
  • 2021-01-07 00:33

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

    0 讨论(0)
  • 2021-01-07 00:34

    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.)

    0 讨论(0)
提交回复
热议问题