How to check if a file has been opened by another application in C++?

后端 未结 10 1792
耶瑟儿~
耶瑟儿~ 2020-12-02 01:55

I know, that there\'s the is_open() function in C++, but I want one program to check if a file hasn\'t been opened by another application. Is there any way to d

相关标签:
10条回答
  • 2020-12-02 02:13

    In Windows this little and dirty trick will work (if the file exists and you have the right permissions)

      if (  0 != rename("c:/foo.txt", "c:/foo.txt")  ) {
         printf("already opened\n");
      }
    

    It's likely to work also in Linux.

    0 讨论(0)
  • 2020-12-02 02:16

    Not only the standard library does not have this funcionality, it's not even possible in general. You could (on linux) check /proc/*/fd — but it is possible that your program does not have permission to do it on processes from other users (this is the default in Ubuntu, for instance).

    0 讨论(0)
  • 2020-12-02 02:18

    No, the standard library has no such functionality.

    0 讨论(0)
  • 2020-12-02 02:22

    The following code may work.

    int main(int argc, char ** argv)
    {
        int fd = open(argv[1], O_RDONLY);
        if (fd < 0) {
            perror("open");
            return 1;
        }
    
        if (fcntl(fd, F_SETLEASE, F_WRLCK) && EAGAIN == errno) {
            puts("file has been opened");
        }
        else {
            fcntl(fd, F_SETLEASE, F_UNLCK);
            puts("file has not been opened");
        }
    
        close(fd);
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-02 02:26

    Perhaps you could just try and get a full write lock? It'll fail if anyone else has it open for reading or writing.

    fopen("myfile.txt", "r+")
    

    If it's not cross platform and is Win32, then you can request even more fine-grained set of locks.

    See here and look at dwShareMode, value of 0, as well as the other parameters.

    0 讨论(0)
  • 2020-12-02 02:27

    Nope. Unless other application uses advisory locks.

    See http://docs.sun.com/app/docs/doc/816-0213/6m6ne37v5?a=view

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