• C语言 文件的读写操作


     //凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 void main(){
     4     int a;
     5     void write();
     6     void read();
     7     while(1){
     8         printf("*****************
    ");
     9         printf("1.write
    ");
    10         printf("2.read
    ");
    11         printf("0.exit
    ");
    12         printf("*****************
    ");
    13         printf("Please choose:");
    14         scanf("%d",&a);
    15         if(a==0){
    16             exit(0);
    17         }
    18         else if(a==1){
    19             write();
    20         }
    21         else if(a==2){
    22             read();
    23         }
    24         else
    25             printf("input error!
    Please choose:");
    26     }  
    27     
    28 }
    29 
    30 void write(){
    31     FILE *fp;
    32     char ch,filename[20];
    33     printf("Please input the filename you want to write:");
    34     scanf("%s",filename);
    35     if(!(fp=fopen(filename,"wt+"))){
    36         printf("Cannot open the file!
    ");
    37         exit(0);
    38     }
    39     
    40     printf("Please input the sentences you want to write:");
    41     ch=getchar();
    42     ch=getchar();
    43     while(ch!=EOF){  //EOF: Ctrl+z
    44         fputc(ch,fp);
    45         ch=getchar();
    46     }
    47     
    48     fclose(fp);
    49     
    50 }
    51 
    52 void read(){
    53     FILE *fp;
    54     char ch,filename[20];
    55     printf("Please input the filename you want to read:");
    56     scanf("%s",filename);
    57     if(!(fp=fopen(filename,"r"))){
    58         printf("Cannot open the file!
    ");
    59         exit(0);
    60     }
    61     
    62     printf("%s 的内容为:",filename);
    63     while(ch!=EOF){  //EOF(end of file): Ctrl+z
    64         ch=fgetc(fp);
    65         putchar(ch);
    66     }
    67     
    68     fclose(fp);
    69 }

    程序运行前的当前目录:

    程序运行结果:

    当前目录多了一个文件wrr.txt

    打开该文件:

     

    里面已经有了刚刚输入的内容:

    Hello world!
    I am RONGRONG WANG!
    My English name is Kailugaji!
    Thank you!

  • 相关阅读:
    lottie 动画
    .netcore 跨域问题
    数据库规范
    课程总结
    Beta版本发布
    个人作业-Alpha项目测试
    第三次作业结对编程
    第二次作业-熟悉使用工具
    第一次阅读作业
    个人作业-Alpha项目测试
  • 原文地址:https://www.cnblogs.com/kailugaji/p/8592777.html
Copyright © 2020-2023  润新知