C语言随机读写数据文件(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangshuxuncom/article/details/84966294

void rewind(FILE * fp):将文件位置标记重新指向文件开头,该函数没有返回值;
【例子】计算机D盘根目录有一个存放学生信息的stud.dat文件,请先讲文件信息显示在控制台,然后在将数据复制到F盘stud.dat文件中。

#include <stdio.h>
#include <stdlib.h>

int main(){
    struct Student{
        char name [10];
        int num;
        int age;
        char addr [30];
    } stud [5];

    FILE * input = fopen("D:\\stud.dat","rb");

    if(input == NULL){
        printf("无法打开文件");
        exit(0);
    }

    int validCount;//实际读取多少数据项
    while((validCount = fread(stud,sizeof(struct Student),5/*最多读取5个数据项*/,input))!=0){
        for(int i=0;i<validCount;++i){
            printf("%s %d %d %s\n",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
        }
    }

    rewind(input);//将文件位置标记重新指向文件开头,否则因文件位置标记经过上面循环执行指向文件末尾而无法将已有文件中的数据复制到新文件中。

    FILE * output = fopen("F:\\stud.dat","wb");

    if(output == NULL){
        printf("无法打开文件");
        exit(0);
    }

    while((validCount = fread(stud,sizeof(struct Student),5/*最多读取5个数据项*/,input))!=0){
        fwrite(stud,sizeof(struct Student),validCount,output);
    }
    fclose(output);
    fclose(input);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wangshuxuncom/article/details/84966294