Link to home
Create AccountLog in
Avatar of Ocrana

asked on

c++ - check file in use


anybody know a function where I can check whether the selected file is in use by another app/function? For Win2000 up to Win 7?

Avatar of Deepu Abraham
Deepu Abraham
Flag of United States of America image

File open will fail if some other application is using it.

Is this what you want? Or do you want to know the parent process using this file? Like what you see in FILEMON by sysinternels.

Best Regards,
Avatar of phoffric

I modified the example in the fopen link you provided so that it reads a file, and does not exit immediately. I ran the program and then a second time before the first program closed the file. The second run did not fail to open the file. Could you tell me what you did to make the fopen fail?
/* fopen example */
#include <stdio.h>
int main ()
  FILE * pFile;
  char buf[100];

  pFile = fopen ("myfile.txt","r");
  if (pFile!=NULL)
	  fgets(buf, 100, pFile);
	  printf("File Contents: %s\nhit enter to close file\n", buf);
	  fclose (pFile);
  else {
	  printf("FAIL TO OPEN - hit enter to exit\n");
  return 0;

Open in new window

Avatar of Ocrana


ok, file open is a choice, but what if the file is 4.7 GB big (DVD ISO)? Will this work, too?
Is it possible that fopen will destroy a file cause it is not readable or to big?

Avatar of jkr
Flag of Germany image

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
It depends very much want you actually want to know:
   - if there is any open handle to that file or
   - if you can read the file or
   - if you can write the file

The most difficult to answer is the first case.
The other ones depend on the dwShareMode the previous handles were opened with for that file and the action you need on the file:
    "If this parameter is zero and CreateFile succeeds, the file or device cannot be shared and cannot be opened again until the handle to the file or device is closed."  - copied from the link above

So... what you really need to know about that file?
Avatar of Ocrana


We have to know whether teh file is in use. We have a analyze module and a burning module. IF the ISO is opened by the analayze tool, the burn will fail. We want to avoid a failure error, and so build a queue and check regular whether the file is still in use or not.
'If the above call to 'CreateFile()' succeeds, the file is definitely not in use, not even opened as 'shared' by another process.
Avatar of Ocrana