Python写入映射文件

2024-04-26 14:29:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python脚本,可以成功地将二进制数据写入文件:

iterable_array = [i + 32 for i in range(50)]
file_handle = open("a.bin", "wb")
bytes_to_write = bytearray(iterable_array)
file_handle.write(bytes_to_write)
file_handle.close()

但是,我得到以下错误:

Traceback (most recent call last):
File "python_100_chars.py", line 20, in <module>
file_handle = open("a.bin", "wb")
OSError: [Errno 22] Invalid argument: 'a.bin'

当我尝试在执行以下程序(源代码最初来自Microsoft docs)时写入,该程序创建文件映射并在按键后读取数据:

HANDLE hFile = CreateFileA( "a.bin",
                            GENERIC_READ | GENERIC_WRITE,
                            FILE_SHARE_WRITE | FILE_SHARE_READ,
                            NULL,
                            CREATE_ALWAYS,
                            FILE_ATTRIBUTE_NORMAL,
                            NULL);
HANDLE hMapFile;
LPCTSTR pBuf;
hMapFile = CreateFileMapping(
             hFile,    // use paging file
             NULL,                    // default security
             PAGE_EXECUTE_READWRITE,          // read/write access
             0,                       // maximum object size (high-order DWORD)
             BUF_SIZE,                // maximum object size (low-order DWORD)
             szName);                 // name of mapping object

if (hMapFile == NULL)
{
   _tprintf(TEXT("Could not create file mapping object (%d).\n"),
          GetLastError());
   return 1;
}
pBuf = (LPTSTR) MapViewOfFile(hMapFile,   // handle to map object
                     FILE_MAP_ALL_ACCESS, // read/write permission
                     0,
                     0,
                     BUF_SIZE);
if (pBuf == NULL)
{
   _tprintf(TEXT("Could not map view of file (%d).\n"),
          GetLastError());

    CloseHandle(hMapFile);

   return 1;
}


 _getch(); 

 printf("string inside file:%s",(char *)((void *)pBuf));
UnmapViewOfFile(pBuf);

CloseHandle(hMapFile);

我已经测试过可以用基本I/O以以下方式写入内存映射文件(并查看结果):

HANDLE hFile =  CreateFileA(         "a.bin",
                               GENERIC_WRITE,
          FILE_SHARE_WRITE | FILE_SHARE_READ,
                                        NULL,
                               OPEN_EXISTING,
                      FILE_ATTRIBUTE_NORMAL ,
                                        NULL);
char *p = "bonjour";
DWORD bw;
WriteFile(   hFile,
                 p,
                 8,
               &bw,
               NULL);
  • python脚本在做什么阻止它编写代码?你知道吗

感谢您的反馈!你知道吗


Tags: 文件tosharebinobjectnullfilewrite
1条回答
网友
1楼 · 发布于 2024-04-26 14:29:33

我没有Windows,因此无法测试其行为,但我相信这是因为Windows没有完全遵循POSIX语义,open(name, 'wb')将使用^{}打开现有文件,而不是用^{em>截断现有文件,这将与另一个进程中映射的文件冲突。ab模式也可以工作,但是。。。作为Python documentation says

'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position).

不幸的是,open函数使用C语义作为标志,因此不可能将所需的模式指定为“只打开文件进行随机访问写入而不截断文件”,因此最好的方法是“打开文件进行读写而不截断文件”,这就是r+b。你知道吗


正如用户Eryk Sun指出的,问题是如果存在任何现有内存映射,Windows根本不支持file truncation

If CreateFileMapping is called to create a file mapping object for hFile, UnmapViewOfFile must be called first to unmap all views and call CloseHandle to close the file mapping object before you can call SetEndOfFile.

同样地,没有比现有文件大的空间映射-如果映射长于文件大小,则文件将被扩展。。。你知道吗


在正确的平台上

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <time.h>
#include <unistd.h>


int main(int argc, char const *argv[])
{
    struct stat s;
    int fd = open("a.bin", O_RDWR);
    fstat(fd, &s);
    unsigned char *d = mmap(0, s.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    getchar();

    for (int i = 0; i < s.st_size; i++) {
        putchar(d[i]);
    }

    putchar('\n');
    fflush(stdout);
    getchar();
}

不会干扰上述Python程序的运行。但是,如果此C程序在窗口内访问文件,而文件被截断为0,则会在C进程中引发SIGBUS信号。你知道吗

相关问题 更多 >