-
Notifications
You must be signed in to change notification settings - Fork 0
/
format.cpp
106 lines (92 loc) · 2.6 KB
/
format.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <fstream>
#include <iostream>
#include <sstream>
#include <stack>
#include <string>
using namespace std;
void FormatFile(const std::string &filename) {
std::ifstream inFile(filename);
if (!inFile) {
std::cerr << "Error opening file.\n";
return;
}
std::string content((std::istreambuf_iterator<char>(inFile)),
std::istreambuf_iterator<char>());
inFile.close();
int indentLevel = 0;
std::string formatted = "";
std::stack<char> brackets;
bool isNewLine = false;
for (char c : content) {
if (c == '{') {
indentLevel++;
formatted += "{\n" + std::string(indentLevel * 4, ' ');
brackets.push(c);
isNewLine = true;
} else if (c == '}') {
if (!brackets.empty()) {
brackets.pop();
indentLevel--;
}
if (!isNewLine) {
formatted += "\n" + std::string(indentLevel * 4, ' ');
}
formatted += "}\n" + std::string(indentLevel * 4, ' ');
isNewLine = true;
} else if (c == ',') {
formatted += ", ";
isNewLine = false;
} else {
formatted += c;
isNewLine = false;
}
}
// Write the formatted content back to the file
std::ofstream outFile(filename);
if (!outFile) {
std::cerr << "Error opening file for write.\n";
return;
}
outFile << formatted;
outFile.close();
}
void formatFile(const std::string &filename) {
std::ifstream inFile(filename);
if (!inFile) {
std::cerr << "Unable to open file: " << filename << std::endl;
return;
}
std::ostringstream formatted;
std::string line;
while (std::getline(inFile, line)) {
bool isBlank = true;
for (char ch : line) {
if (!std::isspace(ch)) {
isBlank = false;
break;
}
}
if (!isBlank) {
formatted << line << '\n';
}
}
inFile.close();
// Re-open the file in output mode to overwrite it
std::ofstream outFile(filename);
if (!outFile) {
std::cerr << "Unable to open file for writing: " << filename
<< std::endl;
return;
}
// Write the formatted content to the file
outFile << formatted.str();
outFile.close();
}
void Format(const std::string &filename) {
FormatFile(filename); // replace with your file name
formatFile(filename); // replace with your file name
}
int main() {
Format("test1.koopa");
return 0;
}