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

问题描述 投票:0回答:1

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

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

//main//

case 'W':
      if(save(array, len) == 0);
      {
           printf("Data saved.\n");
      }     
      break;
case 'O':
      if(getRawData(array, len));
      {
            printf("File read.\n");
      }
      break;

int save(struct student *h, int num_students)
{
    char name[20];
    printf("Enter file name: " );
    scanf("%s", name); // Read in filename
    FILE *output = fopen(name, "w"); // open the file to write
    if (!output) {
        return -1; // error
    }
    for (int i = 0; i < num_students; ++i)
    {
        fprintf(output, "%s %s %s \n", h[i].f_name, h[i].s_name, h[i].ID);
        for(int j = 0; j < MAXROUNDS; j++)
        {

            fprintf(output, "%d\n", h[i].points[j]);
        }
        printf("Information of student %s %s (%s) written into file %s\n", h[i].s_name, h[i].f_name, h[i].ID, name);

    }
    fclose(output); // close
    return 0;
}
int getRawData(struct student *records)
{
    int i;
    int nmemb; // amount of structs
    char name[20];
    printf("Name of the file to be opened: \n");
    scanf("%s", name);
    FILE *outtput = fopen(name, "r");
    int ch=0;
    int lines=0; 

    if (outtput == NULL);
        return 0;

    lines++;
    while(!feof(outtput))  
    {
        ch = fgetc(outtput);
        if(ch == '\n')
        {
            lines++;
        }
    }
    nmemb = lines / 7;
    for(i = 0; i < nmemb; i++) {
        fscanf(outtput, "%s %s %s", records[i].f_name, records[i].s_name, records[i].ID);
        for(int j = 0; j < MAXROUNDS; j++)
        {

            fscanf(outtput, "%d\n", &records[i].points[j]);
        }
    }
    printf("%d", lines);
    return i;
}

所以我的目标是从文件中获取数据并将其写在struct array中存储的任何内容中。我会感激一些帮助,因为我已经花了太长时间研究这个问题。

c arrays file struct
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.