Reading binary file to unsigned char array 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);
}
但是它会写入我的缓冲区,还会将一些0xFF字节附加到文件末尾(对于较小的文件,它会附加一些字节,但对于较大的文件,它可以附加一些千字节)。会有什么问题?
推荐答案
您应该投资于fread
和fwrite
,让底层的库和操作系统处理循环:
// 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);
如果要执行不带任何字节翻译的精确复制,请以"rb"打开输入文件,并以"wb"打开输出文件。
您还应该考虑使用new
和delete[]
,而不是malloc
和free
。
这篇关于将二进制文件读取到无符号字符数组并将其写入另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:将二进制文件读取到无符号字符数组并将其写入另一个


基础教程推荐
猜你喜欢
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01