[英]How to store in or print information from a binary *.dat file? C programming
我想以二進制模式存儲* .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!!!!!! */
}
}
對“流”了解不多...一些提示將不為人知!
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: %d\n", i);
}
執行程序的結果:
>> ./test-51 2345 Number saved and restored from file: 2345 >> ./test-51 -200 Number saved and restored from file: -200
如您所料,輸出文件的大小只有4個字節。
>> wc data.o 0 1 4 data.o
首先,更改以下內容,否則您將永遠不會輸入“菜單”。
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
更改模式。
希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.