无法将多行文本文件复制到缓冲区 [英] Unable to copy multiline text file to a buffer

查看:72
本文介绍了无法将多行文本文件复制到缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文本文件复制到缓冲区,以便通过套接字发送它。只要文本文件没有任何换行符(或\ n),文件就会成功复制到缓冲区中。但是,只要文本文件中有多行,我就会收到错误,无法将文件复制到缓冲区。



以下是代码片段:

  //   === ==================在套接字上发送文件=========================  
FILE * fp = fopen( File.txt r +);
char file_buffer [ 1000 ];
fseek(fp, 0 ,SEEK_SET);
int bytes_read = 0 ;
if ((bytes_read = fread(file_buffer, 1 ,file_size,fp))< = 0
{
MessageBox(NULL,
无法将文件复制到缓冲区
错误!
MB_ICONEXCLAMATION |
MB_OK);
退出( 1 );
}
MessageBox(NULL,
file_buffer,
复制的文件在缓冲区
MB_ICONEXCLAMATION |
MB_OK);





注意: 如果文本文件不包含新行,则代码可以正常工作。

解决方案

此代码不正常: file_size 未初始化,在确定计数 fread c>(在您的情况下 file_size 本身)参数小于(或等于)提供的缓冲区的大小。


打开二进制模式的文件解决了问题:)

fopen必须如下:

 FILE * fp = fopen(File.txt, R + b); 


I am trying to copy a text file to a buffer in order to send it over the socket. As soon as the text file does not have any newlines (or \n), the file is successfully copied into buffer. But, whenever there are multiple lines in a text file, I get an error, "Unable to copy file into buffer".

Below is the code snippet:

//=====================Sending a File at Socket=========================
   FILE *fp = fopen("File.txt", "r+");
   char file_buffer[1000];
   fseek(fp, 0, SEEK_SET);
   int bytes_read=0;
   if((bytes_read=fread(file_buffer, 1, file_size, fp))<=0)
     {
       MessageBox( NULL,
               "Unable to copy file into buffer",
               "Error!",
               MB_ICONEXCLAMATION |
               MB_OK);
      exit(1);
     }
     MessageBox( NULL,
             file_buffer,
            "File copied in Buffer",
            MB_ICONEXCLAMATION |
            MB_OK);



NOTE: The code works perfectly fine if the text file contains no new lines.

解决方案

This code is NOT fine: file_size is not initialized and you should never call fread before being sure that the count (in your case file_size itself) argument is less than (or equal to) the size of the provided buffer.


opening the file in binary mode solved the problem :)
fopen must be as follows:

FILE *fp = fopen("File.txt", "r+b");


这篇关于无法将多行文本文件复制到缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆