Created
June 12, 2021 09:18
-
-
Save TellowKrinkle/df80987f0c7707049539120675fd8a45 to your computer and use it in GitHub Desktop.
NS2 Reader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <vector> | |
#include <string> | |
#include <iconv.h> | |
#include <filesystem> | |
static const iconv_t iconv_toutf = iconv_open("UTF-8", "CP932"); | |
static std::string iconv_convert(const char* src, size_t len, iconv_t conv) { | |
std::string out; | |
char buffer[512]; | |
size_t res; | |
do { | |
char* bufptr = buffer; | |
size_t outlen = sizeof(buffer); | |
res = iconv(conv, const_cast<char**>(&src), &len, &bufptr, &outlen); | |
out.append(buffer, bufptr); | |
} while (res == (size_t)-1 && errno == E2BIG); | |
if (res == -1) { | |
perror("Failed string encoding conversion:"); | |
return std::string(); | |
} | |
return out; | |
} | |
static std::string toUTF8(const std::string& str) { | |
return iconv_convert(str.data(), str.size(), iconv_toutf); | |
} | |
int main(int argc, const char * argv[]) { | |
// insert code here... | |
FILE* f = fopen(argv[1], "r"); | |
uint32_t len; | |
fread(&len, 4, 1, f); | |
std::vector<std::pair<std::string, uint32_t>> files; | |
while (1) { | |
char ch = fgetc(f); | |
if (ch == 'e') { | |
break; | |
} | |
if (ch != '"') { | |
puts("Unexpected char!"); | |
return 1; | |
} | |
std::string name; | |
while ((ch = fgetc(f)) != '"') { | |
name.push_back(ch); | |
} | |
uint32_t size; | |
fread(&size, 4, 1, f); | |
files.emplace_back(toUTF8(name), size); | |
} | |
if (ftell(f) != len) { | |
printf("Unexpected end position!\n"); | |
fseek(f, len, SEEK_SET); | |
} | |
for (auto& file : files) { | |
for (char& c : file.first) { | |
if (c == '\\') { c = '/'; } | |
} | |
puts(file.first.c_str()); | |
std::filesystem::path p(file.first, std::filesystem::path::format::generic_format); | |
if (p.has_parent_path()) { | |
std::filesystem::create_directories(p.parent_path()); | |
} | |
FILE* newfile = fopen(file.first.c_str(), "w"); | |
char buf[4096]; | |
uint32_t amt = file.second; | |
while (amt) { | |
uint32_t rsize = std::min<uint32_t>(sizeof(buf), amt); | |
assert(fread(buf, rsize, 1, f) == 1); | |
assert(fwrite(buf, rsize, 1, newfile) == 1); | |
amt -= rsize; | |
} | |
fclose(newfile); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment