我想在二进制模式的 *.dat 文件中存储信息或从中读取信息。该文件包含以下数据(以二进制形式编码):
License: 123456
Owner: John Doe
Value: 10000.00
License: IAMDOE
Owner: Jane Doe
Value: 20000.00
这是我的代码:
#include <stdio.h>
#include <string.h>
#define MAXPLEN 80
typedef struct {
char none; /* used for registry initiated by '\0' ,should be ingnored */
char owner[MAXPLEN];
char license[6];
double value;
} veiculo_t;
/* i need to use the following functions in the process */
void print_registry(veiculo_t *v)
{
printf("Owner: %s - License: %.6s - Value: %.2lf \n", (*v).owner, (*v).license, (*v).value);
}
void read_registry(veiculo_t *v)
{
char license2[8];
printf("Name of the owner:\n");
fgets((*v).owner,100,stdin);
printf("License plate:\n");
fgets(license2,10,stdin);
memcpy(&(v->license),license2,6);
printf("Value:\n");
scanf("%lf",&(*v).value);
}
int op_menu()
{
int op;
printf("\n0 - end\n");
printf("1 - insert\n");
printf("2 - print\n");
printf("option: ");
scanf("%d",&op);
getchar();
return op;
}
int main()
{
int op;
op_menu();
if (op=1){
/* !!!!!HELP HERE!!!!!! */
}
if (op=2){
FILE *f=fopen("veic.dat", "rb");
if (f == NULL)
{
printf("Not opened!\n");
}
else
/* !!!!!HELP HERE!!!!!! */
}
}
不太了解“流”...一些提示将不胜感激!
最佳答案
首先,更改以下内容,否则您将永远无法进入“菜单”。
op = op_menu(); //op should be assigned by the return value of open_menu
if (op==1){...
if (op==2){... // I believe you want '==' not '='
根据注释,您必须调用read_registry
方法。添加的代码:
if (op==1){
//insert
veiculo_t *t = malloc(sizeof(veiculo_t));
read_registry(t);
FILE *f=fopen("veic.dat", "ab");
if (f == NULL)
{
printf("open file failed\n");
}
fwrite(t, sizeof(char), sizeof(*t), f);
free (t);
}
if (op==2){
//print
FILE *f=fopen("veic.dat", "rb");
if (f == NULL)
{
printf("Not opened!\n");
}
else
{
veiculo_t *t = malloc(sizeof(veiculo_t));
printf("sizeof t: %d\n", sizeof(*t));
while(fread(t, sizeof(char), sizeof(*t), f))
print_registry(t);
free(t);
}
示例代码仅供引用,我更想提供一种思考而不是答案,但似乎代码总是清晰而强大。在下面的例子中我写文件使用追加模式,如果你想每次都重新写文件,写文件时在fopen
中改变模式。
希望对您有所帮助。
关于c - 如何在二进制 *.dat 文件中存储或打印信息? C编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22651617/