C++ 需要在C++中将txt文件转换为二进制文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5016262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Need to convert txt file into binary file in C++
提问by aki
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?
我有一个 txt 文件,里面的数字是 541399.531 261032.266 16.660(第一行)541400.288 261032.284 16.642(第二行)......一百点。我想将此文件转换为二进制格式。任何人都可以帮助我吗?
采纳答案by Kings
In C++ just open the file for reading, then copy it to another file as a binary file.
在 C++ 中,只需打开文件进行读取,然后将其作为二进制文件复制到另一个文件中。
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);
回答by Thomas Matthews
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.
从文件加载二进制表示比翻译文本表示更有效的想法是正确的。然而,大多数处理器可以比读入二进制数据更快地转换 ASCII 转换。 总结:通过删除转换获得的时间被更大的时间消耗(例如文件 I/O 和上下文切换)所掩盖。
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:
改变数据表示是一种优化形式。优化规则(按重要性排序)是:
- Don't.
- Only if the program doesn't fit on the target machine or Users complain about the speed.
- Optimize after the program is robust and runs correctly.
- Optimize the platform, if possible, before optimizing the program.
- If you need to optimize, Profile first.
- Optimize Requirements before optimizing code.
- Optimize Design & Algorithms before optimizing code.
- Optimize data before optimizing code.
- Optimize in high level language before writing in assembly.
- 别。
- 仅当程序不适合目标机器或用户抱怨速度时。
- 在程序健壮并正确运行后进行优化。
- 如果可能,在优化程序之前优化平台。
- 如果需要优化,先分析。
- 在优化代码之前优化需求。
- 在优化代码之前优化设计和算法。
- 在优化代码之前优化数据。
- 在编写汇编语言之前先用高级语言进行优化。
回答by Rob?
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.)
请注意,这并没有解决机器类型之间的任何可移植性问题。您可能必须自己解决这个问题。(我会给你一个提示:解决二进制格式可移植性问题的最佳方法是不要使用 binary format。)
回答by Emthreex
#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;
}
回答by Nick
Have a look at std::ifstream and std::ofstream. They can be used for reading in values and writing out values.
看看 std::ifstream 和 std::ofstream 。它们可用于读入值和写出值。
回答by Alex Darsonik
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).
查找 stl 类 istringstream 和 ofstream。第一个自动将字符串转换为双精度,第二个具有二进制文件输出。在示例中,instream 是一个 istringstream,而 os 是一个 ofstream,后者以正确的模式打开(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;
}
回答by Sriram
This is what you may want to do.
这就是您可能想要做的。
- Open the text file using ifstream.
- Open the target file using ofstream in binary mode.
- Read information from file1 and write to file2.
- 使用 ifstream 打开文本文件。
- 在二进制模式下使用 ofstream 打开目标文件。
- 从 file1 读取信息并写入 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
HTH,
斯里拉姆
回答by daouzli
There is binmakean open source C++ tool allowing to convert text data to binary data. It currently manages several number representations and raw text (hexa, octal, floats..).
有binmake一个开源C ++工具允许文本数据转换成二进制数据。它目前管理几种数字表示和原始文本(六进制、八进制、浮点数……)。
I think it is interesting to mention it here as the title deals with text to binary file in C++ what binmakecan do.
我认为在这里提及它很有趣,因为标题涉及在 C++中将文本转换为二进制文件,binmake可以做什么。
It can be used as a standalone binary but also included in your C++ code.
它可以用作独立的二进制文件,也可以包含在您的 C++ 代码中。
Using as a standalone program
作为独立程序使用
With stdin
/stdout
:
与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
包含在 C++ 代码中
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
:
文件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