linux下fgets(..,..,stdin)不阻塞??

snakepoon 2007-07-26 06:32:18
我编写了一个修改文档的程序,但是不知道为什么用fgets(buf,1024,stdin)的时候就不阻塞,我是分为两个函数写的,两个函数分别工作的时候就正常,两个函数合起来工作的时候就会这样,求救!!
函数如下:
find函数寻找对应项,modify函数修改对应项。
#include <stdio.h>
extern int modify(FILE *fp);
int main()
{
FILE *fp;
if(fp=fopen("./t.txt","r+")==NULL)
{
printf("there is no such file");
return -1;
}
find(fp);
modify(fp);
fclose(fp);
return 0;
}

int find(FILE *fp)
{
char *t;
char *idata;
char *namebuf,*buf2,*addr,*tempbuf;
char *searchname;
char *tsearchname,*tnamebuf;
long count;
long offsize;
offsize=0;
fseek(fp,0,SEEK_SET);
searchname=(unsigned char *)malloc(1024);
idata=(unsigned char *)malloc(1024);



tsearchname=(unsigned char *)malloc(1024);
tsearchname=searchname;
while((*searchname=(unsigned char)fgetc(stdin))!=':')
{
searchname++;
}



namebuf=(unsigned char *)malloc(1024);
tempbuf=(unsigned char *)malloc(1024);
tnamebuf=(unsigned char *)malloc(1024);
namebuf=tnamebuf;
while((t=fgets(tempbuf,1024,fp))!=NULL)
{

fseek(fp,offsize,SEEK_SET);

while((*tnamebuf=(unsigned char)fgetc(fp))!=':')
{
tnamebuf++;
printf("the number is:%s\n",namebuf);
}

printf("namebuf:%s\nsearchname:%s\n",namebuf,tsearchname);
int a=0;

if((a=strcmp(namebuf,tsearchname))==0)
break;

printf("strcmp is:%d\n",a);

tnamebuf=namebuf;
fgets(tempbuf,1024,fp);
offsize=ftell(fp);
printf("%s\n",tempbuf);
}
if(t==NULL)
{
printf("can't find the number\n");
return 1;
}
else
{

printf("the number %s is found\n",namebuf);
printf("end here\n");
}
printf("enter your data **:**\n");

printf("yeye\n");
return 0;
}

int modify(FILE *fp)
{
char *pointbuftemp;
char *buf,*buf2,*buftemp;
int rest;
long current,next,nextnext,departure;
buf=(unsigned char *)malloc(1024);
buftemp=(unsigned char *)malloc(1024);
buf2=buf;
current=ftell(fp);
rest=1024;
fgets(buf,rest,fp);
next=ftell(fp);
departure=0;
while(fgets(buf,rest,fp)!=NULL)
{
nextnext=ftell(fp);
departure=nextnext-next;
next=ftell(fp);
rest-=departure;
buf+=departure;
}
fseek(fp,current,SEEK_SET);
fgets(buftemp,1024,stdin);
fputs(buftemp,fp);
fputs(buf2,fp);
printf("fflush?\n");
return 0;
}
请问这是什么原因,应该怎么办呢?谢谢!!
...全文
1616 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
snakepoon 2007-07-30
  • 打赏
  • 举报
回复
cceczjxy() 谢谢你的建议,我已经按你讲的修改过,已经可以运行了,我是个菜鸟,以后还请多多指教,哈哈
dai_weitao 2007-07-27
  • 打赏
  • 举报
回复
代码很烂, 变量名很丑, 流程很乱.
没法看.
cceczjxy 2007-07-27
  • 打赏
  • 举报
回复
设这样的
*searchname=(unsigned char)fgetc(stdin)!=':'

读完以后,缓冲区里的\n号没读取出来.在modify内再用fgets(buftmp,1024,stdin)读时就会把这个'\n'读走.

这样改一下就可以了:
while((*searchname=(unsigned char)fgetc(stdin))!=':')
{
searchname++;
}
fgetc(stdin); //添加一句.


不过说实话,楼主的程序有很多地方都是冗余的.
你的malloc分配的空间,好象都没free吧.

23,217

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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