Skip to content

Instantly share code, notes, and snippets.

@EAirPeter
Last active September 29, 2018 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EAirPeter/7c12d5135ca5401a6aba1934798fa535 to your computer and use it in GitHub Desktop.
Save EAirPeter/7c12d5135ca5401a6aba1934798fa535 to your computer and use it in GitHub Desktop.
Combines multiple C/C++ files into one and copy to clipboard.
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <cstdlib>
#include <exception>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <unordered_set>
using namespace std;
using namespace filesystem;
[[noreturn]] void IncorrectUsage() {
cerr << "Incorrect usage";
exit(1);
}
unordered_set<string> Once;
string Output;
bool IsAnalyzed(const path& pa) {
return Once.find(canonical(pa).string()) != Once.end();
}
void Insert(const path& pa) {
Once.emplace(canonical(pa).string());
}
void Analyze(const path& pa) {
if (IsAnalyzed(pa))
return;
ifstream fi(pa);
string line;
while (getline(fi, line)) {
if (line.find("#pragma once") == 0)
Insert(pa);
else if (line.find("#include") == 0) {
auto beg = line.find('"');
auto end = line.rfind('"');
if (beg != string::npos && end != string::npos)
Analyze(pa / ((string_view) line).substr(beg + 1, end - beg - 1));
else {
Output += line;
Output += "\r\n";
}
}
else {
Output += line;
Output += "\r\n";
}
}
}
int main(int argc, char* argv[]) {
if (argc != 2)
IncorrectUsage();
try {
Analyze(argv[1]);
if (!OpenClipboard(nullptr))
throw runtime_error("OpenClipboard");
EmptyClipboard();
auto h = GlobalAlloc(GMEM_MOVEABLE, Output.size() + 1);
if (!h) {
CloseClipboard();
throw runtime_error("GlobalAlloc");
}
auto p = GlobalLock(h);
memcpy(p, Output.c_str(), Output.size() + 1);
GlobalUnlock(h);
SetClipboardData(CF_TEXT, h);
CloseClipboard();
cout << Output << endl;
}
catch (exception& e) {
cerr << "Failed: " << e.what() << endl;
return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment