파일에서 데이터를 읽고 구조체에 데이터를 저장하려고합니다. 구조체는 다음과 같습니다.파일에서 구조체로 데이터 읽기
struct someData {
int number;
char *name;
};
파일의 데이터 형식은 다양 할 수 있습니다. 지금은 CSV 형식으로 읽으려고합니다. 데이터는 항상 정수 다음에 오는 문자열입니다.
some string data,100
another string,500
여기는 데이터를 읽고 구조체에 배치하려고하는 코드의 일부입니다.
FILE *ifp;
char *mode = "r";
char *name;
int number;
ifp = fopen("myDataFile.txt", mode);
if (ifp == NULL) {
fprintf(stderr, "Can't open input file in.list!\n");
exit(1);
}
// read up to 100 characters up to a comma, then a decimal
while(fscanf(ifp, "%100[^,],%d\n", name, &number) != EOF){
// print out the data we got
printf("Data from file: %s %d", name, number);
struct someData *newData = (struct someData *) malloc(sizeof(struct someData));
newData->number = number;
newData->name = name;
printf("Name: %s Number: %d\n\n",newData->name, newData->number);
}
인쇄 문
나에게주는 두 번째 이름은 차단 실제로 이상한 문자의 몇 가지를 인쇄 끝됩니다Data from file: some string d 100
Name: some string d Number: 100
Data from file: another stri Number: 500
Name: another stri Number 500
다음과 같습니다. while 루프에서 fscanf에 문제가 있다고 생각합니다. % 100 대신 % s를 사용하는 것과 같은 데이터를 얻으려면 몇 가지 다른 방법을 시도했지만 아무 것도 작동하지 않습니다.
'char * name;'name은 배열을 가리 키지 않습니다. fscanf 전에'if' –