简体   繁体   中英

How to make a buffer for fstream from std::string

I wrote this code:

  ifstream f("file.txt");
  char c;
  std::string buffer;
  buffer.reserve(1024);

  bool flag = true;
  while (flag) {
    for (int i = 0; i < 1024; ++i) {
      if (f.get(c))
        buffer += c;
      else
        flag = false;
    }

    // do something with buffer

    buffer.clear();
  }

I need exactly 1 KB string buffer. Is there any better and efficient way to do this? Maybe some fstream or string functions which I don't know?

You don't need the for loop, you can use std::istream::read() instead. And if possible, replace the std::string with char[] , eg:

ifstream f("file.txt");
char buffer[1024];

while (f.read(buffer, 1024))
{
  // do something with buffer up to f.gcount() chars... 
}

If, for some reason, you actually needed a std::string , then you can do this:

ifstream f("file.txt");
std::string buffer(1024);

while (f.read(&buffer[0], 1024)) // or buffer.data() in C++17 and later
{
  buffer.resize(f.gcount());

  // do something with buffer ... 

  buffer.resize(1024);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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