您的位置:首页 > 其它

创建磁盘文件,输出内容到文件中,并把磁盘内容打印到屏幕

2015-10-22 00:00 483 查看
/* 在磁盘创建文件,然后接受键盘输入。
* 从键盘输入完以后,把文件输出到磁盘并保存
* 最后把磁盘内容打印到屏幕*/

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char ch;
puts("Input your data, and enter Ctrl+Z to exit:\n");

/*check if success open the file*/
if((fp = fopen("my data file.txt", "w")) == NULL){
fprintf(stderr, "Error opening %s.\n", fp);
exit(1);
}

/*Get a character from keyboard*/
while ((ch = getchar()) != EOF)
/*Write a character to the file*/
putc(ch,fp);

/*remenber close the file*/
fclose(fp);
puts("You data file is:\n");

/*Ropen the file ready to read*/
if((fp = fopen("my data file.txt", "r")) == NULL){
fprintf(stderr, "Error opening %s.\n", fp);
exit(1);
}

ch = fgetc(fp);
while(ch != EOF){
putchar(ch);
ch = fgetc(fp);
}
///*read a character from file*/
//while((ch=getc(fp)) != EOF)
// /*display a character on screen*/
// printf("%c",ch);

fclose(fp);
printf("\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: