Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
We are opening a file in a.c and we are closing it .We have another file b.c in that file we have to check whether a file is closed/notclosed in a.c.
how to know that whether it is closed or not.

a.c
----
C++
int main()
{
...
...
fp = fopen("abc.txt","rw");
fclose(fp);
..
...
}

b.c
----
if(fp == 0)
{
  printf("file closed successfully \n");
}
else
{
  printf("file not closed \n");
}

what kind of approach can be taken to solve this ?
Posted
Updated 4-Feb-13 2:06am
v3
Comments
Zoltán Zörgő 4-Feb-13 8:09am    
You can't check this precisely just with C language tools, you need operating system level support to get status of the file handles.
Marius Bancila 7-Feb-13 9:04am    
Notice that the file could be closed just the next moment after you've found the file was opened, or the other way around. Therefore make sure you're asking the right question when you code "is this file opened".

If your operating system is Microsoft Windows, you can use the platform-specific Openfile function to open the file with the "Exclusive" attribute OF_SHARE_EXCLUSIVE. You will get an error result if another process has the file open.
 
Share this answer
 
v6
Comments
Albert Holguin 5-Feb-13 2:12am    
to add... this does imply you have to use the platform specific calls (such as the WinAPI call OpenFile). +5
H.Brydon 13-Feb-13 0:53am    
Almost correct - if the file is open elsewhere you get a return code of HFILE_ERROR. No exception is thrown from OpenFile().
The solutions so far assume your b.c is compiled into a separate executable or runs on a separate thread from a.c?
Anything that involves crossing threads or process will involve platform specific API calls because threads and processes are platform specific things.

However if a.c and b.c are part of the same executable and you're only running one thread then you simply set a flag in a.c

int iOpenFlag = 0;

fp = fopen("abc.txt","rw");
iOpenFlag = 1;
fclose(fp);
iOpenFlag = 0;

then in b.c
extern int iOpenFlag; //tells the linker to look for iOpenFlag from the other c files in the link

if( iOpenFlag == 0 )
{
  //file is closed
}

Clearly error and return value checking are needed to ensure the flag is only set and cleared when it should be.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900