IO高级编程——获取特定位置上的数据(lseek函数的使用)

本文介绍了一个使用C语言进行文件操作的例子,包括文件的创建、打开、读写及使用结构体来存储学生信息。通过具体代码展示了如何利用结构体进行数据组织,并实现了基本的数据输入与保存功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1、demo1.c

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
struct stu
{
    int no;
    char name[20];
    float score;
};
/*
1.判定文件是否存在,存在打开,不存在创建
2.输入记录
3.保存记录
4.提示继续输入
5.继续/不继续
6.关闭文件
*/
int openfile(const char *filename)
{
    int fd;
    fd=open(filename,O_RDWR|O_CREAT|O_EXCL,0666);
    if(fd==-1)//表示文件存在,则打开
    {
        fd=open(filename,O_RDWR|O_APPEND);
        return fd;
    }
    return fd;
}
void input(struct stu *record)
{
    bzero(record,sizeof(struct stu));
    printf("输入学号:");
    scanf("%d",&(record->no));
    printf("输入姓名:");
    scanf("%s",record->name);
    printf("输入成绩:");
    scanf("%f",&(record->score));
}
void save(int fd,struct stu *record)
{
    write(fd,record,sizeof(struct stu));
}
int iscontinue()
{
    char c;
    printf("是否继续输入:\n");
    //fflush(stdin);
    //fflush(stdout);
    scanf("\n%c",&c);    
    if(c=='Y' || c=='y')
    {
        return 1;
    }
    return 0;
}

int main()
{
    int fd;
    int r;
    struct stu s={0};
    fd=openfile("stu.dat");
    if(fd==-1) printf("openfile:%m\n"),exit(-1);
    
    while(1)
    {
        input(&s);
        save(fd,&s);
        r=iscontinue();
        if(r==0) break;
        system("clear");
    }
    close(fd);
    printf("输入完毕!\n");    
}


2、main.c

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


int main(){

   int fd = open("stu.dat",O_RDONLY);
   if(fd == -1){
     printf("open error:%m\n");
     exit(-1);
   }

   float score;

   int i;
   for(i = 0 ; i < 2 ; ++i){
      int r = lseek(fd,i*28+24,SEEK_SET);
      r = read(fd,&score,sizeof(float));
      printf("%.2f\n",score);
   }
}


3、编写makefile文件

lseek:
        gcc lseek.c -omain


4、在命令行中输入命令:  make


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

帅气的东哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值