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

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

本文关键字:一个 文本 文件 fwrite 正确地 fread      更新时间:2023-10-16

这是我第一次使用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
}

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

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新创建的文件。

那么,这段代码有什么问题,为什么它没有输出一个完美的文件?我是否错误地使用fread()fwrite()

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

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

而且效果很好!

谢谢@Barmar!对不起,我是菜鸟:)你让我开心!

相关文章: