我尝试将文本文件的内容加载到结构中。
我的想法是这样的:
我有两个文件,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'时会显示,但它不是!
答案 0 :(得分:1)
我会评论你的代码在做什么:
void load() {
fp = fopen("list.txt", "r"); // opens the file for reading
if(fp == NULL) {
printf("fail"); // if the file couldn't be opened, return an error
return 1; // (aside: a void function can't return an int)
}
else {
printf("file loaded!\n"); // tell the user that the file was opened
}
fclose(fp); // close the file, having read nothing from it
return;
}
在任何时候你都没有从文件中读取任何内容。因此,你在内存中拥有的内容与你在磁盘上拥有的内容无关。
C没有用于序列化和反序列化结构的内置方法,因此您需要做的是在磁盘上为您的文件定义一个正式语法,并编写可以将该语法解析为结构的代码。
答案 1 :(得分:0)
在您的代码中,我看到有两个潜在的问题。选择必须是基于l
或p
切换的角色。您可能还需要添加案例来处理大写。
另一个问题是在load
函数中,您正在关闭文件指针。因此,当您输入print
函数时fgets
可能无效,因为fp
已经关闭。
要将文件加载到结构中,必须将加载修改为
void load() {
fp = fopen("list.txt", "r");
if(fp == NULL) {
printf("fail");
return; // There was an error in original code as this was returning 1
}
do{
fgets(h[count++].word, 6, fp); // Count is a global variable - no. of elements read
}while(!feof(fp));
printf("file loaded!\n");
fclose(fp);
return;
}
相应的打印功能将变为
void print(){
int i;
printf("Inside print\n");
for(i=0; i < count; i++) {
printf("%s", h[i].word);
}
return;
}
主要功能是,
int main(){
char choice;
do{
printf("choose L or P: ");
scanf("%c", &choice); //Only character is read and hence, %s is not required
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:
case 'q':
break;
}
} while(choice !='q');
return 0;
}
最后一点。在scanf
语句中,如果使用scanf("%s", &choice);
,则在main
退出时会生成运行时检查错误,并显示堆栈在变量choice
周围已损坏。