繁体   English   中英

如何在C ++中使用mmap将整数数组正确写入文件

[英]How can I write array of integers properly to file by using mmap in c++

我目前正在尝试使用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的值?

阅读更多内容后,我认为一个核心问题是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的名称很容易引起误解。 该代码似乎只能从中读取。 arrayToWriteIn是源还是目标?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM