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
。
这篇关于将二进制文件读取到无符号字符数组并将其写入另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:将二进制文件读取到无符号字符数组并将其写入另一个


猜你喜欢
- GDB 不显示函数名 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- XML Schema 到 C++ 类 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- DoEvents 等效于 C++? 2021-01-01