C语言 如何修复创建缓冲区并将其直接写入磁盘(WriteFile)

uidvcgyl  于 2023-03-28  发布在  其他
关注(0)|答案(3)|浏览(125)

代码:

#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个)字符。
    1.写入16个扇区后- WriteFile失败,GetLastError = 5(访问被拒绝)

问题:

1.我如何修复WriteFile,使其不会失败后16个部门和...
1.如何修复GetBuffer,使其实际生成512缓冲区而不是528?

注意事项应用程序为ANSI C,程序以admin身份运行。

8gsdolmq

8gsdolmq1#

我不能说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()结果,因为它寻找一个'\0',只找到一个在528字节,阅读512字节以外的错误调用未定义的行为,你可能会找到一个'\0'在513字节,或从来没有找到一个。
其他注解,在调用GetBuffer()之后,你永远不会返回free(),这是一个内存泄漏,因为它在上下文之外被错误定位和丢失。此外,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;
}
ghg1uchk

ghg1uchk2#

INT类型只能是一个2字节的数字从0 - 65536无符号.替换所有INT类型与长(长)开始与...不确定什么编译器环境你是虽然-因为这个变化可能不适用

jchrr9hc

jchrr9hc3#

我无法解决问题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

相关问题