My question is: How do i read a string that is on multiple lines as one line of string from a file in C? I'm trying to do a binary map and my 1d array is represented as a 2d array. So this is in my "level_1.txt":
//start of file
WIDTH: 4
HEIGHT: 5
11,12,13,14,
21,22,23,24,
31,32,33,34,
41,42,43,44,
51,52,53,54,
// eof
and i would like to get the string "11,12,13,14,21,22...."
And this is my code:
int ImportMapDataFromFile(char *fileName, Map *self)
{
FILE *pFile;
char* myStr;
pFile = fopen(fileName, "r");
// Check if the file exists:
if(pFile)
{
// scanf width and height
//fscanf(pFile, "%*s %i %*s %i", &self->width, &self->height);
/*
// this doesnt work
fscanf(pFile, "%*s %i %*s %i %s", &self->width, &self->height, &myStr);
*/
//printf("%i %i", self->width, self->height);
// initialise the array
(self->theScreenMap) = (Grid*)malloc(sizeof(Grid) * self->width * self->height);
// scan the whole remaining file
/*
I dont know how to do this. I tried using fscanf and had a look at fgets
but i cant seem to make it work sorry.
*/
// tokenise it
/*
Pretty sure i have to use strtok right?
http://www.cplusplus.com/reference/cstring/strtok/
*/
// close it
fclose(pFile);
printf("%s \n", &myStr);
return TRUE;
}
else
{
fclose(pFile);
return FALSE;
}
}
What i want to do is read the file, get the size from the 1st 2 lines and use those values to create the 1d array. Then once that's done, i want to read the remaining string and assign it to the array. Eg.
theScreenMap[0] = 11; // first element has 1st token
theScreenMap[1] = 12;
theScreenMap[size - 1] = 54; // last element has last token
Thanks to anyone helping me out. But if anyone has a better way of doing this (read from file and init an array to create binary map), then feel free to tell me so. Thanks! :)