我的问题是:如何在C语言中将跨多行的字符串作为一行字符串从文件中读取?我正在尝试做一个二进制映射,我的1D数组表示为2D数组。所以这是在我的“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
我希望获得字符串 "11,12,13,14,21,22...."。
这是我的代码:
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;
}
}
我想要做的是读取文件,从前两行中获取大小值并使用这些值创建一维数组。然后,一旦完成了这个步骤,我想要读取剩余的字符串并将其分配给数组。例如:
theScreenMap[0] = 11; // first element has 1st token
theScreenMap[1] = 12;
theScreenMap[size - 1] = 54; // last element has last token
感谢任何帮助我的人。但如果有更好的方法来完成这个任务(从文件中读取并初始化一个数组以创建二进制映射),请随时告诉我。谢谢! :)