我想从二进制模式的*.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 ' ' ,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 - endn");
printf("1 - insertn");
printf("2 - printn");
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 failedn");
}
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: %dn", sizeof(*t));
while(fread(t, sizeof(char), sizeof(*t), f))
print_registry(t);
free(t);
}
示例代码只是供您参考,我想提供一个思考多于一个答案,但似乎代码总是清晰而强大。在下面的例子中,我使用追加模式写文件,如果你想每次都重写文件,在写文件时更改fopen
模式。
希望对大家有所帮助
fwrite
和fread
可根据您的需要使用。
下面是一个示例程序,说明了它们的用法:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
FILE* out = fopen("data.o", "wb");
int i = atoi(argv[1]);
fwrite(&i, sizeof(int), 1, out);
fclose(out);
FILE* in = fopen("data.o", "rb");
fread(&i, sizeof(int), 1, in);
fclose(in);
printf("Number saved and restored from file: %dn", i);
}
程序执行结果:
<>之前>> ./test-51 2345从文件保存和恢复的号码:2345>> ./test-51 -200从文件中保存和恢复的数量:-200之前输出文件的大小,如您所料,只有4个字节。
<>之前>> wc data.o0 14数据