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

后端 未结 10 1831
耶瑟儿~
耶瑟儿~ 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: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;
    }
    

提交回复
热议问题