从键盘输入一行字符,写入到string.txt文本文件中

《程序设计基础实训指导教程-c语言》
ISBN 978-7-03-032846-5
p197
8.1.2 上级实训内容

【实训内容1】从键盘输入一行字符,写入到string.txt文本文件中

#include
#include
#include
int main()
{
	FILE *fp;
	char str;
	if((fp=fopen("string.txt","w"))==NULL)
	{
		printf("file open error\n");
		exit(0);
	}
	printf("输入字符串:");
	while((str=getchar())!='\n')
	{
		fputc(str,fp);
	}
	fclose(fp);

	//查看
	if((fp=fopen("string.txt","r"))==NULL)
	{
		printf("file open error\n");
		exit(0);
	}
	while((str=(fgetc(fp)))!=EOF)
	{
		putchar(str);
	}
	#if 0
	while(!feof(fp))	//最后会多输出一个乱码
	{
		str=getc(fp);
		putchar(fp);
	}
	putchar('\n');
	#endif
}

在这里插入图片描述

你可能感兴趣的:(#,专升本c语言)