c++較好程式:讀取csv檔案
{
private:
ifstream input;
public:
trace_reader_t(string filename)
: input(filename.c_str())
{
}
/*
* Read and convert a line to a host_io_command
*
* Return true if success.
*
*/
bool read(host_io_command_t& command)
{
static uint32_t ln = 0;
typedef char_separator<char> CS;
CS delimeter(" ,\t");
string line;
if (!input.is_open())
{
INFO("trace reader error: the file was not open.");
return false;
}
bool ret = false;
while (std::getline(input, line))
{
tokenizer<CS> tok(line, delimeter);
vector<string> vec;
ln++;
vec.assign(tok.begin(), tok.end());
if (vec.size() < 3)
{
// discard this line
continue;
}
if (vec[0] == string("$read"))
{
command.type = IO_READ;
}
else if (vec[0] == string("$write"))
{
command.type = IO_WRITE;
}
else
{
// discard this line
continue;
}
command.id = ln;
command.lba = stoul(vec[1], 0, 0);
command.blk_number = stoul(vec[2], 0, 0);
ret = true;
break;
}
return ret;
}
~trace_reader_t()
{
input.close();
}
};
csv檔案的內容是:
Version=2,,,,
Operation,Address,Size,StartTime,Duration
$read,10235,23,0,0
$read,12052,15,0,0
最終的結果是將 10235給command的lba,23改command的blk,而其中的id是記錄這是第幾條命令的。
host_io_command_t的結構是:
class host_io_command_t
{
public:
uint32_t id;
io_command_type type;
uint32_t lba; // logical block address
uint32_t blk_number; // how many blocks does this command operate?
// Assumes the block size is 4096 bytes.
// defines more fileds below
// 這個的結果是使用者的資訊回車,加上這些資訊。
string& to_string(string& str)
{
str += "\n command: ";
switch (type)
{
case IO_READ: str += "IO Read"; break;
case IO_WRITE: str += "IO Write"; break;
case IO_TRIM: str += "IO Trim"; break;
case IO_FLUSH: str += "IO Flush"; break;
default: str += "<Unknown>"; break;
}
str += "\n id: " + std::to_string
str += "\n lba: " + std::to_string(lba);
str += "\n len(in block): " + std::to_string(blk_number);
return str;
}
};
io_command_type 的結構是:
enum io_command_type
{
IO_READ,
IO_WRITE,
IO_TRIM,
IO_FLUSH
};
對外提供的介面函式,或者說是使用方法是:
host_io_command_t cmd;
file_reader_t trace("./input.csv");
trace.read(cmd)
到這裡,就將input.csv檔案中的一行資料讀到cmd這個結構體裡邊去了。
while (trace.read(cmd))
可以將整個檔案的內容讀完。
這個讀取檔案的類用圖形表示如下: