Opening a sequence of files inside a loop

C, C++, Visual C++, C++.Net Topics
Post Reply
User avatar
Kevin
Sergeant Major
Sergeant Major
Posts: 40
Joined: Sun Jul 19, 2009 7:49 pm
Location: Sydney

Opening a sequence of files inside a loop

Post by Kevin » Sun Jul 19, 2009 7:57 pm

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
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Re: Opening a sequence of files inside a loop

Post by Neo » Sun Jul 19, 2009 8:04 pm

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

Return to “C/C++ Programming”