如何使用 C 中的结构创建数据库

How to Create database using structures in C

我正在尝试在 C 中创建二进制数据库写入程序。

问题是当数据库更新时,程序会删除文件以前的数据,只存储新的更新数据。

程序:

#include <stdio.h>
int main (){

    struct STUINFO { char  fname[30], lname[30], year[5], batchno[30];};
    int id, s, roll;
    FILE *outfile;

    // open file for writing

    if (outfile = fopen ("stuinfo.bin", "w") == NULL)
    {
        fprintf(stderr, "\nError opening file\n");
        return (-1);
    }
    printf("\nEnter Nine Digit Enrollment no. :\n");
    scanf("%d", &roll);
    id = roll - 100000000;
    if (id < 0 ) { 
        printf("Please Enter Valid Nine Digit no.\n");
        return -2;
        }

    struct STUINFO output;
    printf("Enter First Name :\n");
    scanf("%s", output.fname);
    printf("Enter Last Name :\n");
    scanf("%s", output.lname);
    printf("Enter Year of Semester :\n");
    scanf("%s", output.year);
    printf("Enter Batch no. :\n");
    scanf("%s", output.batchno);

    s = sizeof(struct STUINFO);
    fseek(outfile, +id*s, SEEK_CUR);
    // write struct to file

    if(fwrite (&output, sizeof(struct STUINFO), 1, outfile) != 0) 
        printf("contents to file written successfully !\n");
    else 
        printf("error writing file !\n");

    return 0;
}

文件在您使用时被截断:

fopen ("stuinfo.bin", "w");

要打开文件进行写入而不截断,请使用:

fopen ("stuinfo.bin", "r+");

但是如果文件不存在,这将不会创建文件,因此您必须检查错误,如果失败则以 w 模式打开。

if ((outfile = fopen("stuinfo.bin", "r+") == 0) {
    outfile = fopen("stuinfo.bin", "w");
}

How to choose open mode with fopen()?

此外,由于您正在编写二进制文件,因此您应该使用 b 修饰符:

fopen ("stuinfo.bin", "rb+");

它在 Unix 上没有区别,但在其他操作系统上却有区别,因此对于可移植性来说是必要的。