I'm new in C programming and I am trying to open a .txt file for reading it.
I have a text file with different file names I want to read, each one in a different line. I created a function txt_to_stations() that reads this file and returns a double pointer to char, I guess it has to be a double pointer because I want to save a string of char strings. This is the function.
char** txt_to_stations(const char* txt_file) {
FILE* file;
file = fopen(txt_file, "r");
int line_count = 0;
int char_count = 0;
int len = 1;
char tmp_station[25];
char** stations = (char**)malloc(len*sizeof(char*));
char character;
while(!feof(file)) {
character = fgetc(file);
if(character != '\n') {
tmp_estation[char_count] = character;
char_count++;
}else if(character == '\n') {
stations = (char**)realloc(stations, len*sizeof(char*));
stations[line_count] = (char*)malloc(char_count*sizeof(char));
strcpy(stations[line_count], tmp_station);
len++;
line_count++;
char_count = 0;
}
}
fclose(file);
return stations;
}
My text file is this one. "stations.txt"
weatherdata-429-81.csv
weatherdata-429-84.csv
weatherdata-429-88.csv
The problem comes when I try from the main function to read this files. The function works great because if I
char** stations = txt_to_stations("stations.txt")
and then for example
printf("station1: %s\n", stations[0])
it prints weatherdata-429-81.csv
in the terminal.
But if I define a new file in main function
FILE* reading;
reading = fopen(stations[0]);
if(reading == NULL) {
printf("csv file cant be opened");
}
It prints "csv file cant be opened", which means fopen(stations[0]) == NULL
, but it does not because if I simply change stations[0] by fopen("weatherdata-429-81.csv")
it works. It may be a rookie error, but I understand that stations[0] == weatherdata-429-81.csv (as char*)
I really tried converting stations[0]
(char*) to a const char*, and also in "stations.txt" writing each name into double quotes, but anyway it did not work at all. How can I fix this?