当前位置: 代码迷 >> 综合 >> day11 C语言 随机读写
  详细解决方案

day11 C语言 随机读写

热度:57   发布时间:2024-01-17 14:39:14.0

C语言

随机读写

ftell

#include<stdio.h>
#include<stdlib.h>
#include<string.h>int main (void)
{
    FILE *fp;if((fp = fopen("hello.txt","w")) == NULL){
    printf("打开文件失败!\n");exit(EXIT_FAILURE);}printf("%ld\n", ftell(fp));//0fputc('Y',fp);//1个字符printf("%ld\n", ftell(fp));//1fputs("Yoona\n",fp);//6个字符printf("%ld\n", ftell(fp));//8/* 指针重新指向开头rewind(fp);fputs("Hello",fp);覆盖开头字节*/fclose(fp);return 0;
}

fseek

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 4
//SET CUR END
struct Stu
{
    char name[24];int num;float score;
} stu[N],sb;int main (void)
{
    FILE *fp;int i;if((fp = fopen("sorce.txt","w")) == NULL){
    printf("打开文件失败!\n");exit(EXIT_FAILURE);}printf("请开始录入成绩(格式:姓名 学号 成绩)");for(i = 0; i < N; i++){
    scanf("%s %d %f",stu[i].name,&stu[i].num,&stu[i].score);}fwrite(stu,sizeof(struct Stu), N, fp);fclose(fp);if((fp = fopen("sorce.txt","r")) == NULL){
    printf("打开文件失败!\n");exit(EXIT_FAILURE);}fseek(fp, sizeof(struct Stu), SEEK_SET);//指针从开头偏移一个结构体位置fread(&sb, sizeof(struct Stu), 1, fp);printf("%s(%d)的成绩是:%.2f\n",sb.name, sb.num, sb.score);fclose(fp);return 0;}