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

/* 在磁盘建立文件,而后接受键盘输入。
 * 从键盘输入完之后,把文件输出到磁盘并保存 
 * 最后把磁盘内容打印到屏幕*/
 
#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;
}
相关文章
相关标签/搜索