• Advertisement
Sign in to follow this  

files and arrays

This topic is 4817 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

i want to have an 2d array: map[100][100]; and a file that contains something like: 0123456789 ---------- 0 |11121102101010210210102 1 |11121102101010210210102 2 |11121102101010210210102 3 |11121102101010210210102 4 |11121102101010210210102 then i want to put that in the array... so map[0][0] == 1, map[7][0] == 2 can someone help me?

Share this post


Link to post
Share on other sites
Advertisement
this is what ive done so far..:


FILE *f;
f=fopen("maps/desert.map","r");
if (f==NULL) perror ("Error opening file desert.map");
else
{
fseek (f, 0, SEEK_END);
size=ftell (f);
bytecount = size;
fseek (f, 0, SEEK_SET);
}

int player_index = 0;//stores our position in the world array
while(i<bytecount)
{

int temp = fgetc(f)-48;//read a tile index from the file
int rows, columns;
for(rows=0; rows<15; rows++)
{
for(columns=0; columns<20; columns++)
{
map[rows][columns] = temp;
printf("%i", map[rows][columns]);
}

}
i++;

}
printf("%i", map);



but the problem is, that the printf("%i", map); dosnt display anything so i cant know if it works or not

Share this post


Link to post
Share on other sites
Well, first off, in order to save the data to the file, I would recommend that you do this:


int mapdata[100][100];
FILE *pFile;

// Fill your mapdata array with the necessary info

pFile = fopen("desert.map", "w");

fwrite(&mapdata, sizeof(int), 10000, pFile);

fclose(pFile);




That will save every cell in your array to the file. Now, when you go to load it, do this:


int mapdata[100][100];
FILE *pFile;

pFile = fopen("desertnew.map", "r");

fread(&mapdata, sizeof(int), 10000, pFile);

// Then loop through the array and print out it's contents;

for(int x = 0; x < 100; x++)
{
for(int y = 0; y < 100; y++)
{
printf("[%i][%i]: %i\n", x, y, mapdata[x][y]);
}
}

fclose(pFile);



The output of the loop will be really, really, really long with 10,000 entires, but you can format it any way you'd like. The bottom line is, your array will contain the data that you need it to.

Hope this helps!

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement