c - 独家开卷

标签 c windows winapi stdio createfile

通过将 dwShareMode 设置为 0,我可以使用 CreateFile “独占”打开卷:

#include <windows.h>
int main() {
  HANDLE ki = CreateFile("\\\\.\\F:", GENERIC_READ | GENERIC_WRITE, 0,
    NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
}

我可以使用 fopen 以“共享模式”打开卷:

#include <stdio.h>
int main() {
  FILE* ki = fopen("\\\\.\\F:", "r+b");
}

我可以用 open 来“独占”打开一个文件:

#include <stdio.h>
#include <fcntl.h>
int main() {
  int ju = open("lima.txt", O_RDWR | O_EXCL);
  FILE* ki = fdopen(ju, "r+b");
}

但是,如果我尝试使用 open 打开卷,它将失败:

#include <stdio.h>
#include <fcntl.h>
int main() {
  int ju = open("\\\\.\\F:", O_RDWR | O_EXCL);
  FILE* ki = fdopen(ju, "r+b");
}

经过测试,无论有或没有 O_EXCL 标志都会发生这种情况。是独家卷 打开一些只能用 CreateFile 完成的东西,或者我错过了 东西?

最佳答案

根据the standard :

result is undefined if O_RDWR is applied to a FIFO

在这种情况下,卷似乎被识别为 FIFO。修复:

open("\\\\.\\F:", O_RDONLY);

或者:

open("\\\\.\\F:", O_WRONLY);

或者:

open("\\\\.\\F:", O_RDONLY | O_WRONLY);

关于c - 独家开卷,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37265683/

相关文章:

c - 在编写内核模块时,如何为字符指针分配字符串值?

c - 如何针对 linux 换行符\r\n 字符处理任何文本文件中的换行符 '\n'?

java - 在 Windows 7 上运行 Bash(.sh)

windows - UWP - 从基页 C# 继承

windows - DirectX 12 "Full Screen Exclusive Windows"是否强制以与 DWM 相同的刷新率运行?

c - 有关于形状的事件吗?

winapi - 云文件 API 中的删除在 Windows 21H1 上停止工作

c - 在 C 中打印 char[] 的一部分的最简单方法

c - 宏在 C 中如何工作?

c++ - 普通 C++ 代码如何应用于 GUI 编程?