C fwrite和fread 文件相关

fwrite和fread函数用于二进制文本读写,按数据块读文件
而fprintf和fscanf函数用于文本文件,以ASCII码存储的文件读写
fseek函数好像也主要用于二进制文件(第二段代码如果我是文本文件,不改变fseek函数语句,会出现错误)

//将内容先以二进制形式存到文件中
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student
{
    long id;
    char name[10];
    int year;
}STUDENT;
int main()
{
    FILE *fp;
    STUDENT stu[3];
    int i,f=100310121;
    fp=fopen("score2.txt","wb");
    for(i=0;i<3;i++){
        stu[i].id=f;
        f++;
    }
    strcpy(stu[0].name,"王刚");
    strcpy(stu[1].name,"李小明");
    strcpy(stu[2].name,"王力宏");
    int x=1991;
    for(i=0;i<3;i++){
        stu[i].year=x;
        x++;
    }

    fwrite(stu,sizeof(STUDENT),3,fp);


    fclose(fp);
    return 0;
}

#include <stdio.h>
#include <stdlib.h>
//读取第k条记录
typedef struct student
{
    long id;
    char name[10];
    int year;
}STUDENT;
void searchfile(char filename[],long k);
int main(){
    long k;
    printf("input the searching record number:");
    scanf("%ld",&k);
    searchfile("score2.txt",k);
    return 0;
}

void searchfile(char filename[],long k){
    FILE *fp;
    STUDENT stu;
    if((fp=fopen(filename,"rb"))==NULL){
        printf("failure to open %s!\n",filename);
    }
    fseek(fp,(k-1)*sizeof(STUDENT),0);//第k条记录,偏移k-1位
    printf("record number = %d\n",ftell(fp)/sizeof(STUDENT)+1);//ftell()返回的是字节偏移量,偏移量为它再除以结构体变量所占字节数,当前位置为偏移量+1
    fread(&stu,sizeof(STUDENT),1,fp);
    printf("%10ld%8s%6d\n",stu.id,stu.name,stu.year);
    printf("record number = %d\n",ftell(fp)/sizeof(STUDENT)+1);//fscanf()读取完一条记录后,文件位置指针指向下一条记录

    fclose(fp);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值