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

标签 c struct fopen fread

我正在尝试用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 上没有什么区别,但在其他操作系统上却有区别,因此它对于可移植性是必要的。

关于c - 如何使用 C 中的结构创建数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46538286/

相关文章:

c - C语言写入txt文件并打印数据

c - 将指针类型转换为 &(int*) 和 (int*)& 并将其分配给某个指针变量时有什么区别?

c - 传递给函数时如何访问二维结构数组中的所有成员?

struct - 为什么将结构传递给当前包中带有文字结构参数的函数不同于另一个包中的函数?

c - 为什么 scanf 不接受元素进入这个 C 结构?

c - 从文件读取数据并打印到另一个文件的程序

PHP 使用 fopen() 后清理内存

c - 使用 MPI 进行矩阵乘法

c - 未找到 Automake 错误 './ltmain.sh'

c - 在 C 中访问传递的结构数组的成员