char数组在结束前包含空字符
Char Array contains null characters before the end
我有一个类项目,可以在C 中制作网络服务器。一切都很好,直到我到达需要托管图像或PDF的地步,这时文件已损坏。做更多的挖掘,我意识到所有损坏的图像在结束前都有空字符。
这使我提出了问题。我有一个char*,我已经阅读了这些文件,并且知道文件的长度。我很肯定整个文件都在(下面的代码)中读取,但是我不知道如何打印出来或发送它。我该如何告诉C 我想在char*之后发送第一个X字符?(我敢肯定答案在这里或网络上的某个地方,我似乎无法以正确的方法来找到我的问题)
ifstream myfile (path.c_str() , ios::in|ios::binary|ios::ate);
ifstream::pos_type size = myfile.tellg();
cout << size << endl;
fileSize = (int) size;
fileToReturn = new char [size];
myfile.seekg (0, ios::beg);
myfile.read (fileToReturn, size);
myfile.close();
cout << "file readn"<< fileToReturn << endl;
对于纯文本文件,这将输出良好。对于PDF,它仅打印文件的第一部分(第一个NULL字符之前的部分)。我该如何打印整个文件?
编辑:要澄清,我的最终目标是通过网络发送它,而不是重新保存文件。
// reply is string with all my headers and everything set.
// fileToReturn is my char*, and fileSize is the int with how long it should be
char* totalReply = new char [reply.length() + fileSize+1];
strcpy(totalReply, reply.c_str());
strcat(totalReply, fileToReturn);
send(client, totalReply, reply.length() + fileSize, 0);
问题是ostream& operator<< (ostream& out, const char* s );
期望s
是一个无效的ASCII字符串。因此,它一旦遇到NUL
字符就会停止。如果您真的想将所有数据写入控制台,请使用`ostream&amp;写(const char* s,流式n),这样:
cout.write(fileToReturn, size);
strcat
的问题相同:它在第一个NUL
字符之后停止。因此使用memcpy
:
memcpy(totalReply, reply.c_str(), reply.size()+1);
memcpy(totalReply+reply.size()+1, fileToReturn, fileSize )
但是您将这个问题标记为C ,所以为什么不这样做:
ifstream myfile (path.c_str() , ios::in|ios::binary|ios::ate);
vector<char> totalReply;
totalReply.insert(buffer.end(), reply.begin(), reply.end());
// need a NUL character here?: totalReply.push_back(' ');
totalReply.insert(buffer.end(), istream_iterator(myfile), istream_iterator());
send(client, &totalReply[0], totalReply.size(), 0);
您没有提及打开文件的方式,请确保您已经以二进制模式打开,否则请搜索ET都无法与新的线字符正常工作。
即。myfile.open( "yourfile", ios::binary|ios::in )
相关文章:
- pcap_handler回调仅在使用 NPCAP v0.9991 时包含空数据包
- 无法将字符数组转换为包含 utf-8 字符的字符串
- VSCode C++调试文件名中包含中文字符的文件时插件损坏
- 如何获取包含 NULL 字符的外壳代码字符串的长度
- 在 Windows 上,stat 和 GetFileAttributes 对于包含奇怪字符的路径失败
- Flex 词法分析器规则,对包含连字符和斜杠的字母数字字符串具有积极的前瞻断言
- cout 打印的字符 [] 包含的字符数超过设置长度
- C4838 警告,包含常量字符* 数组的数组初始化
- 如何使用正则表达式匹配不包含特殊字符(&、\、<、>、|、)的字符串,除非它们以反斜杠开头
- 我的逻辑有什么问题?尝试计算文件中包含特定字符的单词数
- 在std::字符串或字符数组中间包含NULL字符的UPDATE
- C++,我想在字符串中搜索一个字符,并输出包含该字符的所有单词
- 从包含Unicode字符的文件中读取
- 如何在 gtk 中设置包含宽字符的文本
- C 读取CSV文件包含空单元
- 包含2D字符数组的构造函数
- 不能传递宏中包含各种字符的g++
- 在linux中输入一个包含希腊字符的字符串
- 如何使用包含空值的字符*初始化 std::string
- 如何从包含空值的字符数组中提取std::string