What's a good solution to read a text file?


#1

I would like to simply read a text file and get the content as a std::string.

And I found out ofBuffer can do this.

ofBuffer buffer = ofBufferFromFile("someFile.txt"); // reading into the buffer 
std::string str = buffer.getText();

But I can’t really figure out how it works internally. Is this method fast enough to use?

Or is there a faster way to do the identical job?


#2

fast enough depends on what you are trying to do. for most cases it’s totally ok and indeed pretty optimized. you can tweak the buffer size used when reading from a file by calling:

ofFile textFile("someFile.txt")
ofBuffer buffer(textFile, blockSize);

which by default is 1024 but higher or lower values might give you better results depending on the file size and even on the drive you are reading from;

As always with optimizations the best is to always try the simplest way of doing things first and if that’s slow then try to optimize, in this case perhaps reading to a string buffer directly which would avoid 1 copy but other than that unless you use some weird file reading mode like mapped memory files or unbuffered reads i don’t think you are going to get much faster reads from a normal file read


#3

Thank you for your answer!