cant read from file

i am writing a function for my game engine
that reads data from a file and sets it to variables
but its not setting the data from the file to the c
variable
dose anyone know why this is?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void load_btl(const char* file){//under construction
	FILE *fp = fopen(file, "r");
	char c;//a place holder for characters
	char caption[50];
	char name[30];
	char hp[3];//will convert to int later
	char lvl[3];//will convert to int later
	unsigned char i = 0;
	unsigned char data_lvl = 0;
	
	if(fp == NULL){perror("\nFailed To Load btl File\a");getchar();}
	while(fscanf(fp, "%c", &c) != EOF){
	    if (c == 10){data_lvl++;}//10 is '\n' in ASCII
		if (data_lvl == 0){c = name[i];}
		else if(data_lvl == 1){c == caption[i];}
		else if(data_lvl == 2){c == hp[i];}
		else if(data_lvl == 3){c == lvl[i];}
		i++;
	}
        printf("%c", name[0]);//prints out random value each time run
	fclose(fp);
	}


file:
tom
Hello!
66
3

the reason the file is in that format is the first line is
the name of a enemy
2nd line is a caption
3rd line is hp
4th is lvl
Last edited on
change it to:
1
2
3
4
		if (data_lvl == 0){name[i] = c;} // Note: assign c to name
		else if(data_lvl == 1){caption[i] = c;}
		else if(data_lvl == 2){hp[i] = c;}
		else if(data_lvl == 3){lvl[i] = c;}


The next problem will be the missing terminating 0 which is required for c strings
i have changed my function to what you showed but i get a segmentation fault when run!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void load_btl(const char* file){//under construction
	FILE *fp = fopen(file, "r");
	char c;//a place holder for characters
	char caption[50];
	char name[30];
	char hp[3];//will convert to int later
	char lvl[3];//will convert to int later
	unsigned char i = 0;
	unsigned char data_lvl = 0;
	
	if(fp == NULL){perror("\nFailed To Load btl File\a");getchar();}
	while(fscanf(fp, "%c", &c) != EOF){
	    if (c == 10){data_lvl++;}
		if (data_lvl == 0){name[i] = c;}
		else if(data_lvl == 1){caption[i] = c;}
		else if(data_lvl == 2){hp[i] = c;}
		else if(data_lvl == 3){lvl[i] = c;}
		i++;
	}
	fclose(fp);
	}
Last edited on
There are two possible reasons:

1. The buffer is too small (hp and lvl can contain only 3 char)
2. Missing 0 at the end of the string (as mentioned above)

One possible approach for the missing 0 is: Inititialize the strings like so
1
2
3
4
	char caption[50] = { 0 };
	char name[30] = { 0 };
	char hp[3] = { 0 };//will convert to int later
	char lvl[3] = { 0 };//will convert to int later 
Last edited on
changing hp[3] to hp[4] and lvl[3] to lvl[4]
worked thank you!
Topic archived. No new replies allowed.