将二进制文件读取到unsigned char数组并将其写入另一个

时间:2014-03-02 15:14:31

标签: c++ file binaryfiles

您好,我在使用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字节(它为小文件附加了一些字节,但是可以为更大的文件追加一些千字节)。可能有什么问题?

2 个答案:

答案 0 :(得分:4)

您应该投资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);

如果要执行精确副本而不翻译任何字节,请将输入文件打开为&#34; rb&#34;并打开输出文件为&#34; wb&#34;。

您还应该考虑使用newdelete[]代替mallocfree

答案 1 :(得分:2)

这并没有真正回答你关于错误在哪里的问题,但我认为从一个二进制文件写到另一个文件是一种更简单的方式:

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();