parent
5757bd1504
commit
66405b1384
@ -0,0 +1,58 @@
|
|||||||
|
#include "CSVReader.h"
|
||||||
|
|
||||||
|
// 构造函数
|
||||||
|
CSVReader::CSVReader(const string& filename) : filename(filename) {
|
||||||
|
file.open(filename);
|
||||||
|
if (!file.is_open()) {
|
||||||
|
cerr << "Error: Could not open file " << filename << endl;
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 析构函数
|
||||||
|
CSVReader::~CSVReader() {
|
||||||
|
if (file.is_open()) {
|
||||||
|
file.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 按行读取CSV文件
|
||||||
|
vector<CSVRow> CSVReader::readByLine() {
|
||||||
|
vector<CSVRow> rows;
|
||||||
|
string line;
|
||||||
|
while (getline(file, line)) {
|
||||||
|
CSVRow row;
|
||||||
|
stringstream ss(line);
|
||||||
|
string cell;
|
||||||
|
while (getline(ss, cell, ',')) {
|
||||||
|
row.data.push_back(cell);
|
||||||
|
}
|
||||||
|
rows.push_back(row);
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 按块读取CSV文件
|
||||||
|
vector<CSVRow> CSVReader::readByBlock(int blockSize) {
|
||||||
|
vector<CSVRow> rows;
|
||||||
|
string line;
|
||||||
|
int count = 0;
|
||||||
|
while (getline(file, line) && count < blockSize) {
|
||||||
|
CSVRow row;
|
||||||
|
stringstream ss(line);
|
||||||
|
string cell;
|
||||||
|
while (getline(ss, cell, ',')) {
|
||||||
|
row.data.push_back(cell);
|
||||||
|
}
|
||||||
|
rows.push_back(row);
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 按字节读取CSV文件
|
||||||
|
string CSVReader::readByByte(int byteSize) {
|
||||||
|
vector<char> buffer(byteSize);
|
||||||
|
file.read(buffer.data(), byteSize);
|
||||||
|
return string(buffer.data(), byteSize);
|
||||||
|
}
|
Loading…
Reference in new issue