【问题标题】:How can I write array of integers properly to file by using mmap in c++如何在 c++ 中使用 mmap 将整数数组正确写入文件
【发布时间】:2013-03-04 23:44:17
【问题描述】:

我目前正在尝试使用 mmap 将整数从数组写入 .txt 文件。但是,我遇到了一个无法解决的意外问题。首先,这是我试图将整数数组写入文件的代码。

bool writeFileFromArrayByMemoryMap( int *&arrayToWriteInto, int size, char *output_file_name){ 
    int sizeForOutputFile = size * sizeof(int);
    int openedFile = open(output_file_name, O_RDWR | O_CREAT); //openning the file with the read&write permission
    lseek (openedFile, sizeForOutputFile-1, SEEK_SET);
    write (openedFile, "", 1);

    int *memoryBuffer = (int *)mmap(NULL, sizeForOutputFile, PROT_READ | PROT_WRITE, MAP_SHARED, openedFile, 0); //creating a memory mapping

    int currentIndex = 0; //the current index to put currentIntegerToPutArray to the array
    int *currentByte = memoryBuffer;
    while(currentIndex < size) {

        sprintf((char *)currentByte, "%d\n", arrayToWriteInto[currentIndex]);
        currentByte++;
        currentIndex++;
    }
    close(openedFile); //closing the file
    munmap(memoryBuffer, sizeForOutputFile); //remove the maping*/
return true;}

数组和文件的路径由调用者传递,目前大小为100。实际上,我想要写入的文件大小比 100*sizeof(int) 大得多,但为了测试我只是把它变小了。不过,我无法正确写出整数。输出文件正确写入了一些结果,但过了一会儿它没有进入新行,然后它写入所有整数而不用新行分隔它们。 这样做的原因可能在哪里?据我所知,我正确设置了文件的大小,但似乎问题可能与错误地使用文件的字节有关。

编辑:我还发现如果程序试图写入一个大于 999 的值,那么它就会崩溃。如果数组中充满了小于 1000 的值,那么正确写入是没有问题的。为什么它不能正确写入大于 999 的值?

【问题讨论】:

  • 这里发生了很多事情,所以我只想指出您可能会覆盖 \n,因为您一次只能前进四个字节。当我消化我在这里看到的内容时,我会写出更多作为答案。
  • 在我再次忘记之前,您为什么要使用 mmap 开始?做我认为你想做的事,这是一种冗长的方式。

标签: c++ file io mmap


【解决方案1】:

在阅读了更多之后,我认为一个核心问题是 sprintf 中的 %d\n。

%d 写入可变数量的字节。例如,1\n 产生 2 个字节。 315\n 产生 4。1024\n 产生 5。您的循环增量 (currentByte++) 假设每次写入四个字节。事实并非如此。

你可能想要这样的东西。

char *pc = (char*)memoryBuffer
for(int i=0;i<size;++i) {
    pc+=sprintf(pc, "%d\n", arrayToWriteInto[i]);
}

但是,您的变量名 arrayToWriteInto 具有很大的误导性。该代码似乎只能从中读取。 arrayToWriteInto 是源还是目标?

【讨论】:

  • 谢谢,它有效,但如果每次写入5个字节,它不会超过数组大小乘以整数大小(当然是4个字节)的sizeForOutputFile吗?我想,现在我需要 5*(数组大小)字节的文件,不是吗?
  • 好的。它超过了。我也修复了文件大小。
  • 好的,那么当要打印的数字是 182376 时会发生什么?或者819239801呢?我认为您可能更喜欢某种固定宽度的格式。
猜你喜欢
  • 1970-01-01
  • 2013-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多