如何检查文件是否从另一个文件关闭? [英] How to check whether a file is closed from another file ?

查看:53
本文介绍了如何检查文件是否从另一个文件关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在用ac打开一个文件,我们正在关闭它。我们在该文件中有另一个文件bc我们必须检查文件是否关闭/未关闭ac

如何知道是否它是关闭的。



ac

----

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

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 ?

推荐答案

如果你的操作系统是Microsoft Windows,您可以使用特定于平台的 Openfile 函数来打开具有Exclusive属性的文件 OF_SHARE_EXCLUSIVE 。如果另一个进程打开了文件,你将得到一个错误结果。
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.


到目前为止,解决方案假设你的bc被编译成一个单独的可执行文件或者在一个单独的线程上运行ac?

涉及跨线程或进程的任何事情都涉及特定于平台的API调用,因为线程和进程是特定于平台的事情。



但是如果ac和bc是其中的一部分相同的可执行文件,你只运行一个线程然后你只需在交易中设置一个标志


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;



然后在b.c


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.


这篇关于如何检查文件是否从另一个文件关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆