从/向二进制文件读取和编写malloc链接列表

nyc*_*cht 5 c binary struct file

我需要为我正在上课的课程做作业.这是一个简单的电话本应用程序在C,我有一点麻烦,因为我需要在程序中使用一些新的东西,截止日期非常紧张.

我环顾四周,找到了一些答案,但每次都会出现一个新答案.:)

这是我的(简化)计划:

typedef struct record
{
    char fname[31];
    char lname[31];
    char tel[21];
    struct record *next;
} record;


record *new_entry(record *first, char *fname, char *lname, char *tel)
{
    record *new;
    new=(record*) malloc(sizeof(record));
    strcpy(new->fname, fname);
    strcpy(new->lname, lname);
    strcpy(new->tel, tel);
    new->next=first;
}


void fileopen (char *db_file)
{
    FILE *fp;  

    fp=fopen(db_file, "rb");
    if (fp==NULL) 
    {
        fp=fopen(db_file, "wb");
        fclose(fp);
        fp=fopen(db_file, "r+b");
    }
}



int main
{
 char db[51];
 record *next = NULL;

 printf("File:           "); scanf("%s, db);
 fileopen(db);
 printf("First name:     "); scanf("%s", fname);
 printf("Last name:      "); scanf("%s", lname);
 printf("Phone number:   "); scanf("%s", tel);
 first=new_entry(*first, fname, lname, tel);
}
Run Code Online (Sandbox Code Playgroud)

我遗漏了不必要的部分.现在我知道它并不多,但我的班长说我应该使用二进制文件来存储和恢复数据.但是我真的很困惑,如果我应该如何使用fread和fwrite.


非常感谢您的解决方案!我想我开始理解这个概念.该程序现在存储数据(至少我认为它存在,因为随着我添加更多数据,文件不断增长.)当启动新的二进制文件时,程序在请求时正确显示数据,但如果我关闭它,并重新打开同一个文件,尝试列出联系人时没有任何反应.

这是(再次简化,我在实际作业中的一个记录中有10个细节)打开功能:

record *open (char *db_file, record start)
{
  FILE *fp
  record *temp = start;
  fp=fopen(db_file, "rb");
  while (fread(temp, sizeof(rekord), 1, fp)>0) 
    {
        fread(temp->fname, sizeof temp->fname, 1, fp);
        fread(temp->lname, sizeof temp->lname, 1, fp);
        fread(temp->tel, sizeof temp->tel, 1, fp);
    temp=temp->next;
    }
  fclose(fp);
  return temp;
}
Run Code Online (Sandbox Code Playgroud)

在main()中,我使用:

start=open(db, start);
Run Code Online (Sandbox Code Playgroud)

声明部分:

record *start=NULL;
Run Code Online (Sandbox Code Playgroud)

如果有人回复,再次感谢.

md5*_*md5 4

要将链接列表写入文件,您可以运行该列表并写入结构。

#include <stdio.h>

record *it = first;

while (it != NULL) {
    fwrite (it->fname, sizeof it->name, 1, stream);
    fwrite (it->lname, sizeof it->lname, 1, stream);
    fwrite (it->tel, sizeof it->tel, 1, stream);
    it = it->next;
}
Run Code Online (Sandbox Code Playgroud)

stream是一个可以使用wb模式打开的文件fopen