• 文件的操作


    一直以来对文件的操作过程并不是特别熟悉,贴出以下代码来提醒自己,也从实际的例子中感受文件的操作运用

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    typedef struct Students
    {
    char Id[10];
    char name[20];
    double score;
    }Student;
    void main()
    {
    Student stu;//定义学生结构变量
    readText("./tmp/computer.txt");
    printf("------------------------------------- ");
    strcpy(stu.Id,"B10003");
    strcpy(stu.name,"隔壁老王");
    stu.score=99;
    writeText("./tmp/computer.txt",stu);
    readText("./tmp/computer.txt");
    }
    void writeText(char *filename,Student stu)
    {
    FILE *fp;
    fp=fopen(filename,"a+");//
    // a+ 打开一个文本文件,允许读写文件。如果文件不存在,则会创建一个新文件。
    // 读取会从文件的开头开始,写入则只能是追加模式。
    // a 打开一个文本文件,以追加模式写入文件。如果文件不存在,则会创建一个新文件。
    // 程序会在已有的文件内容中追加内容。
    if(!fp)
    {
    printf("文件不存在! ");
    exit(1);
    }
    fprintf(fp,"%s %s %lf ",stu.Id,stu.name,stu.score);
    fclose(fp);
    }
    void readText(char *filename)
    {
    Student stu;//定义学生结构变量
    FILE *fp;
    fp=fopen(filename,"r");//
    // a+ 打开一个文本文件,允许读写文件。如果文件不存在,则会创建一个新文件。
    // 读取会从文件的开头开始,写入则只能是追加模式。
    if(!fp)
    {
    printf("文件不存在! ");
    exit(1);
    }
    fscanf(fp,"%s%s%lf",stu.Id,stu.name,&stu.score);//读入一条记录
    while(!feof(fp))//如果位置指针不在文件末尾,即没有读到文件末尾
    {
    // fprintf(stdout,"%-8s%-8s%3.2lf ",stu.Id,stu.name,stu.score);//输出到标准输出stdout(屏幕)
    //等价于:
    printf("%-8s%-8s%3.2lf ",stu.Id,stu.name,stu.score);
    //%3.2lf 表示小数点前面有三位,小数点后面有两位
    // %-8d表示显示长度最小为8个字符,不足的话右边补空格,比如 123456,显示的是“123456空格空格”
    fscanf(fp,"%s%s%lf",stu.Id,stu.name,&stu.score);//读入下一条记录
    //stu.Id这里是数组名,本质上是地址所有不用再加取地址符&
    //stu.score是double类型变量,
    // 要加上取地址符“&”,让扫描函数知道把扫描到的第三数据放到的内存空间的地址
    }
    fclose(fp);
    }

  • 相关阅读:
    配置Robot Framework 环境时如何查看wxPython是否成功安装
    win10系统同时安装python2.7和python3.6
    Python 统计不同url svn代码变更数
    JavaWeb之 Servlet执行过程 与 生命周期
    JavaWeb之Servlet:请求 与 响应
    webservice(基础)
    通过反射,给对象之间赋值
    用反射获取类中的属性值
    tree树形
    破解weblogic(数据库)密码
  • 原文地址:https://www.cnblogs.com/wengst/p/12381808.html
Copyright © 2020-2023  润新知