0

我在文本文件中有一些数据。现在我想将此数据复制到字符缓冲区,以便我可以通过 udp 套接字发送它。如何将文本文件中的数据复制到缓冲区?我为此尝试了 fread ,但它也复制了一些冗余数据,尽管我只指定了等于要读取的文件大小的字节数,但它仍在读取一些冗余数据。下面是我正在尝试的代码片段:

    char file_buffer[1000];
    fpSend = fopen("sendclInformation.txt", "w+");
    WriteFile(sendFile,"Data in File",strlen("Data in File"),&dwWritten,0);
    fseek(fpSend, 0, SEEK_END);
    size_t file_size = ftell(fpSend); // The size calculated here is 12 so fread must display only 12 bytes but it is displaying large redundant data appended to actual data.
    fseek(fpSend, 0, SEEK_SET);                         
    if(file_size>0)   //if file size>0
    {  
    int bytes_read=0;                               
if((bytes_read=fread(file_buffer, file_size, 1, fpSend))<=0)
    {                                                                                        "Unable to copy file into buffer",
    }
    else
    {
    MessageBox( NULL,file_buffer,"File copied in Buffer",MB_ICONEXCLAMATION|MB_OK);
    }
}
4

1 回答 1

0

问题

你写了字符串,但似乎没有写结尾 \0 来标记字符串的结尾,当你从文件中读取时,你似乎认为它是一个正确的终止字符串,你得到了

改变

WriteFile(sendFile,"Data in File",strlen("Data in File"),&dwWritten,0);

WriteFile(sendFile,"Data in File",strlen("Data in File") + 1,&dwWritten,0);

其他

使用它以 r/w 二进制模式打开文件"wb+"将确保您从/向文件读取/写入的内容是原始字节,无需任何换行符转换。如果您以文本模式打开文件,fseek则会ftell给出错误的(出于您的目的)结果。

您的 if 语句似乎有点奇怪,也许您的意思是

if((bytes_read=fread(file_buffer, file_size, 1, fpSend))<=0)
{
  "Unable to copy file into buffer",
}
else
{
  MessageBox( NULL,file_buffer,"File copied in Buffer",MB_ICONEXCLAMATION|MB_OK);
}

像这样的东西(还要注意我改变了 fread 参数

if((bytes_read=fread(file_buffer, 1, file_size, fpSend))<file_size)
{
  MessageBox( NULL,"error","Unable to copy file into buffer",MB_ICONEXCLAMATION|MB_OK);
}
else
{
  MessageBox( NULL,file_buffer,"File copied in Buffer",MB_ICONEXCLAMATION|MB_OK);
}

还建议您检查

于 2013-04-11T05:43:36.490 回答