程序员的知识教程库

网站首页 > 教程分享 正文

C/C++|按记录分块读写文件,对数据文件建立索引文件并实现查找

henian88 2025-02-15 15:41:36 教程分享 75 ℃ 0 评论

在文件中存储数据记录时,通常以二进制文件的形式存储,通过fwrite()函数或write()方法、fread()函数或read方法,以记录为单位进行文件读写。

另外,对于大量数据的查找,需要读入内存并在一个较大的空间内查找,时空相关的性能损耗是比较大,如果建立索引文件,并通过索引文件来索引数据的相对存储地址,则可取得较好的查找效率。

1 按记录分块读写文件

1.1 C实例

#include 
#include 

struct record {
    char name[10]; 
    int age;
};  
void fileWrite()
{
    struct record array[2] = {{"Ken", 24}, {"Knuth", 28}}; 
    FILE *fp = fopen("d:/test.txt", "w");
    if (fp == NULL) {  
        perror("Open file recfile"); 
        exit(1);  
    }  
    fwrite(array, sizeof(struct record), 2, fp);
    fclose(fp);
}
void fileRead()  
{  
    struct record array[2]; 
    FILE *fp = fopen("d:/test.txt", "r"); 
    if (fp == NULL) {  
        perror("Open file recfile");
        exit(1);  
    }  
    fread(array, sizeof(struct record), 2, fp);  
    printf("Name1: %s\tAge1: %d\n", array[0].name, array[0].age);  
    printf("Name2: %s\tAge2: %d\n", array[1].name, array[1].age);  
    fclose(fp);   
}
int main(void)
{  
    fileWrite();
    fileRead();
    getchar();
    return 0;
}

1.2 C++实例

#include  // 按记录分块读写文件
#include 
#include
#include
using namespace std;

class Student
{
public:
    Student(void) {}
    Student(int n, char nam[20], float s):
    num(n),score(s)
    {
        strcpy(name,nam);
    }
    void setNum(int n)
    {
        num=n;
    }
    void setName(char nam[20])
    {
        strcpy(name,nam);
    }
    void setScore(float s)
    {
        score=s;
    }
    void show()
    {
        cout<

2 对数据文件建立索引文件并实现查找

/*
(1) 将st数组中学生记录写入stud.dat文件作为主文件
(2) 输出主文件中的学生记录
(3) 建立与主文件相对应的索引文件,其中每个记录由两个字段组成:
    学号和该学生记录在数据文件中的位移量
    (例:主函数st数组中学号为2的学生许可,其位移量是5。
    由于本例用定长文件,可以根据位移量计算记录在主文件中的相对地址)。
    索引文件按学号有序。
(4) 输出索引文件中的全部记录
(5) 根据用户输入的学号,利用索引文件,用二分查找法找到对应的记录号,再通过主文件输出该记录

(6) 是否有想法,将这个项目再扩充了?加大数据量、哈希文件、多关键字文件……

*/
#include 
#include 
#include 

#define MaxRec 100          //最多的记录个数

typedef struct Index        //定义索引文件结构
{
    int no;                 //学号
    long offset;            //主文件中的记录号
} Index;

typedef struct
{
    int no;                 //学号
    char name[10];          //姓名
    int age;                //年龄
    char sex[3];            //性别
    int deg1,deg2,deg3;     //课程1-课程3成绩
} StudType;

void InsertSort(Index R[],int n) //采用直接插入排序法对R[0..n-1]按学号递增排序
{
    int i,j;
    Index temp;
    for(i=1; i=0 && temp.nono)
            high=mid-1;
        else if(idx[mid].no

-End-

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表