C语言输入输出函数全解析
1. 随机文件访问函数
在文件操作中,有时需要随机读取特定记录。下面的代码实现了从文件中读取特定记录的功能:
/*
** Reads a specific record from a file. The arguments are the stream
** from which to read, the desired record number, and a pointer to
** the buffer into which the data should be placed.
*/
#include <stdio.h>
#include "studinfo.h"
int
read_random_record( FILE *f, size_t rec_number, StudentInfo *buffer )
{
fseek( f, (long)rec_number * sizeof( StudentInfo ), SEEK_SET );
return fread( buffer, sizeof( StudentInfo ), 1, f );
}
此函数 read_random_record
接收三个参数:文件流指针 f
、所需记录的编号 rec_number
以及用于存储数据的缓冲区指针 buffer
。通过 fseek
函数将文件指针定位到指定记录的位置,然后使用