我正在尝试用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/