1

我尝试将文本文件的内容加载到结构中。

我的想法是这样的:

我有两个文件struct.hmain.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”时会显示,但事实并非如此!

4

2 回答 2

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 没有用于序列化和反序列化结构的内置方法,因此您需要为磁盘上的文件定义正式语法并编写可以将该语法解析为结构的代码。

于 2013-02-26T23:09:06.613 回答
1

在您的代码中,我看到有 2 个潜在问题。选择必须是基于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;
 }

主要功能是,

诠释主要(){

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;
}

最后一点。在使用scanfif 语句scanf("%s", &choice);时,退出时会生成运行时检查错误main,并显示变量周围的堆栈已损坏的消息choice

于 2013-02-26T23:09:53.303 回答