将文本文件的内容复制到缓冲区(win32api)

时间:2013-04-10 11:49:49

标签: c windows winapi text-files

我在文本文件中有一些数据。现在我想将这些数据复制到字符缓冲区,以便我可以在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);
    }
}

1 个答案:

答案 0 :(得分: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);

其他

使用"wb+"以r / w二进制模式打开文件,这将确保您从/向文件读取/写入的内容是原始字节,而不进行任何换行转换。如果您以文字模式打开文件,则fseekftell会出错(为了您的目的)。

你的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);
}

还建议您检查

相关问题