如何将文件读入结构数组?

时间:2019-04-21 02:06:22

标签: c arrays file struct

我正在尝试将文本文件读取到结构数组中,但是在尝试打印该数组时,该结构为空。打印功能工作正常,我认为问题出在getRawData中。

'1','0','0','1'
'1001'
struct student
{
    char ID[MAXID + 1];
    char f_name[FIRST_NAME_LENGTH + 1];
    char s_name[LAST_NAME_LENGTH + 1];
    int points[MAXROUNDS];
};

所以我的目标是从文件中获取数据并将其写入struct数组中存储的任何内容。我已经为此工作了太久了,希望能有所帮助。

1 个答案:

答案 0 :(得分:2)

看看getRawData()中的这段代码,首先您正在读取文件以标识总行数:

    while(!feof(outtput))  
    {
        ch = fgetc(outtput);
        if(ch == '\n')
        .....
        .....

由于此,文件流指针指向EOF,然后在for循环中,您正在做

    for(i = 0; i < nmemb; i++) {
        fscanf(outtput, "%s %s %s", records[i].f_name, records[i].s_name, records[i].ID);
        .....
        .....

在这里,fscanf()必须返回EOF,因为从流文件中读取的内容已经没有了。读取文件时,应检查fscanf()的返回值。

在再次读取文件之前,应将指针重置为文件的开始。您可以使用rewind(ptr)fseek(fptr, 0, SEEK_SET)。下面是一个示例程序,向您展示代码中发生了什么以及该解决方案的工作原理:

#include <stdio.h>

int main (void) {
        int ch;
        int lines = 0;
        char str[100];
        FILE *fptr = fopen ("file.txt", "r");

        if (fptr == NULL) {
                fprintf (stderr, "Failed to open file");
                return -1;
        }

        while (!feof(fptr)) {
                ch = fgetc (fptr);
                if(ch == '\n') {
                        lines++;
                }
        }

        printf ("Number of lines in file: %d\n", lines);
        printf ("ch : %d\n", ch);

        printf ("Now try to read file using fscanf()\n");
        ch = fscanf (fptr, "%s", str);
        printf ("fscanf() return value, ch : %d\n", ch);

        printf ("Resetting the file pointer to the start of file\n");
        rewind (fptr);  // This will reset the pointer to the start of file
        printf ("Reading file..\n");

        while ((ch = fscanf (fptr, "%s", str)) == 1) {
                printf ("%s", str);
        }

        printf ("\nch : %d\n", ch);
        fclose (fptr);

        return 0;
}

上述程序中文件读取的内容:

Hello Vilho..
How are you!

输出:

Number of lines in file: 2
ch : -1
Now try to read file using fscanf()
fscanf() return value, ch : -1
Resetting the file pointer to the start of file
Reading file..
HelloVilho..Howareyou!
ch : -1

在这里您可以看到,第一个ch : -1表示文件指针位于EOF,如果尝试读取,则将得到EOF,因为没有什么要读取的内容。重置文件指针后,您可以看到fscanf()能够读取文件。

您不应使用while (!feof(file))。选中this

相关问题