这个小程序有什么问题。。。貌似四内存泄露?

philistine_x 2011-04-15 11:54:12
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Winsock2.h>


void main()
{
FILE* userfile = NULL;
userfile = fopen("data.txt", "r");//只读打开文件
if(userfile == NULL)
return;

char buffer[256]= {0};
int c = 0;
int cnt = 0;

while(!feof(userfile))
{
while( (c = fgetc(userfile)) != '\n' )
{
if((char)c !=' ')
buffer[cnt++] = (char)c;
}
printf("%s\n",buffer);
cnt=0;
//send(buffer);
}
fclose(userfile);
return;
}


//data.txt内容 如下
12 34 41 42 07
...全文
120 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
woshierjian 2011-04-20
  • 打赏
  • 举报
回复
调试的时候发现楼主的程序会读取文本文件时,读到字符串结束地方的时候继续读取,C的值为-1,跳不出循环。。。
philistine_x 2011-04-16
  • 打赏
  • 举报
回复
第二个循环体的判断条件还加上!feof(userfile)就OK了~~
改为:while( !feof(userfile)&&(c = fgetc(userfile)) != '\n' )
应该这样就可以了。
wangkai856 2011-04-16
  • 打赏
  • 举报
回复
楼上的改法是对的,不过我也不太明白为什么楼主的程序会出现内存泄漏?
newfarmerchi 2011-04-16
  • 打赏
  • 举报
回复
你试试以下两种方法
while(!feof(userfile))
{
if ((c = fgetc(userfile)) != '\n' )
{
if((char)c !=' ')
buffer[cnt++] = (char)c;
}
}


while( (c = fgetc(userfile)) != EOF )
{
if((char)c !=' '&&(char)c!='\n')
buffer[cnt++] = (char)c;
}

15,440

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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