将二进制文件读取到无符号字符数组并将其写入另一个

2022-06-17 00:00:00 file binaryfiles c++

您好,我在使用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字节附加到文件末尾(对于较小的文件,它会附加一些字节,但对于较大的文件,它可以附加一些千字节)。会有什么问题?


解决方案

您应该投资于freadfwrite,让底层的库和操作系统处理循环:

// 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"打开输出文件。

您还应该考虑使用newdelete[],而不是mallocfree

相关文章