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

Ale*_*ich 2 c++ binaryfiles file

您好,我在使用 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);
}
Run Code Online (Sandbox Code Playgroud)

但它写入我的缓冲区,并在文件末尾附加一些 0xFF 字节(它为小文件附加一些字节,但可以为更大的文件附加一些千字节)。有什么问题?

Tho*_*ews 6

你应该投资freadfwrite让底层库和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);
Run Code Online (Sandbox Code Playgroud)

如果您想在没有任何字节转换的情况下执行精确复制,请将输入文件打开为“rb”,并将输出文件打开为“wb”。

您还应该考虑使用newanddelete[]代替mallocand free