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

后端 未结 4 1782
无人共我
无人共我 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条回答
  •  猫巷女王i
    2020-12-01 11:24

    In C++ (and you added the C++ tag) you can write a function accepting an arbitrary input/output stream. Since std::stringstream or std::ofstream are derived classes you can pass both of them equally into this function. An example:

    #include  // for std::cout
    #include  // for std::ofstream
    #include  // for std::stringstream
    
    void write_something(std::ostream& stream) {
      stream << "Hello World!" << std::endl;
    }
    
    int main() {
      write_something(std::cout); // write it to the screen
      {
        std::ofstream file("myfile.txt");
        write_something(file); // write it into myfile.txt
      }
      {
        std::stringstream stream;
        write_something(stream); // write it into a string
        std::cout << stream.str() << std::endl; // and how to get its content
      }
    }
    

    And analogously with std::istream instead of std::ostream if you want to read the data:

    void read_into_buffer(std::istream& stream, char* buffer, int length) {
      stream.read(buffer, length);
    }
    
    int main() {
      char* buffer = new char[255];
    
      {
        std::ifstream file("myfile.txt");
        read_into_buffer(file, buffer, 10); // reads 10 bytes from the file
      }
      {
        std::string s("Some very long and useless message and ...");
        std::stringstream stream(s);
        read_into_buffer(stream, buffer, 10); // reads 10 bytes from the string
      }
    }
    

提交回复
热议问题