Opening files in a loop

Hello all,
That's my first post in here so I'm not sure if I'm gonna be very clear. I hope I will.
In C, I need to open a variable number of files stored in nFiles in a loop so I can write a piece of text in each file and keep appending text to them. So, basically, I need to reopen the files every time until I'm done appending text to them. The problem is that it works for the first file, but when the first loop is done, the second loop crashes when executing the line of fopen. I don't know the reason why.

The code fragment is here:

1
2
3
4
5
6
7
8
9
for ( inxFile = 1 ; inxFile < nFiles ; inxFile++ )
{
	itoa( inxFile , tempName , 10 ) ;
	strcpy( fileName , "frag" ) ;
	strcat( fileName , tempName ) ;
         pFile = fopen( nomeFrag , "a+t" ) ;
         // fprintf stuff //
	fclose( pFile ) ;
}


What seems to be the error? I think it's something to do with the reuse of the pointer pFile, but i don't know how to fix that...

Thanks a lot.
Last edited on
Lines 3-5 can be replaced with:
sprintf(fileName, "frag%i", inxFile);

http://www.cplusplus.com/reference/clibrary/cstdio/sprintf.html

itoa isn't in the C++ standard. strcpy and strcat aren't length safe and are prone to buffer overflows.

After fclose( pFile ) ; it wouldn't hurt to have pFile = 0;

You are also not verifying that fopen() isn't returning null.




Last edited on
1
2
3
4
5
6
7
8
9
10
11
for ( inxFile = 1 ; inxFile < nFiles ; inxFile++ )
{
	sprintf(fileName, "frag%i", inxFile);
                pFile = fopen( nomeFrag , "a+t" ) ;
                if ( pFile == NULL )
                {
                     exit(1) ;
                 }
                 // fprintf stuff //
	fclose( pFile ) ;
}


It still doesn't work. I inserted some printf to check what's going on and it's still the same thing: it opens the first file, does all the fprintf stuff that i need it to do, but when it comes to open the second file it crashes again.

Thanks a lot Zaita, but any idea what could be happening?
how is fileName declared? do you have enough memory allocated for it?
char fileName[ 20 ] ;
Topic archived. No new replies allowed.