Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

c - Attempting to read file and save its content to a struct, not working

I have been trying to save register.txt contents to my main file and put it into a struct, it works until I try to print the actual struct. Somehow it doesn't go into it, like it does not save as an array, so the print I have written on the last line prints out what is on the register.txt file but the code does not save its contents as an array/struct in the main file. Any help is appreciated, thank you.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define Anvandarnamn 100
#define Register 10
#define antalval 100

typedef struct {
    char Fornamn[Anvandarnamn];
    char Efternamn[Anvandarnamn];
    int alder;
} agare;

typedef struct {
    agare user;
    char marke[Anvandarnamn];
    char typ[Anvandarnamn];
    char reg[6];
} fordon;

void Readfile(fordon bil[]) {
    FILE *txt;
    txt = fopen("Register.txt", "r"); 
    int i;
 
    for (i = 0; i < Register; i++) {
        fscanf(txt, "%s %s %s %s %d %s",
               bil[i].marke, bil[i].typ, bil[i].user.Fornamn,
               bil[i].user.Efternamn, &bil[i].user.alder, bil[i].reg);
    }
    fclose(txt);
}

int main() {
    fordon bil[Register];
    Readfile(bil);
    int raknare = 0;
    int i = 0;
    for (i = 0; i < 10; i++) {
        printf("%s %s %s %s %d %s 
",
               bil[i].marke, bil[i].typ, bil[i].user.Fornamn,
               bil[i].user.Efternamn, bil[i].user.alder, bil[i].reg);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are many reasons your code could fail: you should add some error testing.

  • test if fopen() succeeds and report failures with an explicit message that includes the filename.
  • test for fscanf() failure and report those.

Here is a modified version of ReadFile:

// pass the maximum count of records and return actual count
int Readfile(int count, fordon bil[]) {
    FILE *txt;
    int i;

    txt = fopen("Register.txt", "r");
    if (txt == NULL) {
        fprintf(stderr, "cannot open Register.txt
");
        return -1;
    }
 
    for (i = 0; i < count; i++) {
        // tell fscanf the maximum length of each string field
        if (fscanf(txt, "%99s %99s %99s %99s %d %5s",
                   bil[i].marke, bil[i].typ, bil[i].user.Fornamn,
                   bil[i].user.Efternamn, &bil[i].user.alder, bil[i].reg) != 6) {
            fprintf(stderr, "read failed for record %d
", i + 1);
            break;
        }
    }
    fclose(txt);
    return i;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...