can i use the same handle over again in a loop?..
HANDLE fhandle;
HANDLE fhandleMap

int *Mem = NULL;

for (loop 7 times)
{
fhandle = CreateFile(file, GENERIC_READ, ...);
fhandleMap = CreateFileMapping(fhandle, ...);
.
.
Mem = ...;
... // do various things
}

if (fhandleMap)
{CloseHandle(fhandleMap);}
if (fhandle)
{CloseHandle(fhandle);}

Recommended Answers

All 6 Replies

Yes.

Consider this:

HANDLE fHandle;

for( int i = 0; i < 7; ++i )
{
   fHandle = CreateFile( ... );
}

close( fHandle );

First time CreateFile is called, let's assume that fHandle will be set to 0x00000001. The next time it's set to 0x00000002, until 0x0000007.

After the loop, you're closing only the last handle (0x00000007), what happens to the other 6?
(They will be closed by Windows automatically when your program terminates, but it is very bad practice to leave them open.
So close the file handle when you're done with it, inside the for loop.

(In future please use code tags).

how about this?.

int n = 7;
HANDLE *fhndl = (HANDLE*)malloc(n);
for( int i = 0; i < n; ++i )
  fhndl[i] = CreateFile( ... );
for( int i = 0; i < n; ++i )
   //use fhndl[i]
for( int i = 0; i < n; ++i )
 close( fhndl[i]);
delete [] fhndl
fhndl = NULL;
HANDLE *fhndl = (HANDLE*)malloc(n);
delete [] fhndl

What is wrong here? (apart from the missing ; behind fhndl)

i see. is it ok to create array of handles like this?.

int n = 7;
HANDLE *fhndl = (HANDLE*)malloc(n);
for( int i = 0; i < n; ++i )
  fhndl[i] = CreateFile( ... );
for( int i = 0; i < n; ++i )
   //use fhndl[i]
for( int i = 0; i < n; ++i )
 close( fhndl[i]);
free(fhndl);
fhndl = NULL;

It will now work, but in C++ it's not advised to use malloc/free. It's better to use new and delete.

(Of course you should also check the return value of CreateFile before using the file handles in the second loop)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.