Sign in to follow this  
peb

files and arrays

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this