SetFilePointer without FILE_FLAG_NO_BUFFERING

2019-06-14 05:16发布

问题:

Consider this program:

#include <stdio.h>
#include <windows.h>
int main(int argc, char** argv) {
  if (argc != 2)
    return 1;
  HANDLE j = CreateFile("\\\\.\\F:", FILE_GENERIC_READ, FILE_SHARE_WRITE,
    NULL, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM, NULL);
  int k = SetFilePointer(j, atoi(argv[1]), NULL, FILE_BEGIN);
  printf("%d\n", k);
}

I am getting these results:

> a 512
512

> a 513
-1

> a 1024
1024

So I can only move the file pointer in multiples of the volume sector size. This is the behavior that would be expected with the FILE_FLAG_NO_BUFFERING flag. However I am not using that flag, so why am I getting these results?

回答1:

You opened direct access to a drive volume instead of a file. Reads/writes of a volume must be in even multiples of the sector size regardless of buffering. You cannot read/write partial sectors.



回答2:

From the documentation for CreateFile:

A volume contains one or more mounted file systems. Volume handles can be opened as noncached at the discretion of the particular file system, even when the noncached option is not specified in CreateFile. You should assume that all Microsoft file systems open volume handles as noncached. The restrictions on noncached I/O for files also apply to volumes.