简体   繁体   中英

C++ Fastest way to parse through a file

I have a file which I have opened using:

ifstream ifile(FilePath)

The file contains, say 10 lines of data and each line contains an evenly-incrementing number of comma separated values (like a pyramid). So first line has 1 value, second line has 2 values and so on....

I wanted to do the following, all within one function (whilst traversing the file char array just the once):

-Every time I encounter a newline character, I can increment a parameter passed in by value (which, when the function exits, I have the number of lines in the file).

-I also wanted to store each line of the file in an array. What would be the best way to "glue" together all the characters between newline characters?

I'd prefer to use statically-allocated arrays, but the problem is I only know the size of the array once I have performed step 1 (counting how many new line characters there are). Would it be quicker to perform a double-parse for this (one parse to count how many lines, then use that value to allocate a static array) or single parse, but insert into a dynamic array?

The emphasis on this is to write fast code (so not being OO-friendly is not a concern)

Apologies if I am asking a lot, hopefully you can see I have given this some thought.

EDIT, example file:

a

b,c

d,e,f,g,h

j,k,l,m,n,o,p

From this file I would want to achieve:

  • Knowledge that there are 4 lines in the file
  • A non-dynamic array containing each line
  • The number of elements in the second line

There are plenty of examples in existing posts on how to do this.

if you want to use ifstream to read in the file once, you can do something like this:

std::ifstream in("myfile");

std::stringstream buffer;
buffer << in.rdbuf();

std::string contents(buffer.str());

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