ファイルからバッファに読み込み、読み込んだテキストを文字列に分割して、各行が改行して改行し、新しい行にします。ブロックからファイルをブロック単位で読み込み、行単位で行を分割する
はここに私のコードです:
int ysize = 20000;
char buffer2[ysize];
int flag = 0;
string temp_str;
vector<string> temp;
while(fread(buffer2, ysize, 1, fp2)>0){
//printf("%s", buffer2);
std::string str(buffer2);
//push the data into the vect
std::string::size_type pos = 0;
std::string::size_type prev = 0;
/*means the last read did not read a full sentence*/
if (flag == 1) {
if (buffer[0] == '\n') {
//this means we have read the last senstense correctly, directly go to the next
}
else{
if((pos = str.find("\n", prev)) != std::string::npos){
temp_str+=str.substr(prev, pos - prev);
temp.push_back(temp_str);
prev = pos + 1;
}
while ((pos = str.find("\n", prev)) != std::string::npos)
{
temp.push_back(str.substr(prev, pos - prev));
prev = pos + 1;
}
// To get the last substring (or only, if delimiter is not found)
temp.push_back(str.substr(prev));
if (buffer2[19999] != '\n') {
//we did not finish readind that query
flag = 1;
temp_str = temp.back();
temp.pop_back();
}
else{
flag = 0;
}
}
}
else{
while ((pos = str.find("\n", prev)) != std::string::npos)
{
temp.push_back(str.substr(prev, pos - prev));
prev = pos + 1;
}
// To get the last substring (or only, if delimiter is not found)
temp.push_back(str.substr(prev));
if (buffer2[19999] != '\n') {
//we did not finish readind that query
flag = 1;
temp_str = temp.back();
temp.pop_back();
}
else{
flag = 0;
}}
}
問題は、これは正しくデータを読み取らないで、それはほとんどのテキストの半分を排除します。
私はここで何が欠けているのか分かりません。私の考えは、データブロックをブロック単位で読み込み、それを1行ずつに分割することです。これは、whileループでハッピングしているものです。私はフラグを使用してオーバーフローケースを処理しています。 にfread魔法のstd ::文字列str(バッファ2)は未定義の動作につながることを意味し、NULLで終了する文字列を、作成しないことを
['while(std :: getline(myFileStream、lineStr)){{}}'(http://en.cppreference.com/w/cpp/string/basic_string/getline) std :: ifstream'を実装しています。 – BoBTFish
私はそれをしましたが、パフォーマンスは恐ろしいものでした。私は、テストしたときに有意差があったが、文字列を分割することが少しジレンマであるパフォーマンスを改善するためにデータブロックを読み込もうとしている。 – user7631183
私はBoBTFishに同意するが、 'std :: regex'または' std :: stringstream'。 –