C Data file (TXT) into struct data

Hello, I'm in C since 6 month or so. I would like to get data from a TXT File (in the same folder as the project). And put this data to my structure "Fdata". But when I run my current program i don't get any data. The printf output is (" is level 0 and curently has 0 lives.")

data.txt

22

3

Ayly

----------------------------------------

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

​

typedef struct Fdata Fdata;

​

struct Fdata

{

int lives;

int level;

char playerN[100];

};

​

void filedata()

{

char line[100];

int x=1;

Fdata getdata;

FILE *fp;

fp=fopen("/Users/ayly/Documents/Code/C/Reader/Reader/data.txt", "r");

if ((fp = fopen("/Users/ayly/Documents/Code/C/Reader/Reader/data.txt", "r"))==NULL)

{

printf("Error ! Coudn't open the file");

}

while (fgets(line,sizeof line, fp) !=NULL)

{

fgets(line, 100, fp);

switch (x) {

case 1:

getdata.level = atoi(line);

break;

case 2:

getdata.lives = atoi(line);

break;

case 3:

strcpy(getdata.playerN, line);

break;

}

}

fclose(fp);

}

​

int main()

{

filedata();

Fdata filedata;

printf("%s is leves %d and curently has %d lives.", filedata.playerN, filedata.level, filedata.lives);

return 0;

}

Posted Mar 12, 2020, 6:27 AM UTC

24
Loading comments…