如何正确地 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
}
现在我正在客户端成功解析字符串(我不确定损坏问题是否在于我将缓冲区转换为字符串)。 发送循环中的所有数据后。客户端尝试使用缓冲区数据块进行写入:
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!对不起,我是菜鸟:)你让我开心!
相关文章:
- C++试图读取一个文件并输出到另一个文本文件
- 将所有 *.txt 文件合并到一个文本文件中,其名称由用户使用 C++ 提供
- 我该如何循环遍历我的数组(缓冲区——包含一个文本文件),并将其打印成30字节的块
- 检查一个文本文件中的单词是否在另一个文本文件 (C++) 中
- 我想使用 ofstream 在 cpp 中创建一个文本文件
- 检查一系列单词,形成一个文本文件,保存在字符串vector C 中
- 从一个文本文件加载多个 char 和 int 类型的数组
- 使用文本文件中的值进行计算并写入另一个文本文件
- 为什么当我在Visual c ++ studio 2010中运行应用程序时光标会转到最后一个文本框
- 将三个文本文件组合成一个文本文件,形成一个句子C++
- 控制台程序读取文本文件行,做Levenstein并输出一个文本文件
- 如何将XML文件拆分为多个XML,以便每个新文件只包含原始文件中的一个文本节点
- 读取文本文件中的多行并写入另一个文本文件
- 我把矢量从一个文本文件中归档,它不会变成一行.我该怎么做
- 如何将字符串的特定部分替换为另一个文本
- 在QT中制作了一个文本浏览器,但代码就像它不存在一样?
- 如何正确地将一个文本整数作为参数作为空指针进行传递,并使用其地址作为整数的实际值
- 给定一个单词和一个文本,返回文本中单词字谜的出现次数
- 给定一个单词和一个文本,我们需要返回字谜的出现次数
- 我正试图将一个过程的结果写入一个文本文件,我遇到的问题是列的对齐问题