如何正确地 fread() 和 fwrite() 一个非文本文件?

How to properly fread() and fwrite() a non text file?

这是我第一次使用 fread()fwrite() 函数。所以我还在学习如何对付他们。对于文本文件,我已经成功地读取了一个文件,然后在另一个函数中创建了一个文件。但是,每当我尝试使用非文本文件时,它们只会输出损坏的文件。我在这里问是因为我在互联网上搜索这件事没有成功的结果。

简而言之:我将从我在服务器上打开的文件中收集的数据发送到客户端,然后客户端尝试使用解析的数据创建准确的文件。

那么,让我解释一下我是如何做到的: 我以二进制模式打开一个非文本文件:

FILE* myfile = fopen(fullPath.c_str(), "rb");

然后我创建一个循环来读取文件:(出于某种原因我发现非文本文件的实际大小等于 size/4

int readPos = 0;
std::string externalBuffer;

while (true) {
    unsigned char buffer[1024];
    int bytesRead = 0;

    bytesRead += fread(buffer, sizeof(unsigned char), 1024, upfile);    

    if (bytesRead == 0)
        break;

    externalBuffer = unsigned_char_to_string(buffer, bytesRead); //This simple function loops over the buff and converts each entry to the string -> the results are numbers from 0-255

//Here I convert the buffer to a string and send it to the client to be parsed and add to a string buffer like: dataChunk += parsedString;

//clear buffers

}

现在我在客户端成功解析了字符串(我不确定损坏问题是否在于我将缓冲区转换为字符串)。 发送循环中的所有数据后。客户端尝试写入然后使用缓冲区 dataChunk:

FILE* myfile = fopen(fullPath.c_str(), "wb+");
fwrite(dataChunk.c_str(), sizeof(char), dataChunk.size(), myfile);
fclose(myfile);

我已经尝试将发送的数据转换为十六进制字符串,将每个条目从 0-255 转换为十六进制并写入新文件。我还尝试将 dataChunk 字符串转换为 unsigned char 数组。但是我所有的尝试都导致文件损坏。我使用这种方法尝试创建一个可执行文件和一个 png 图像。 我还看到了一些示例,然后 fopen 并一次复制所有文件,然后 fwrite 使用看起来对他们有用的 unsigned char 在同一函数的新创建文件中。

那么,这段代码有什么问题,为什么它不能输出完美的文件?我用错了 fread()fwrite() 吗?

使用@Barmar 更正。 我将 unsigned_char_to_string 函数更改为以下代码:

std::string externalBuffer(&buffer[0], &buffer[0] + bytesRead);

而且效果很好!

谢谢@Barmar!对不起,你太笨了 :) 你让我很开心!