-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvertCSVtoTXT.cpp
More file actions
70 lines (61 loc) · 1.85 KB
/
convertCSVtoTXT.cpp
File metadata and controls
70 lines (61 loc) · 1.85 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
void convertCSVtoTXT(std::string const& folderPath) {
// Loop over files of directory
for (auto const& fileCSV : std::filesystem::directory_iterator(folderPath)) {
// Select file validity and .CSV extension
if (fileCSV.is_regular_file() && fileCSV.path().extension() == ".CSV") {
// Input file name opening
std::ifstream infile(fileCSV.path());
if (!infile.is_open()) {
std::cerr << "Failed to open " << fileCSV.path() << '\n';
return;
}
// Replace extension from .csv to .txt
std::filesystem::path txtPath = fileCSV.path();
txtPath.replace_extension(".txt");
// Skip to next file if already converted
if (std::filesystem::exists(txtPath)) {
std::cout << "Skipping (already converted): " << fileCSV.path() << '\n';
continue;
}
// Create output .txt file
std::ofstream outFile(txtPath);
if (!outFile.is_open()) {
std::cerr << "Failed to create " << txtPath << '\n';
return;
}
// Read input file lines
std::string line;
int row{};
while (std::getline(infile, line)) {
// Defining loop variables
std::stringstream ss(line);
std::string item;
bool first = true;
// Loop over columns
while (std::getline(ss, item, ';')) {
if (!first) {
outFile << '\t';
}
outFile << item;
first = false;
}
outFile << '\n';
++row;
if (row > 65000) {
continue;
}
}
outFile.close();
// Status
std::cout << "Converted: " << fileCSV.path() << " -> " << txtPath << '\n';
}
}
}
int main() {
convertCSVtoTXT("/mnt/c/Users/Simone/Desktop/DATA - Copia (2) - Copia");
return EXIT_SUCCESS;
}