简体   繁体   English

C ++解析文件的最快方法

[英]C++ Fastest way to parse through a file

I have a file which I have opened using: 我有一个使用以下文件打开的文件:

ifstream ifile(FilePath) 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). 该文件包含10行数据,每行包含均匀递增数量的逗号分隔值(如金字塔)。 So first line has 1 value, second line has 2 values and so on.... 所以第一行有1个值,第二行有2个值,依此类推...

I wanted to do the following, all within one function (whilst traversing the file char array just the once): 我想在一个函数中进行以下操作(仅一次遍历文件char数组):

-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). 我更喜欢使用静态分配的数组,但是问题是执行步骤1(计算有多少个换行符)后,我才知道数组的大小。 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) 对此的重点是编写快速代码(因此不关心OO友好)

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 d,e,f,g,h

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

From this file I would want to achieve: 从这个文件中,我想实现:

  • Knowledge that there are 4 lines in the file 知道文件中有4行
  • 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: 如果要使用ifstream一次读取文件,可以执行以下操作:

std::ifstream in("myfile");

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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