c++ - C++ 中用于字节 block 随机读/写的基本文件 I/O

标签 c++ file file-io stream binary

我正在将一个低级文件 I/O 库从 Java 移植到 C++,我需要一些有关 C++ 中基本文件 I/O 的帮助。当前 API 如下所示:

public class BinaryFile {

    // open/close the file stream
    public BinaryFile(string path, string mode)
    public void Close()

    // append to the end of file
    public void AppendBytes(byte[] bytes, uint readPos, uint length)

    // write a certain byte chunk at a certain position into the file
    public void WriteBytes(byte[] bytes, uint readPos, uint length, uint writePos)

    // read a certain byte chunk from the file
    public byte[] ReadBytes(uint position, uint length)
}

首先,我已经了解了在 C/C++ 中访问文件/文件流的所有 5 种不同方式,我真的不关心我使用哪种方法(fread 和 friend 们可能没问题)。如您所见,我需要从文件的任何部分随机读取/写入二进制 block ,因此 fgets不太合适,因为它写了一个长度前缀。

但是,由于我对 C++ 有点陌生,是否有已经具有类似 API 的库或头文件? (请不要使用像 boost 这样的整体框架)简而言之,我只需要读取、写入二进制 block 并将其附加到二进制文件中。没有汗水,没有字符串,没有 JSON,没有 XML,没有什么复杂的。在 VC++ 2010 中实现此目的的最简单方法是什么?我有 Visual Studio 2010。

编辑:我的目标是 Windows XP+ 并构建一个 DLL,我已经包含了 <stdlib.h> , <stdio.h><windows.h>#define WIN32_LEAN_AND_MEAN .

最佳答案

您可以使用 FILE* APIs from <cstdio> :

#include <cstdio>

struct foo {
    unsigned int a;
    unsigned int b;
};

int main(void)
{
    // connect to the file
    FILE *f = fopen("test.bin", "wb");
    if (!f)
        return 1;

    // use "unbuffered mode" since you are doing random access
    setbuf(f, NULL );

    // declare an array of 2 objects
    struct foo data[] = { 
        { .a = 0xDEADBEEF, .b = 0x2B84F00D },
        { .a = 0xCAFEBABE, .b = 0xBAADB0B1 },
    };  

    // write the data
    fwrite(&data, sizeof(struct foo), 2, f); 

    // move to byte 0x20
    fseek(f, 0x20, SEEK_SET);

    // write an ASCII string
    fprintf(f, "ASCII TOO");

    // disconnect from the file
    fclose(f);

    return 0;
}

test.bin 的十六进制转储:

00000000  ef be ad de 0d f0 84 2b  be ba fe ca b1 b0 ad ba  |.......+........|
00000010  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000020  41 53 43 49 49 20 54 4f  4f                       |ASCII TOO|
00000029

关于c++ - C++ 中用于字节 block 随机读/写的基本文件 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33670947/

相关文章:

c++ - 书籍索引,如何查看每个单词并根据其首字母存储

c - 文件到字符串数组(逐行)

c - 将缓冲区的N个字节写入文件

java - 删除使用 FileOutputStream 创建的文件

c++ - 错误 : ‘memset’ was not declared in this scope

c++ - XDrawString 在 Solaris 上不工作

c++ - 在单独的控制台窗口中打开应用程序

c - 自制fstat获取文件大小,总是返回0长度

Java:具有编码和缓冲区大小的PrintWriter

c++ - 如何将控制台指定为要用 ostream 写入的文件?