ZwReadFile函数读出来的是乱码的解决方案

本文作者:邱朋飞

在用ZwReadFile内核函数读取文件时,读取出的一直是乱码,这里记录一下我的代码中的问题。

原因:之前没有使用过ZwReadFile函数,所以用的时候是参考网上的代码写的,但是有些代码将该函数的倒数第二个参数ByteOffset设置成了NULL,该参数是要读取的偏移位置,也就是从这个位置开始读,如果设置为NULL的话,ZwReadFile可能不知道从哪个地方开始读文件中的内容,所以读出来的可能就是乱码了。

解决方法:

参考微软对ZwReadFile函数中的ByteOffset的介绍,我们可以定义一个变量LARGE_INTEGER ,假如定义的变量为ByteOffset,然后我们将其设置为0,ByteOffset.QuadPart = 0,然后将ByteOffset作为参数传递给ZwReadFile函数,ZwReadFile函数就会从头开始读文件了。

以下是微软对ZwReadFile函数的介绍的页面:

https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ntifs/nf-ntifs-ntreadfile?redirectedfrom=MSDN

对ByteOffset的介绍如下:

ByteOffset

Pointer to a variable that specifies the starting byte offset in the file where the read operation will begin. If an attempt is made to read beyond the end of the file, NtReadFile returns an error.

If the call to NtCreateFile set either of the CreateOptions flags FILE_SYNCHRONOUS_IO_ALERT or FILE_SYNCHRONOUS_IO_NONALERT, the I/O Manager maintains the current file position. If so, the caller of NtReadFile can specify that the current file position offset be used instead of an explicit ByteOffset value. This specification can be made by using one of the following methods:

  • Specify a pointer to a LARGE_INTEGER value with the HighPart member set to -1 and the LowPart member set to the system-defined value FILE_USE_FILE_POINTER_POSITION.
  • Pass a NULL pointer for ByteOffset.

NtReadFile updates the current file position by adding the number of bytes read when it completes the read operation, if it is using the current file position maintained by the I/O Manager.

Even when the I/O Manager is maintaining the current file position, the caller can reset this position by passing an explicit ByteOffset value to NtReadFile. Doing this automatically changes the current file position to that ByteOffset value, performs the read operation, and then updates the position according to the number of bytes actually read. This technique gives the caller atomic seek-and-read service.

你可能感兴趣的:(实用教程)