Buffer vs getline

Hi,

I was wondering why is buffering so long in comparison of a backup with getline.

eg :

1
2
3
4
5
6
7
8
9
10
11
ifstream in;
in.open("mytest.txt", std::ios::in|std::ios::binary);
string line,c;
    while ( getline(in,line) )
    {

        c += line;

    }
cout << c;
c.clear();


vs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  std::ifstream is ("mytest.txt", std::ifstream::binary);
  if (is) {
    // get length of file:
    is.seekg (0, is.end);
    int length = is.tellg();
    is.seekg (0, is.beg);

    char * buffer = new char [length];

    std::cout << "Reading " << length << " characters... ";
    // read data as a block:
    is.read (buffer,length);

    is.close();
    cout << buffer;
    // ...buffer contains the entire file...

    delete[] buffer;


It happens that my first code is waaaay easier and twice as fast.
c is a kind of buffer here, isn't it ?
Any reason to use buffers "the right way" if it is slower ?

Thanks,

Larry
I'm pretty sure the two methods aren't equivalent. The first "cleans" the newlines.
(Although you can add a c += '\n'; to revert that).

Anyway, I'm not sure I understand your question.
Last edited on
My question is just :

why bother with the read and so on if a simple += can do the whole thing ?
why bother with the read and so on if a simple += can do the whole thing ?
The quest doesn't make sense. Do whatever you feel what's better.

There're mostly more than one way to do things...
why bother with the read and so on if a simple += can do the whole thing ?

Can do what thing exactly? That is the real question.

They're different functions used for different things. getline() stops when a certain character is found, while read() stops after a certain number of characters were read.

Try doing this with getline() -- reading binary data:
1
2
3
float f;

input_file.read(reinterpret_cast<char *> (&f), sizeof (float));


And since we're on the topic of input methods, you might be interested to learn about stream iterators:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <fstream>
#include <iostream>
#include <iterator>

int main()
{
    typedef std::istreambuf_iterator<char> iter;

    std::ifstream input_file("textfile.txt");
    iter file_begin(input_file);
    iter file_end;

    for (iter i = file_begin; i != file_end; ++i)
        std::clog << *i;
}
Thanks,

Catfish, your solution is even faster.

I cannot understand why I am not able to deal with regexes in the same string.
I open a new thread for it.

Thanks everybody,

Larry
Topic archived. No new replies allowed.