这是我第一次使用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!对不起,我很讨厌:)你让我开心!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句