바이너리 모드에있는 * .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
쓸 때 모드를 변경 합니다.
도움이 되었기를 바랍니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다