이진 파일 I/O를 테스트하고있었습니다. 그래서, 작은 프로그램을 만들어 연습 :fwrite는 쓰레기를 출력하고, fread는 쓰레기 구조를 읽습니다.
을 main.c :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "person.h"
int main()
{
struct person me;
struct person cpy_me;
FILE *dataWrite, *dataRead;
strcpy(me.fname, "john");
strcpy(me.lname, "smith");
me.age = 12;
printf("%s %s %d\n", me.fname, me.lname, me.age);
dataWrite = fopen("people.bin", "wb");
if (fwrite(&me, sizeof(struct person), 1, dataWrite) != 1)
fprintf(stderr, "Error!\n");
printf("Wrote to the file\n");
dataRead = fopen("people.bin", "rb");
fread(&cpy_me, sizeof(struct person), 1, dataRead);
printf("%s->Fname\n", cpy_me.fname);
printf("%s->Lname\n", cpy_me.lname);
printf("%d->Age\n", cpy_me.age);
fclose(dataWrite);
fclose(dataRead);
return 0;
}
person.h :
smith ÿÿb¸tÄ[½tà@ john @ à@
:
#ifndef PERSON_H_INCLUDED
#define PERSON_H_INCLUDED
#define MAXFIRST 10
#define MAXLAST 20
struct person
{
char lname[MAXLAST], fname[MAXFIRST];
int age;
};
#endif // PERSON_H_INCLUDED
이 파일 people.bin
등장 무엇인가
fread
의 결과가 표시되면 다음과 같이 표시됩니다.
바이너리 파일에서 사람이 읽을 수있는 형식으로 표시하지 않지만 다음과 같이 표시되어 있습니까? 나이가 보이지 않기 때문에 나는 그렇게 생각하지 않으며, fread
은 쓰레기를 읽음을 보여주고 있습니다.
fclose (data); data = fopen ("people.bin", "rb"); fread (& cpy_me, ...' – BLUEPIXY
이제 나는 이것을 알게되었다 :'smith ÿÿb¸tÄ [½tà @ john @ à @ ' – stackptr
그것은 나에게 잘 작동 – BLUEPIXY