我尝试将文本文件的内容加载到结构中。
我的想法是这样的:
我有两个文件struct.h
,main.c
和一个list.txt
文件。
在文件中struct.h
:
struct analg {
char word[6];
char signature[6];
};
struct analg h[106];
FILE *fp;
在文件中main.c
:
#include<stdio.h>
#include "struct.h"
void load() {
fp = fopen("list.txt", "r");
if(fp == NULL) {
printf("fail");
return 1;
}
else {
printf("file loaded!\n");
}
fclose(fp);
return;
}
void print() {
int i;
for(i=0; i<1000; i++) {
while(fgets(h[i].word, 6, fp)) {
printf("%s", h[i].word);
}
}
return;
}
int main () {
int choice;
do {
printf("choose L or P: ");
scanf("%s", &choice);
switch(choice) {
case 'l':
load();
printf("\n[l]oad - [p]rint\n");
break;
case 'p':
print();
printf("\n[l]oad - [p]rint\n");
break;
default:
break;
}
} while(choice!='q');
return;
}
在文件中list.txt
:
throw
timer
tones
tower
trace
trade
tread
所以我尝试通过按“L”来加载文本文件到结构,然后当我按“p”时会显示,但事实并非如此!