[编程练习] C语言 输入输出

#include <stdlib.h>
#include <stdio.h>

void main ()
{
	//initialize the file pointer and a char character,a char array
	FILE *fp;
	char ch, filename[10];
	
	//enter the filename and open it with "a+" style
	scanf ("%s", filename);
	fp = fopen (filename, "a+");
	
	//if fp doesn't exist output "cannot open file"
	if (!fp) {
		printf ("cannot open file\n");
		exit (0);
	}
	ch = getchar ();		//recieve '\n'
	ch = getchar ();		//receive the first character
	while (ch != '\n') {		//when receive '\n', exit the loop 
		fputc (ch, fp);		//enter a character into the file
		putchar (ch);		//output the character on the screen
		ch = getchar();		//receive another character from the keyboard
	}
	fclose (fp);			//close the file
	putchar (10);           //output '\n'

	fp = fopen (filename, "r");//read the file
	while (!feof (fp))	{
		ch = fgetc (fp);
		putchar (ch);
	}
	putchar (10);           //output '\n'
}

猜你喜欢

转载自blog.csdn.net/cp_oldy/article/details/88290457