C++ 将二进制文件读取到无符号字符数组并将其写入另一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22129349/
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
Reading binary file to unsigned char array and write it to another
提问by Alex Saskevich
Hello, I have some problem with rewriting files using C++. I try to read data from one binary file and write it to another.
您好,我在使用 C++ 重写文件时遇到了一些问题。我尝试从一个二进制文件中读取数据并将其写入另一个。
{
// Reading size of file
FILE * file = fopen("input.txt", "r+");
if (file == NULL) return;
fseek(file, 0, SEEK_END);
long int size = ftell(file);
fclose(file);
// Reading data to array of unsigned chars
file = fopen("input.txt", "r+");
unsigned char * in = (unsigned char *) malloc(size);
for (int i = 0; i < size; i++)
in[i] = fgetc(file);
fclose(file);
file = fopen("output.txt", "w+");
for (int i = 0; i < size; i++)
fputc((int)in[i], file);
fclose(file);
free(in);
}
But it write my buffer and also append some 0xFF bytes to the end of file (it append some bytes for small files, but can append some kilobytes for greater files). In what can be problem?
但它写入我的缓冲区,并在文件末尾附加一些 0xFF 字节(它为小文件附加一些字节,但可以为更大的文件附加一些千字节)。有什么问题?
回答by Thomas Matthews
You should invest in fread
and fwrite
and let the underlying libraries and OS handle the looping:
你应该投资fread
和fwrite
让底层库和OS处理循环:
// Reading size of file
FILE * file = fopen("input.txt", "r+");
if (file == NULL) return;
fseek(file, 0, SEEK_END);
long int size = ftell(file);
fclose(file);
// Reading data to array of unsigned chars
file = fopen("input.txt", "r+");
unsigned char * in = (unsigned char *) malloc(size);
int bytes_read = fread(in, sizeof(unsigned char), size, file);
fclose(file);
file = fopen("output.txt", "w+");
int bytes_written = fwrite(out, sizeof(unsigned char), size, file);
fclose(file);
free(in);
If you want to perform an exact copy without any translations of the bytes, open the input file as "rb" and open the output file as "wb".
如果您想在没有任何字节转换的情况下执行精确复制,请将输入文件打开为“rb”,并将输出文件打开为“wb”。
You should also consider using new
and delete[]
instead of malloc
and free
.
您还应该考虑使用new
anddelete[]
代替malloc
and free
。
回答by Eutherpy
This is not really answering your question about where the mistake is, but I think it's a much simpler way of writing from one binary file to another:
这并没有真正回答您关于错误在哪里的问题,但我认为这是一种从一个二进制文件写入另一个文件的更简单的方法:
ifstream in(inputFile, ios::binary);
ofstream out(outputFile, ios::binary);
if(in.is_open() && out.is_open())
while(!in.eof())
out.put(in.get());
in.close();
out.close();