dark_shadow
dark_shadow

Reputation: 13

How to input a huge txt using fread() and put it into a stringstream?

I am trying to input a huge txt file (approximately 5 MB) into a stringstream, but I face a problem to define fread(). I know, here, I have to use a string to put that string created by fread(). Here is my code, I don't know where is my mistake. I'm eagerly waiting for a solution.

FILE *f;

string buffer;
f = fopen("input.txt", "r");
fread(buffer, 1, buffer.size(), f);

stringstream s(buffer);

Upvotes: 0

Views: 1184

Answers (3)

Martin J.
Martin J.

Reputation: 5118

Assuming you don't have a good reason to not be using C++ standard I/O streams, here's how you can do it:

#include <iostream>

void process_file() {
  std::stringstream s;
  {
    std::ifstream in("input.txt");
    s << in.rdbuf();
  }
  ...
}

Then again, you might want to ask yourself why you're putting the file contents into a stringstream, rather than usfing the ifstream directly...

If for some reason you don't want to use C++ I/O streams, you can make it work C-style like this:

void process_file() {
  stringstream s;
  // your buffer is going to be allocated on the stack, so you may want to keep it relatively small
  constexpr size_t BUFFER_SIZE = 1024; 
  char buffer[BUFFER_SIZE];
  FILE *f = fopen("input.txt", "r");
  while (fread(buffer, 1, BUFFER_SIZE, f))
  {
    s<<buffer;
  }
  fclose(f);
  ... 
}

Upvotes: 1

Mux
Mux

Reputation: 348

Your code is not c++, but plain c, in c++ u can:

std::fstream f("input.txt", "r");

After that u can use f just like stringstream without any extra code

Upvotes: 0

mystic_coder
mystic_coder

Reputation: 472

I think you should use read as below , if you fall back on using fread , else c++ STL provides better way to do same thing .

FILE *f;

char buffer[1024];
std::stringstream s;
f = fopen("input.txt", "r");
while (fread(buffer, 1, 1024, f))
{
    s<<buffer;
}


std::cout<<s.str();

Upvotes: 0

Related Questions