Page 1 of 1

Opening a sequence of files inside a loop

Posted: Sun Jul 19, 2009 7:57 pm
by Kevin
Hi,

I need to open a sequence of files named as bitmapXX.bmp (where XX= 0... 99) inside a 'for' loop, access them and then close at the end of iteration.
something like below.

for (i=0; i<100; i++)
{
//open file

//access

//close
}

I tried to use strcat and itoa but I have a problem when I have generate a number with proceeding 0...for example for 1, it generates bitmap1.bmp instead of bitmap01.bmp.
Can you please help?

Kevin

Re: Opening a sequence of files inside a loop

Posted: Sun Jul 19, 2009 8:04 pm
by Neo
you can use sprintf instead as below.

char filename[50]; // to hold the filename
FILE *fp;

for (............
{
sprintf ( filename, "C:/path/bitmap%.2d.bmp", i); // %.2d will add zeros to the left and make the width exactly 2

fp = fopen (filename, "rb"); //for binary reading (ANSI C)

fread(buf, ..., ..., fp);

fclose(fp);
}

Hope this helps.

Neo