鱼C论坛

 找回密码
 立即注册
查看: 2619|回复: 1

一个文件操作有点纠结用法

[复制链接]
发表于 2012-5-16 20:24:12 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<conio.h>
int main()
{
FILE *fp;
char ch,st[30];
if((fp=fopen("string.txt","at+"))==NULL)
{
  printf("Cannot open file.please strike any key exit!");
  getch();
  exit(1);
}
printf("please a string:\n");
scanf("%s",st);
fputs(st,fp);
rewind(fp);
/*fgets(st,20,stdin);
printf("%s",st);
fclose(fp);*/
ch=fgetc(fp);
while(ch!=EOF)
{
  putchar(ch);
  ch=fgetc(fp);
  //fgets(st,30,stdin);
  //printf("%s",st);
}
printf("\n");
fclose(fp);
}为什么加注释的地方不能这样做
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2012-5-21 23:50:42 | 显示全部楼层
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<conio.h>
int main()
{
FILE *fp;
char ch,st[30];
if((fp=fopen("string.txt","at+"))==NULL)
{
  printf("Cannot open file.please strike any key exit!");
  getch();
  exit(1);
}
printf("please a string:\n");
scanf("%s",st);
fputs(st,fp);
rewind(fp);
fgets(st,20,stdin);
printf("%s",st);
//fclose(fp);/**/

ch=fgetc(fp);
while(ch!=EOF)
{
  putchar(ch);
  ch=fgetc(fp);
  //fgets(st,30,stdin);
  //printf("%s",st);
}
printf("\n");
fclose(fp);
}

把fclose(fp)注释掉就可以了,因为fclose(fp)关闭了文件,后面再调用fgetc(fp)自然会出错了
小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-4 08:52

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表