简单的文件I/O问题

spgoal 2002-12-11 12:17:49
#include <stdio.h>
#define MAX_BUF 1024
int main(void)
{
char *inputstr;
char *outputstr;
FILE *fp;
printf("input string:");
scanf("%s",inputstr);

fp=fopen("file.test","a+b");
fputs(inputstr,fp);
outputstr=fgets(outputstr,MAX_BUF,fp);
fclose(fp);

exit(0);
}
编译成功,但是执行出错。出错信息为:Segmentation fault
如果加上:printf("%s",outputstr);
就显示:(null)Aborted

还有个问题:怎么用gcc step by step debug程序?
...全文
36 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
zzjjww 2002-12-17
  • 打赏
  • 举报
回复
咳,真累
A0110A 2002-12-17
  • 打赏
  • 举报
回复
其他问题不说,只说为什么输出结果为空。
在调用 fgets(outputstr,BUFSIZ,fp);前
写: fseek(fp,0,SEEK_SET);试一下,
spgoal 2002-12-12
  • 打赏
  • 举报
回复
楼上的程序我要加个#include<stdio.h>才能编译通过
而且运行结果是
aaaaaa
bbbb
Segmentation fault

是不是文件权限的问题?我是用telnet连到一个redhat7.3的主机上编译的
spgoal 2002-12-12
  • 打赏
  • 举报
回复
BUFSIZ应该就是1024
lcp 2002-12-12
  • 打赏
  • 举报
回复
请把:
char *inputstr;
char *outputstr;
改为:
char inputstr[1024] ;
char outputstr[1024] ;
再试试看。
spgoal 2002-12-12
  • 打赏
  • 举报
回复
我将程序改为:
#include <stdio.h>
int main(void)
{
char inputstr[BUFSIZ];
char outputstr[BUFSIZ];
char databuf[BUFSIZ];
FILE *fp;
printf("input string:");
scanf("%s",inputstr);

fp=fopen("file.test","a+b");
setvbuf(fp,databuf,_IOLBF,BUFSIZ);
fputs(inputstr,fp);
fgets(outputstr,BUFSIZ,fp);
fclose(fp);
printf("%s",outputstr);
exit(0);
}

输出结果为空
fgets的返回值到底是什么?
spgoal 2002-12-12
  • 打赏
  • 举报
回复
楼上指的是要先设buffer?
用setbuf()吗?
gaoxianfeng 2002-12-12
  • 打赏
  • 举报
回复

buffer
痞子酷 2002-12-11
  • 打赏
  • 举报
回复
我在redhat7.3上编译通过,运行也没有问题,我输入的是:aaaaaaaa
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_BUF 1024


int main(void)
{
char *inputstr;
char *outputstr;
FILE *fp;
printf("input string:");
scanf("%s",inputstr);
printf("aaaaaa\n");
fp=fopen("file.test","a+b");
printf("bbbb\n");
fputs(inputstr,fp);
outputstr=fgets(outputstr,MAX_BUF,fp);
fclose(fp);

exit(0);
}
assign 2002-12-11
  • 打赏
  • 举报
回复
你声明了字符指针,但是没有用molloc()为它们分配空间,所以不能用于scanf()fputs()等函数,
要想调试程序用编译时要加上-g选项:
gcc hello.c -o hello -g

然后用gdb调试,具体使用方法还是用man gdb来看吧,比较复杂.

23,120

社区成员

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

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