Make a file pointer read/write to an in-memory location

后端 未结 4 1768
无人共我
无人共我 2020-12-01 10:38

I can make a file pointer write to a file with fopen(). But can I make a file pointer that will make it so calling functions such as fputc or fprintf will write to a pointer

4条回答
  •  爱一瞬间的悲伤
    2020-12-01 11:11

    As Ise aptly points out, there is a function for this fmemopen in POSIX 2008 and that is supported on Linux. Using POSIX 2004, probably the closest thing to that would be to use a temporary file:

    // This is for illustration purposes only. You should add error checking to this.
    char name[] = "/tmp/name-of-app-XXXXXX";
    int temporary_descriptor = mkstemp(name);
    unlink(temporary_descriptor);
    FILE* file_pointer = fdopen(temporary_descriptor, "r+");
    // use file_pointer ...
    

    It's easier to do the reverse; that is, to have a function that writes into memory, and then to use that both to write into memory and also to write to a file. You can use mmap so that a chunk of memory ends up being backed by a file, and writing into that memory writes the data to the associated file.

    If you use std::istream and std::ostream instead of low-level C FILE* objects, then C++ conveniently provides std::istringstream and std::ostringstream for reading/writing strings.

    You will note that almost all of the functions in C that begin with an "f" and that operate on files, have equivalents beginning with "s" that operate on strings. A perhaps better approach would be to design an interface for I/O that is not specific to either files or strings, and then provide implementations that connect to files and strings, respectively. Then implement your core logic in terms of this interface, instead of in terms of low-level C and C++ I/O. Doing that also has the benefit of allowing for future extensions, such as supporting network files with builtin support for compression, duplication, etc.

提交回复
热议问题