zoukankan      html  css  js  c++  java
  • 文件操作之格式化IO

    其实在我使用最多的文件操作中,还是喜欢格式化IO控制的方式,简单方便易理解。

    #include <stdio.h>
    #include<stdlib.h>
    int main()
    {
        FILE *fp;
        const char *filename="F:/mytest/mytext.txt";
        fp=fopen(filename,"w+");
        char *text="今天是个好日子!
    你觉得呢?";
        if(fp==NULL)
        {
            printf("open file failure!");
            exit(1);
        }
        else
        {
            fprintf(fp,"%s",text);//用这个写入中文简直好用
        }
        fclose(fp);
    
       return(0);
    }

    看了fprintf函数之后,肯定不能忘了fscanf函数啊:

     1 #include <stdio.h>
     2 #include<stdlib.h>
     3 int main()
     4 {
     5     FILE *fp;
     6     const char *filename="F:/mytest/mytext.txt";
     7     fp=fopen(filename,"w+");
     8     char *text="今天是个好日子!
    你觉得呢?";
     9     if(fp==NULL)
    10     {
    11         printf("open file failure!");
    12         exit(1);
    13     }
    14     else
    15     {
    16         fprintf(fp,"%s",text);//用这个写入中文简直好用
    17     }
    18     fclose(fp);
    19     
    20     
    21     
    22     fp=fopen(filename,"r+");
    23     char buff[1024];
    24     if(fp==NULL)
    25     {
    26         printf("open file failure!");
    27         exit(1);
    28     }
    29     else
    30     {
    31         while(!feof(fp))//为什么要循环?因为我要读取多行,只一次的话只能读取一行
    32         {
    33             fscanf(fp,"%s",buff);
    34             printf("%s
    ",buff);
    35         }
    36     }
    37     fclose(fp);
    38    return(0);
    39 }

  • 相关阅读:
    继承 接口 多态
    组合(补充)和 继承
    面向对象初级
    模块和包
    time,random,os,sys,序列化模块
    inline详解
    C++静态数据成员与静态成员函数
    OpenCV Mat数据类型及位数总结(转载)
    拼搏奋斗类
    c++虚函数实现机制(转)
  • 原文地址:https://www.cnblogs.com/yangguang-it/p/6699837.html
Copyright © 2011-2022 走看看