How to check if a file is already open by another process in C?

前端 未结 8 480
感情败类
感情败类 2020-12-03 15:08

I see that standard C has no way of telling if a file is already opened in another process. So the answer should contain several examples for each platform. I need that chec

相关标签:
8条回答
  • 2020-12-03 15:44

    this can't be that hard guys.

    do this:

    try{
    File fileout = new File(path + ".xls");
    FileOutPutStream out = new FileOutPutStream(fileout);
    }
    catch(FileNotFoundException e1){
    
     // if a MS Windows process is already using the file, this exception will be thrown
    }
    catch(Exception e){
    
    }
    
    0 讨论(0)
  • 2020-12-03 15:46

    There's no way tell, unless the other process explicitly forbids access to the file. In MSVC, you'd do so with _fsopen(), specifying _SH_DENYRD for the shflag argument. The notion of being interested whether a file is opened that isn't otherwise locked is deeply flawed on a multitasking operating system. It might be opened a microsecond after you'd have found it wasn't. That's also the reason that Windows doesn't have a IsFileLocked() function.

    If you need synchronized access to files, you'll need to add this with a named mutex, use CreateMutex().

    0 讨论(0)
提交回复
热议问题