文件内容拓展

文件的随机读写

顺序文件处理:在顺序文件处理过程中,数据项是一个接着一个进行读取或者读写。

随机访问:允许在文件中随机定位,并在文件的任何位置直接读写数据

方法:为了实现文件的定位,在每一次打开的文件中,都有一个文件位置指针也称文件位置标记,用来指向当前读写文件的位置,它保存了文件中的位置信息。

eg 这里给出两个函数来定义的文件位置指针。

1
2
int fseek(FILE *fp, long offset, int fromwhere);
void rewind(FILE *fp);

fseek()函数

功能:函数fseek()的功能是将fp的文件位置指针从fromwhere开始移到offset个字节,指示下一个要读取数据的位置

参数的意义offset是一个偏移量,它告诉文件位置指针要跳多少个字节。offect为正时,向后移动,为负时,向前移动。AXSI C要求位移量offset是长整型数据(常量后加L)。fromwhere用于确定偏移量计算的起始位置,它的情况可能有三种:

  • SEEK_SET或0,表示文件开始处
  • SEEK_CUR或1,代表文件当前的位置
  • SEEK_END或2,代表文件结尾处

rewind()函数

功能:将文件位置指针指向文件首字节,即重置位置指针到文件首部

如果函数fseek()调用成功,则返回0值,否则返回非0值

ftell()函数

功能:用于读取当前文件位置指针的函数,用于相对于文件起始位置的字节偏移量来表示返回的当前文件位置指针

原型

1
long ftell(FILE *fp);

fflush()函数

功能:fflush()函数的功能是无条件地把缓冲区中的所有数据写入物理设备

通过下列的这个程序实例,可以实现对文件中的数据的搜索

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<stdio.h>
#include<stdlib.h>
typedef struct date
{
int year;
int month;
int day;
}DATE;
typedef struct student
{
long studentID;
char studentName[10];
char studentSex;
DATE birthday;
int score[4];
float aver;
}STUDENT;
void SearchinFile(char fileName[],long k);
int main()
{
long k;
printf("Input the searching record number:");
scanf("%ld",&k);
SearchinFile("D:\\student.txt",k);
return 0;

}
void SearchinFile(char fileName[],long k)
{
FILE *fp;
int j;
STUDENT stu;
if((fp = fopen(fileName,"r")) == NULL)
{
printf("Faliure to open %s!\n",fileName);
exit(0);
}
fseek(fp,(k-1)* sizeof (STUDENT), SEEK_SET);
fread(&stu, sizeof(STUDENT),1,fp);
printf("%10ld%8s%3c%6d/%02d/%02d",stu.studentID,stu.studentName,stu.studentSex,
stu.birthday.year,stu.birthday.month,stu.birthday.day);
for(j = 0; j < 4; j++)
{
printf("%4d",stu.score[j]);
}
printf("%6.1f\n",stu.aver);
fclose(fp);

}
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2015-2023 dwx
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信