-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathCsvUtils.cpp
55 lines (49 loc) · 1.63 KB
/
CsvUtils.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/// Copyright (C) 2020-2023 Huawei Technologies Co., Ltd.
///
/// This file is part of Cooddy, distributed under the GNU GPL version 3 with a Linking Exception.
/// For full terms see https://github.com/program-analysis-team/cooddy/blob/master/LICENSE.md
#include <utils/CsvUtils.h>
namespace HCXX::CsvUtils {
constexpr static char DELIMITER = ',';
constexpr static char QUOTES = '"';
void WriteValue(std::ofstream& fileStream, std::string_view value)
{
if (value.empty()) {
return;
}
auto position = value.find("\"", 0);
bool needQuotes = position != std::string::npos || value.find(DELIMITER) != std::string::npos ||
value.find("\n") != std::string::npos;
if (needQuotes) {
fileStream << QUOTES;
}
if (position != std::string::npos) {
auto startPosition = 0;
while (position != std::string::npos) {
fileStream << value.substr(startPosition, position - startPosition + 1);
fileStream << QUOTES;
startPosition = position + 1;
position = value.find(QUOTES, startPosition);
}
fileStream << value.substr(startPosition, value.size() - startPosition);
} else {
fileStream << value;
}
if (needQuotes) {
fileStream << QUOTES;
}
}
void WriteRow(std::ofstream& fileStream, std::initializer_list<const std::string_view> values)
{
bool first = true;
for (auto& value : values) {
if (first) {
first = false;
} else {
fileStream << DELIMITER;
}
WriteValue(fileStream, value);
}
fileStream << "\n";
}
} // namespace HCXX::CsvUtils