0

编码:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <Windows.h>

HANDLE creatFile(void);
long WriteBuffer(HANDLE);
char * GetBuffer(void);

void main(void)
{
HANDLE hFile;
printf("CreateFile: ");
hFile = creatFile();
if(hFile != NULL) 
    {
    WriteBuffer(hFile);
    FlushFileBuffers(hFile);
    }
CloseHandle(hFile);
printf("\n\rDone");
getchar();
}

HANDLE creatFile(void)
{
HANDLE hFile;
LPCWSTR sFileName  = L"\\\\.\\E:";
DWORD dwDesiredAccess =  GENERIC_WRITE;
DWORD fShareMode = FILE_SHARE_WRITE | FILE_SHARE_WRITE;
DWORD fCreationDisposition = OPEN_EXISTING;
DWORD fFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;

hFile = CreateFile(sFileName, dwDesiredAccess,fShareMode,
    NULL, fCreationDisposition, fFlagsAndAttributes,
    NULL);

if (hFile == INVALID_HANDLE_VALUE)
{
    hFile = NULL;
    printf("INVALID_HANDLE_VALUE: ");

    switch (GetLastError())
                {
    case 5:
        printf("\n\r Administrative Account required to run this program\n\r");
        break;
    case 87:
        printf("\n\r Invalid Parameter in CreateFile Call \n\r");
        break;
    default:

        printf("Error %d\n",GetLastError());
        break;
    }




    return NULL;
}
else
{
    printf("Attached -> %d\n\r",hFile);
    return hFile;
}
}


long WriteBuffer(HANDLE hFile)
{
char *str = GetBuffer(); // x 64 will give us 512 (sector sized buffer) ;
DWORD bytesWritten;
long totalBytesWritten = 0;
long idx = 0;
int len = strlen(str);

for(idx = 0; idx < 100000; idx ++)
{

    if(WriteFile(hFile, str, 512  * sizeof(char), &bytesWritten, NULL))
    {

        totalBytesWritten += bytesWritten;
        printf("Sectors Written : %d\r",idx+1);
    }
    else
    {
        int le = GetLastError();
        printf("Last Error : %d\r",GetLastError());
        break;
    }
}
printf("\n\r");
printf("Bytes Written: %d\n\r", totalBytesWritten);
printf("Handle -> %d\n\r",hFile);
return totalBytesWritten;
}

char * GetBuffer(void)
{
int i = 0, idx = 0;
const char * cstr_init = "ERASED1 ";
char *buffer = (char*)malloc(512);
char word2[512];

for (idx = 0; idx < 512; idx+=8) {
    for (i = 0; i < 8; i++) {
        buffer[idx+i] = cstr_init[i];
        if(strlen(buffer) == 512) 
            break;
    }
}


return buffer;
}

问题:

  1. char * GetBuffer 中有 16 个字节的无关数据。我修改了 WriteFile,使其只写入缓冲区实际保存的 512 个(而不是 528 个)字符。
  2. 写入 16 个扇区后 - WriteFile 失败,GetLastError = 5 (Access Denied)

问题:

  1. 如何修复 WriteFile 以使其在 16 个扇区后不会失败并且...

  2. 如何修复 GetBuffer 使其实际生成 512 缓冲区而不是 528?

备注 该应用程序是 ANSI C,程序以管理员身份运行。

4

3 回答 3

1

我不能用 来说明错误WriteFile(),但是,您的字符串操作存在问题。

C 字符串是以空结尾的,也就是说,字符串文字"abc"实际上是一个字符数组,例如:{'a','b','c','\0'}所有str...()操作都依赖于这个事实。在字符串长度的任何地方都没有存储任何信息,只有它应该以 . 结尾的事实'\0'

您的GetBuffer()功能改进:

char * GetBuffer(void)
{
    int i = 0, idx = 0;
    const char * cstr_init = "ERASED1 ";
    char *buffer = malloc(513); // Space for a '\0'

    for (idx = 0; idx < 512; idx+=8) {
        for (i = 0; i < 8; i++) {
            buffer[idx+i] = cstr_init[i];
        }
    }
}

您得到了奇怪的结果,strlen()因为它查找 a'\0'并且仅在 528 字节处找到一个,在分配的 512 字节之外读取会调用未定义的行为,您可能在 513 字节处找到了一个 '\0',或者从未找到一个。

其他评论,在调用GetBuffer()你从不返回之后free()char *这是一个内存泄漏,因为它在该上下文之外被分配和丢失。此外,更好的实现GetBuffer()是:

char * GetBuffer(void)
{
    const char * cstr_init = "ERASED1 ";
    const int cstr_init_len = strlen(cstr_init);
    char * buffer = calloc(1,513); // Guaranteed zeroed
    int i;
    for (i = 0; i < 512; i+=8) {
        memcpy(buffer+i, cstr_init, cstr_init_len);
        // Or strcpy(buffer+1, cstr_init);
        // Or strcat(buffer, cstr_init); // Inefficient because each call runs from buffer[0] to find a '\0' for where to start appending
    }
    return buffer;
}
于 2013-09-05T01:29:17.433 回答
0

INT 类型只能是 0 - 65536 无符号的 2 字节数字。用 LONG (long) 替换所有 INT 类型以开始......但不确定您所处的编译器环境 - 因为此更改可能不适用

于 2013-09-05T01:24:12.493 回答
0

我无法以我希望的方式解决问题 2。但是,通过告诉 WriteFile 从 528 字节的缓冲区中写入 512 字节 - 我得到了想要的结果。至于问题1。

因为磁盘驱动器上有一个文件系统 - Windows 操作系统识别这一事实并阻止写入整个驱动器。事实上,我需要做的只是锁定驱动器,这样我就可以独占访问驱动器。

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <Windows.h>
#include <winioctl.h>

HANDLE creatFile(void);
long WriteBuffer(HANDLE);
char * GetBuffer(void);

void main(void)
    {
HANDLE hFile;
printf("CreateFile: ");
hFile = creatFile();
if(hFile != NULL) 
{
    WriteBuffer(hFile);
    FlushFileBuffers(hFile);
}
CloseHandle(hFile);
printf("\n\rDone");
getchar();
}

HANDLE creatFile(void)
{
HANDLE hFile;
LPCWSTR sFileName  = L"\\\\.\\E:";
DWORD dwDesiredAccess =  GENERIC_WRITE;
DWORD fShareMode = FILE_SHARE_WRITE | FILE_SHARE_WRITE;
DWORD fCreationDisposition = OPEN_EXISTING;
DWORD fFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
BOOL bResult = FALSE;                 // results flag
LPDWORD lpBytesReturned = 0;

hFile = CreateFile(sFileName, dwDesiredAccess,fShareMode,
    NULL, fCreationDisposition, fFlagsAndAttributes,
    NULL);

if (hFile == INVALID_HANDLE_VALUE)
{
    hFile = NULL;
    printf("INVALID_HANDLE_VALUE: ");

    switch (GetLastError())
    {
    case 5:
        printf("\n\r Administrative Account required to run this program\n\r");
        break;
    case 87:
        printf("\n\r Invalid Parameter in CreateFile Call \n\r");
        break;
    default:

        printf("Error %d\n",GetLastError());
        break;
    }




return NULL;
}
else
{
    printf("Attached -> %d\n\r",hFile);
// HERE I JUST ADD THE FSCTL_LOCK_VOLUME command to stop Windows preventing me from writing to the drive        
    bResult = DeviceIoControl(hFile,                       // device to be queried
        FSCTL_LOCK_VOLUME,   // dwIoControlCode
        NULL, 0,                       // no input buffer
        NULL, 0,            // output buffer
        lpBytesReturned,                         // # bytes returned
        (LPOVERLAPPED) NULL);          // synchronous I/O

    return hFile;
}
}


long WriteBuffer(HANDLE hFile)
{
char *str = GetBuffer(); // x 64 will give us 512 (sector sized buffer) ;
DWORD bytesWritten;
long totalBytesWritten = 0;
long idx = 0;
int len = strlen(str);

for(idx = 0; idx < 100000; idx ++)
{

    if(WriteFile(hFile, str, 512  * sizeof(char), &bytesWritten, NULL))
    {

        totalBytesWritten += bytesWritten;
        printf("Sectors Written : %d\r",idx+1);
    }
    else
    {
        int le = GetLastError();
        printf("\n\rLast Error : %d\r",GetLastError());
        break;
    }
}
printf("\n\r");
printf("Bytes Written: %d\n\r", totalBytesWritten);
printf("Handle -> %d\n\r",hFile);
return totalBytesWritten;
}

char * GetBuffer(void)
{
const char * cstr_init = "ERASED2 ";
const int cstr_init_len = strlen(cstr_init);
char *buffer = (char*)malloc(513);
int i;
for (i = 0; i < 512; i+=8) {
    memcpy(buffer+i, cstr_init, cstr_init_len);
    // Or strcpy(buffer+1, cstr_init);
    // Or strcat(buffer, cstr_init); // Inefficient because each call runs from buffer[0] to find a '\0' for where to start appending
}
return buffer;
}

因此,为了将来参考,如果您希望直接写入驱动器,请务必先锁定卷。我知道上述代码中存在内存泄漏 - 但作为将数据写入驱动器的学习练习,我并不担心。代码将被整理并制成.dll

于 2013-09-05T18:47:46.527 回答