C++读写CSV文件 (二)

2014-11-23 23:55:32 · 作者: · 浏览: 9
_NONE;
}


const int CXCFileStream::WriteCsvData(LPCTSTR lpszFilename, const vector > &vlStr)
{
/// 1、判断是否是CSV文件
if (! IsCsvFile(lpszFilename))
return XC_ERR_INVALID_FILE_NAME;
/// 2、打开CSV文件
ofstream _streamToFile(lpszFilename);
/// 判断打开文件是否成功
if (NULL == _streamToFile)
return (-errno);
/// 本地变量
static TCHAR chQuote = '"';
static TCHAR chComma = ',';
/// Loop through each list of string in vector
for (vector >::const_iterator vIt = vlStr.begin(); vIt != vlStr.end(); vIt ++) {
/// Loop through each string in list
for (list::const_iterator lIt = vIt->begin(); lIt != vIt->end(); lIt ++) {
/// Separate this value from previous
if (vIt->begin() != lIt)
_streamToFile.put(chComma);
/// 考虑string中可能有,或"的情况,这就要特殊包装。
bool bComma = (lIt->find(chComma) != lIt->npos);
bool bQuote = (lIt->find(chQuote) != lIt->npos);
/// 真的含有,或"的情况
if (bComma || bQuote) {
_streamToFile.put(chQuote);


if (bQuote) {
for (string::const_iterator chIt = lIt->begin(); chIt != lIt->end(); chIt ++ ) {
// Pairs of quotes interpreted as single quote
if (chQuote == *chIt)
_streamToFile.put(chQuote);


_streamToFile.put(*chIt);
}
}
else
_streamToFile << *lIt;


_streamToFile.put(chQuote);
}
else
_streamToFile << *lIt;
}
/// 换行
_streamToFile << endl;
}
///
return XC_ERR_NONE;
}

如果朋友你有更好的建议或这里有问题,请根据blog抬头我的联系方式跟我取得联系,感谢你的支持和帮助。