0
typedef struct Data {
    int name;
    int surname;
    int phone;
} Data;

char buf[50];

void main(int argc, char *argv[]) {
    FILE *file;
    file = fopen("src.txt", "r");
    if (file == NULL) {
        printf("The file is empty or doesnt exist.\n");
        exit(-1);
    }
    fgets(buf, sizeof(buf), file);
    Data dat[100];
    int i;
    while (!feof(file)) {
        Data *d = dat + i;
        sscanf(buf, "%d %d %d", &dat->name, &dat->surname, &dat->phone);
        fgets(buf, sizeof(buf), file);
        i++;
    }
    int n = i;
    for (i = 0; i < n; i++) {
        printf("Name: %d\nSurname: %d\nPhone: %d\n", dat[i].name, dat[i].surname, 
        dat[i].phone);
    }
    fclose(file);
    exit(0);
}

I am trying to read lines of a file into a struct and then print the struct. the file looks like this:

Name Surname Phonenumber
Heinz Friedrich 015134532525
Amy Albertson 015443246678

When I try to print the struct it just shows me random numbers. I also tried to use chars but then it just says Segmentation fault (core dumped).

chqrlie
  • 131,814
  • 10
  • 121
  • 189
ffriedrich
  • 11
  • 3
  • 1
    `int name` and `int surname`? Shouldn't those be strings? – Barmar Jan 13 '22 at 09:34
  • You should check the return value of `sscanf()`. It will tell you that the input isn't numbers, so the `%d` format couldn't parse it. – Barmar Jan 13 '22 at 09:36
  • You should edit your question and provide a sample from the input file. – Károly Szabó Jan 13 '22 at 09:37
  • [Enable your warnings and read them](https://godbolt.org/z/9e6Efjazr). You probably meant to use that `d` variable. [Here's how and why](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings). – n. m. could be an AI Jan 13 '22 at 09:43

1 Answers1

2

There are two main issues:

First, you do not initialize variable i, such that Data *d = dat + i will yield undefined behaviour; use int i = 0 instead of int i;

Second, you read data format integers where the file provides strings, actually. Use %s instead of %d, in scanf as well as in printf.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58