【发布时间】:2013-08-22 05:01:20
【问题描述】:
我想用 c++ 读取一个大的 CSV 文件,但是逐行读取对我来说太慢了(大约 5M 记录)。由于我不确定文件(或空格)中的分隔符,我按字符读取文件,转换为字符串,拆分所有值并通过转换后的值填充数组为双精度值。我的代码如下所示,但它无法读取 '\n' 和 ' ' 字符?请您帮助我如何阅读它们。如果有任何更快,更可靠的阅读方式。
bool readPtFast(istream *dataIn, ANNpointArray &p) // read point (false on EOF)
{
std::istream_iterator<char> begin(*dataIn), end;
std::vector<char> in(begin, end);
std::string wholeFileString(in.begin(), in.end()); // Not all chars are read!!
std::vector<std::string> split_values_string;
std::vector<double> split_values_double;
boost::split(split_values_string, wholeFileString, boost::is_any_of("\n\r,;\t "));
if (split_values_string.size()!=NRecords*NDims) {
cerr << "Error reading file. I expected " << NRecords*NDims << " values, but I found " << split_values_string.size() << "records.\a";
getchar();
return false;
}
std::transform(split_values_string.begin(), split_values_string.end(),
std::back_inserter(split_values_double),
boost::lexical_cast<double, std::string>);
std::copy(split_values_double.begin(),split_values_double.end(),*p);
return true;
}
【问题讨论】:
-
您可以通过使用
istreambuf_iterator<char>而不是istream_iterator<char>来丢弃大量不需要的(从外观上看)处理。前者只会折腾检查并流式传输您的字符。我们在这里谈论的文件有多大?我看到了 500 万条记录;这是否意味着 5M doubles 或 5M rows ?? -
我会使用
istream &,而不是指针。它更易于使用。