fgets()读取文件问题

zcmerlin 2017-02-09 03:13:59
windows vs 2012下用C写程序,socket传输文件,客户端用fgets()读取文件并向server传输出现问题

用fgets时不能读取指定长度,而且每使用一次,读取的长度减小一个字节,不知道是哪里出bug啦

代码片段如下如下:


char sendBuf [20] = { 0 };

/*发送文件*/
recv(sockClient, recvBuf, 1024, 0);
if (!strcmp(recvBuf, "success"))
{
while (!feof(p_source))
{
fgets (sendBuf, strlen(sendBuf), p_source);
printf ("%s", sendBuf);
send (sockClient, sendBuf, strlen(sendBuf) + 1, 0);
}
}


结果如图:


这是哪里出问题了呀,自己找不出来,请大侠帮忙
...全文
195 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zcmerlin 2017-02-10
  • 打赏
  • 举报
回复
引用 1 楼 cfjtaishan 的回复:

fgets (sendBuf, strlen(sendBuf), p_source); //改成
fgets (sendBuf, 20, p_source);
fgets第二个参数是指要读取的最大长度;第一次sendBuf中没有数据,那么strlen()得到是0; fgets的功能如下: char *fgets(char *s, int size, FILE *stream); fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
多谢
自信男孩 2017-02-09
  • 打赏
  • 举报
回复

fgets (sendBuf, strlen(sendBuf), p_source); //改成
fgets (sendBuf, 20, p_source);
fgets第二个参数是指要读取的最大长度;第一次sendBuf中没有数据,那么strlen()得到是0; fgets的功能如下: char *fgets(char *s, int size, FILE *stream); fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧