char数组在结束前包含空字符



我有一个类项目,可以在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 )

最新更新