// all_formats.cpp — C/C++ handler classes for the file formats at // fileformat.vpscoder.com, extracted from the task pages. // Each format is delimited by a marker comment: // // ===== task-NNN .EXT [C++] ===== (or [C] for a C section) // so the file is greppable per format, e.g. grep -n 'task-845'. // Generated by extract_cpp.py from the raw pages in pages/. // The Python / Java / JavaScript / HTML sections were NOT included. // Some task numbers have more than one post (e.g. /task-002/ and // /task-2/); identical code appearing twice was kept only once. // ===== task-082 .CDR [C] ===== #include #include #include #include typedef struct { char signature[5]; uint32_t chunk_size; char form_type[5]; uint16_t version; uint32_t thumbnail_width; uint32_t thumbnail_height; size_t file_size; int is_riff; } CDRProperties; typedef struct { CDRProperties props; FILE *file; } CDRParser; void init_parser(CDRParser *parser, const char *filename); void read_properties(CDRParser *parser); void write_skeleton(CDRParser *parser, const char *output_filename, uint16_t version, uint32_t tw, uint32_t th); void print_properties(CDRParser *parser); int main(int argc, char **argv) { if (argc < 2) { printf("Usage: %s [output.cdr]\n", argv[0]); return 1; } CDRParser parser = {0}; init_parser(&parser, argv[1]); read_properties(&parser); print_properties(&parser); if (argc > 2) { write_skeleton(&parser, argv[2], 500, 100, 100); } if (parser.file) fclose(parser.file); return 0; } void init_parser(CDRParser *parser, const char *filename) { parser->file = fopen(filename, "rb"); if (!parser->file) { perror("Error opening file"); exit(1); } fseek(parser->file, 0, SEEK_END); parser->props.file_size = ftell(parser->file); fseek(parser->file, 0, SEEK_SET); } void read_properties(CDRParser *parser) { uint8_t buffer[4]; size_t offset = 0; // RIFF header fread(buffer, 1, 4, parser->file); buffer[4] = 0; strcpy(parser->props.signature, (char*)buffer); offset += 4; fseek(parser->file, offset, SEEK_SET); fread(buffer, 1, 4, parser->file); memcpy(&parser->props.chunk_size, buffer, 4); offset += 4; fseek(parser->file, offset, SEEK_SET); fread(buffer, 1, 4, parser->file); buffer[4] = 0; strcpy(parser->props.form_type, (char*)buffer); offset += 4; fseek(parser->file, offset, SEEK_SET); // Find vrsn (simple loop) char chunk_id[5]; uint32_t chunk_len; while (offset < 200 && offset < parser->props.file_size) { fseek(parser->file, offset, SEEK_SET); fread(chunk_id, 1, 4, parser->file); chunk_id[4] = 0; fread(&chunk_len, 4, 1, parser->file); if (strcmp(chunk_id, "vrsn") == 0) { uint16_t ver; fseek(parser->file, offset + 8, SEEK_SET); fread(&ver, 2, 1, parser->file); parser->props.version = ver; break; } offset += 8 + chunk_len + (chunk_len % 2); } // Find DISP while (offset < 500 && offset < parser->props.file_size) { fseek(parser->file, offset, SEEK_SET); fread(chunk_id, 1, 4, parser->file); chunk_id[4] = 0; fread(&chunk_len, 4, 1, parser->file); if (strcmp(chunk_id, "DISP") == 0) { uint32_t w, h; fseek(parser->file, offset + 12, SEEK_SET); fread(&w, 4, 1, parser->file); fread(&h, 4, 1, parser->file); parser->props.thumbnail_width = w; parser->props.thumbnail_height = h; break; } offset += 8 + chunk_len + (chunk_len % 2); } parser->props.is_riff = strcmp(parser->props.signature, "RIFF") == 0; // ZIP check approximate fseek(parser->file, 0, SEEK_SET); fread(buffer, 1, 4, parser->file); if (buffer[0] == 0x50 && buffer[1] == 0x4B && buffer[2] == 0x03 && buffer[3] == 0x04) { printf("ZIP container detected.\n"); } } void write_skeleton(CDRParser *parser, const char *output_filename, uint16_t version, uint32_t tw, uint32_t th) { FILE *out = fopen(output_filename, "wb"); if (!out) { perror("Error writing file"); return; } // RIFF header fwrite("RIFF", 1, 4, out); uint32_t fsize = 36 + 1024; fwrite(&fsize, 4, 1, out); // -8 later if needed fwrite("CDR ", 1, 4, out); // vrsn fwrite("vrsn", 1, 4, out); uint32_t vlen = 2; fwrite(&vlen, 4, 1, out); fwrite(&version, 2, 1, out); fputc(0, out); // Pad // DISP stub uint8_t disp_stub[1064] = {0}; // 8+4+4+28+1024 memcpy(disp_stub + 12, &tw, 4); memcpy(disp_stub + 16, &th, 4); fwrite("DISP", 1, 4, out); uint32_t dlen = 1064; fwrite(&dlen, 4, 1, out); fwrite(disp_stub, 1, 1064, out); fputc(0, out); // Pad if odd fclose(out); printf("Basic skeleton written to %s\n", output_filename); } void print_properties(CDRParser *parser) { printf("signature: %s\n", parser->props.signature); printf("chunk_size: %u\n", parser->props.chunk_size); printf("form_type: %s\n", parser->props.form_type); printf("version: %u\n", parser->props.version); printf("thumbnail_width: %u\n", parser->props.thumbnail_width); printf("thumbnail_height: %u\n", parser->props.thumbnail_height); printf("file_size: %zu\n", parser->props.file_size); printf("is_riff: %d\n", parser->props.is_riff); } // ===== end task-082 .CDR ===== // ===== task-001 .3DS [C++] ===== #include #include #include #include #include #include struct ChunkData { std::string id; std::vector subchunks; std::map data; // Use std::any for flexibility }; class ThreeDSFile { private: ChunkData chunks; public: ThreeDSFile(const std::string& filename = "") { if (!filename.empty()) { load(filename); } } void load(const std::string& filename) { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) return; size_t size = file.tellg(); file.seekg(0, std::ios::beg); std::vector buffer(size); file.read(buffer.data(), size); chunks = parseChunk(buffer.data(), 0, size).first; } std::pair parseChunk(const char* buffer, size_t pos, size_t limit) { if (pos >= limit) return {ChunkData{}, pos}; unsigned short id; memcpy(&id, buffer + pos, 2); pos += 2; unsigned int len; memcpy(&len, buffer + pos, 4); pos += 4; size_t end = pos + len - 6; ChunkData chunk; chunk.id = "0x" + std::to_string(id); switch (id) { case 0x4D4D: chunk.data["type"] = std::string("MAIN3DS"); break; case 0x0002: { unsigned int ver; memcpy(&ver, buffer + pos, 4); pos += 4; chunk.data["version"] = ver; break; } case 0x3D3D: chunk.data["type"] = std::string("EDIT3DS"); break; case 0xB000: chunk.data["type"] = std::string("KEYF3DS"); break; case 0xAFFF: chunk.data["type"] = std::string("MATERIAL"); break; case 0xA000: { std::string name = readString(buffer, pos); pos += name.length() + 1; chunk.data["name"] = name; break; } case 0xA010: chunk.data["colorType"] = std::string("Ambient"); break; case 0xA020: chunk.data["colorType"] = std::string("Diffuse"); break; case 0xA030: chunk.data["colorType"] = std::string("Specular"); break; case 0x0010: { float rgb[3]; memcpy(rgb, buffer + pos, 12); pos += 12; chunk.data["rgbFloat"] = std::vector(rgb, rgb + 3); break; } case 0x0011: { unsigned char rgb[3]; memcpy(rgb, buffer + pos, 3); pos += 3; chunk.data["rgbByte"] = std::vector(rgb, rgb + 3); break; } case 0x4000: { std::string name = readString(buffer, pos); pos += name.length() + 1; chunk.data["objectName"] = name; break; } case 0x4100: chunk.data["type"] = std::string("TRIMESH"); break; case 0x4110: { unsigned short count; memcpy(&count, buffer + pos, 2); pos += 2; chunk.data["vertexCount"] = (unsigned int)count; std::vector> vertices; for (unsigned short i = 0; i < count; i++) { float v[3]; memcpy(v, buffer + pos, 12); pos += 12; vertices.push_back({v[0], v[1], v[2]}); } chunk.data["vertices"] = vertices; break; } case 0x4120: { unsigned short count; memcpy(&count, buffer + pos, 2); pos += 2; chunk.data["faceCount"] = (unsigned int)count; std::vector> faces; for (unsigned short i = 0; i < count; i++) { unsigned short f[4]; memcpy(f, buffer + pos, 8); pos += 8; faces.push_back({f[0], f[1], f[2], f[3]}); } chunk.data["faces"] = faces; break; } case 0x4130: { std::string name = readString(buffer, pos); pos += name.length() + 1; chunk.data["materialName"] = name; unsigned short count; memcpy(&count, buffer + pos, 2); pos += 2; chunk.data["faceCount"] = (unsigned int)count; std::vector indices; for (unsigned short i = 0; i < count; i++) { unsigned short idx; memcpy(&idx, buffer + pos, 2); pos += 2; indices.push_back(idx); } chunk.data["faceIndices"] = indices; break; } case 0x4140: { unsigned short count; memcpy(&count, buffer + pos, 2); pos += 2; chunk.data["uvCount"] = (unsigned int)count; std::vector> uvs; for (unsigned short i = 0; i < count; i++) { float uv[2]; memcpy(uv, buffer + pos, 8); pos += 8; uvs.push_back({uv[0], uv[1]}); } chunk.data["uvs"] = uvs; break; } case 0x4150: { std::vector groups; size_t num = (len - 6) / 4; for (size_t i = 0; i < num; i++) { unsigned int group; memcpy(&group, buffer + pos, 4); pos += 4; groups.push_back(group); } chunk.data["smoothingGroups"] = groups; break; } case 0x4160: { float matrix[12]; memcpy(matrix, buffer + pos, 48); pos += 48; chunk.data["matrix"] = std::vector(matrix, matrix + 12); break; } case 0x4600: { float posL[3]; memcpy(posL, buffer + pos, 12); pos += 12; chunk.data["position"] = std::vector(posL, posL + 3); break; } case 0x4700: { float posC[3]; memcpy(posC, buffer + pos, 12); pos += 12; float tar[3]; memcpy(tar, buffer + pos, 12); pos += 12; float bank; memcpy(&bank, buffer + pos, 4); pos += 4; float lens; memcpy(&lens, buffer + pos, 4); pos += 4; chunk.data["position"] = std::vector(posC, posC + 3); chunk.data["target"] = std::vector(tar, tar + 3); chunk.data["bank"] = bank; chunk.data["lens"] = lens; break; } default: { std::vector raw(buffer + pos, buffer + end); chunk.data["raw"] = raw; pos = end; break; } } while (pos < end) { auto [sub, newPos] = parseChunk(buffer, pos, limit); if (!sub.id.empty()) chunk.subchunks.push_back(sub); pos = newPos; } return {chunk, pos}; } std::string readString(const char* buffer, size_t pos) { std::string str; char c; while ((c = buffer[pos++]) != 0) str += c; return str; } void printProperties() { printRecurse(chunks, ""); } void printRecurse(const ChunkData& chunk, const std::string& indent) { std::cout << indent << "Chunk ID: " << chunk.id << std::endl; for (const auto& entry : chunk.data) { std::cout << indent << entry.first << ": "; if (entry.second.type() == typeid(std::string)) { std::cout << std::any_cast(entry.second); } else if (entry.second.type() == typeid(unsigned int)) { std::cout << std::any_cast(entry.second); } else if (entry.second.type() == typeid(float)) { std::cout << std::any_cast(entry.second); } else if (entry.second.type() == typeid(std::vector)) { auto vec = std::any_cast>(entry.second); for (float v : vec) std::cout << v << " "; } else if (entry.second.type() == typeid(std::vector)) { auto vec = std::any_cast>(entry.second); for (unsigned char v : vec) std::cout << (int)v << " "; } else if (entry.second.type() == typeid(std::vector)) { auto vec = std::any_cast>(entry.second); for (unsigned short v : vec) std::cout << v << " "; } else if (entry.second.type() == typeid(std::vector)) { auto vec = std::any_cast>(entry.second); for (unsigned int v : vec) std::cout << v << " "; } else if (entry.second.type() == typeid(std::vector>)) { auto vecs = std::any_cast>>(entry.second); for (auto& vec : vecs) { for (float v : vec) std::cout << v << " "; std::cout << "; "; } } else if (entry.second.type() == typeid(std::vector>)) { auto vecs = std::any_cast>>(entry.second); for (auto& vec : vecs) { for (unsigned short v : vec) std::cout << v << " "; std::cout << "; "; } } else if (entry.second.type() == typeid(std::vector)) { auto raw = std::any_cast>(entry.second); std::cout << "Raw data (" << raw.size() << " bytes)"; } std::cout << std::endl; } for (const auto& sub : chunk.subchunks) { printRecurse(sub, indent + " "); } } void save(const std::string& filename) { std::ofstream file(filename, std::ios::binary); if (!file) return; writeChunk(file, chunks); } void writeChunk(std::ofstream& file, const ChunkData& chunk) { unsigned short id = std::stoul(chunk.id.substr(2), nullptr, 16); std::vector dataBuffer = writeData(chunk.data, id); std::vector subBuffer; for (const auto& sub : chunk.subchunks) { std::ostringstream subOs; writeChunk(subOs, sub); std::string subStr = subOs.str(); subBuffer.insert(subBuffer.end(), subStr.begin(), subStr.end()); } unsigned int totalLen = 6 + dataBuffer.size() + subBuffer.size(); file.write(reinterpret_cast(&id), 2); file.write(reinterpret_cast(&totalLen), 4); file.write(dataBuffer.data(), dataBuffer.size()); file.write(subBuffer.data(), subBuffer.size()); } std::vector writeData(const std::map& data, unsigned short id) { std::vector buffer; if (id == 0x0002) { unsigned int ver = std::any_cast(data.at("version")); buffer.insert(buffer.end(), reinterpret_cast(&ver), reinterpret_cast(&ver) + 4); } else if (id == 0xA000) { std::string name = std::any_cast(data.at("name")); buffer.insert(buffer.end(), name.begin(), name.end()); buffer.push_back(0); } else if (id == 0x4000) { std::string name = std::any_cast(data.at("objectName")); buffer.insert(buffer.end(), name.begin(), name.end()); buffer.push_back(0); } else if (id == 0x0010) { auto rgb = std::any_cast>(data.at("rgbFloat")); for (float f : rgb) { buffer.insert(buffer.end(), reinterpret_cast(&f), reinterpret_cast(&f) + 4); } } else if (id == 0x0011) { auto rgb = std::any_cast>(data.at("rgbByte")); buffer.insert(buffer.end(), rgb.begin(), rgb.end()); } else if (id == 0x4110) { unsigned short count = static_cast(std::any_cast(data.at("vertexCount"))); buffer.insert(buffer.end(), reinterpret_cast(&count), reinterpret_cast(&count) + 2); auto verts = std::any_cast>>(data.at("vertices")); for (auto& v : verts) { for (float f : v) { buffer.insert(buffer.end(), reinterpret_cast(&f), reinterpret_cast(&f) + 4); } } } else if (id == 0x4120) { unsigned short count = static_cast(std::any_cast(data.at("faceCount"))); buffer.insert(buffer.end(), reinterpret_cast(&count), reinterpret_cast(&count) + 2); auto faces = std::any_cast>>(data.at("faces")); for (auto& f : faces) { for (unsigned short s : f) { buffer.insert(buffer.end(), reinterpret_cast(&s), reinterpret_cast(&s) + 2); } } } else if (id == 0x4130) { std::string name = std::any_cast(data.at("materialName")); buffer.insert(buffer.end(), name.begin(), name.end()); buffer.push_back(0); unsigned short count = static_cast(std::any_cast(data.at("faceCount"))); buffer.insert(buffer.end(), reinterpret_cast(&count), reinterpret_cast(&count) + 2); auto indices = std::any_cast>(data.at("faceIndices")); for (unsigned short idx : indices) { buffer.insert(buffer.end(), reinterpret_cast(&idx), reinterpret_cast(&idx) + 2); } } else if (id == 0x4140) { unsigned short count = static_cast(std::any_cast(data.at("uvCount"))); buffer.insert(buffer.end(), reinterpret_cast(&count), reinterpret_cast(&count) + 2); auto uvs = std::any_cast>>(data.at("uvs")); for (auto& uv : uvs) { for (float f : uv) { buffer.insert(buffer.end(), reinterpret_cast(&f), reinterpret_cast(&f) + 4); } } } else if (id == 0x4150) { auto groups = std::any_cast>(data.at("smoothingGroups")); for (unsigned int g : groups) { buffer.insert(buffer.end(), reinterpret_cast(&g), reinterpret_cast(&g) + 4); } } else if (id == 0x4160) { auto matrix = std::any_cast>(data.at("matrix")); for (float f : matrix) { buffer.insert(buffer.end(), reinterpret_cast(&f), reinterpret_cast(&f) + 4); } } else if (id == 0x4600) { auto pos = std::any_cast>(data.at("position")); for (float f : pos) { buffer.insert(buffer.end(), reinterpret_cast(&f), reinterpret_cast(&f) + 4); } } else if (id == 0x4700) { auto pos = std::any_cast>(data.at("position")); for (float f : pos) { buffer.insert(buffer.end(), reinterpret_cast(&f), reinterpret_cast(&f) + 4); } auto tar = std::any_cast>(data.at("target")); for (float f : tar) { buffer.insert(buffer.end(), reinterpret_cast(&f), reinterpret_cast(&f) + 4); } float bank = std::any_cast(data.at("bank")); buffer.insert(buffer.end(), reinterpret_cast(&bank), reinterpret_cast(&bank) + 4); float lens = std::any_cast(data.at("lens")); buffer.insert(buffer.end(), reinterpret_cast(&lens), reinterpret_cast(&lens) + 4); } else if (data.count("raw")) { auto raw = std::any_cast>(data.at("raw")); buffer = raw; } return buffer; } }; // ===== end task-001 .3DS ===== // ===== task-002 .3DSX [C] ===== #include #include #include #include typedef struct { char magic[5]; // Null-terminated uint16_t header_size; uint16_t reloc_header_size; uint32_t format_version; uint32_t flags; uint32_t code_segment_size; uint32_t rodata_segment_size; uint32_t data_segment_size; uint32_t bss_segment_size; uint32_t smdh_offset; uint32_t smdh_size; uint32_t romfs_offset; uint32_t code_abs_relocs; uint32_t code_rel_relocs; uint32_t rodata_abs_relocs; uint32_t rodata_rel_relocs; uint32_t data_abs_relocs; uint32_t data_rel_relocs; int has_extended; // Flag for extended header } ThreeDSXProperties; void read_3dsx(const char* filepath, ThreeDSXProperties* props) { FILE* f = fopen(filepath, "rb"); if (!f) { perror("Failed to open file"); return; } // Read header char magic[4]; fread(magic, 1, 4, f); strncpy(props->magic, magic, 4); props->magic[4] = '\0'; fread(&props->header_size, sizeof(uint16_t), 1, f); fread(&props->reloc_header_size, sizeof(uint16_t), 1, f); fread(&props->format_version, sizeof(uint32_t), 1, f); fread(&props->flags, sizeof(uint32_t), 1, f); fread(&props->code_segment_size, sizeof(uint32_t), 1, f); fread(&props->rodata_segment_size, sizeof(uint32_t), 1, f); fread(&props->data_segment_size, sizeof(uint32_t), 1, f); fread(&props->bss_segment_size, sizeof(uint32_t), 1, f); props->has_extended = (props->header_size > 32); if (props->has_extended) { fread(&props->smdh_offset, sizeof(uint32_t), 1, f); fread(&props->smdh_size, sizeof(uint32_t), 1, f); fread(&props->romfs_offset, sizeof(uint32_t), 1, f); } // Read relocation headers fread(&props->code_abs_relocs, sizeof(uint32_t), 1, f); fread(&props->code_rel_relocs, sizeof(uint32_t), 1, f); fread(&props->rodata_abs_relocs, sizeof(uint32_t), 1, f); fread(&props->rodata_rel_relocs, sizeof(uint32_t), 1, f); fread(&props->data_abs_relocs, sizeof(uint32_t), 1, f); fread(&props->data_rel_relocs, sizeof(uint32_t), 1, f); fclose(f); } void print_properties(const ThreeDSXProperties* props) { printf("Magic Identifier: %s\n", props->magic); printf("Header Size: 0x%X\n", props->header_size); printf("Relocation Header Size: 0x%X\n", props->reloc_header_size); printf("Format Version: %u\n", props->format_version); printf("Flags: 0x%X\n", props->flags); printf("Code Segment Size: 0x%X\n", props->code_segment_size); printf("Read-Only Data Segment Size: 0x%X\n", props->rodata_segment_size); printf("Data Segment Size: 0x%X\n", props->data_segment_size); printf("BSS Segment Size: 0x%X\n", props->bss_segment_size); if (props->has_extended) { printf("SMDH Offset: 0x%X\n", props->smdh_offset); printf("SMDH Size: 0x%X\n", props->smdh_size); printf("RomFS Offset: 0x%X\n", props->romfs_offset); } printf("Code Absolute Relocations: %u\n", props->code_abs_relocs); printf("Code Relative Relocations: %u\n", props->code_rel_relocs); printf("Rodata Absolute Relocations: %u\n", props->rodata_abs_relocs); printf("Rodata Relative Relocations: %u\n", props->rodata_rel_relocs); printf("Data Absolute Relocations: %u\n", props->data_abs_relocs); printf("Data Relative Relocations: %u\n", props->data_rel_relocs); } void write_3dsx(const char* output_path, const ThreeDSXProperties* props) { FILE* f = fopen(output_path, "wb"); if (!f) { perror("Failed to open output file"); return; } fwrite(props->magic, 1, 4, f); fwrite(&props->header_size, sizeof(uint16_t), 1, f); fwrite(&props->reloc_header_size, sizeof(uint16_t), 1, f); fwrite(&props->format_version, sizeof(uint32_t), 1, f); fwrite(&props->flags, sizeof(uint32_t), 1, f); fwrite(&props->code_segment_size, sizeof(uint32_t), 1, f); fwrite(&props->rodata_segment_size, sizeof(uint32_t), 1, f); fwrite(&props->data_segment_size, sizeof(uint32_t), 1, f); fwrite(&props->bss_segment_size, sizeof(uint32_t), 1, f); if (props->has_extended) { fwrite(&props->smdh_offset, sizeof(uint32_t), 1, f); fwrite(&props->smdh_size, sizeof(uint32_t), 1, f); fwrite(&props->romfs_offset, sizeof(uint32_t), 1, f); } fwrite(&props->code_abs_relocs, sizeof(uint32_t), 1, f); fwrite(&props->code_rel_relocs, sizeof(uint32_t), 1, f); fwrite(&props->rodata_abs_relocs, sizeof(uint32_t), 1, f); fwrite(&props->rodata_rel_relocs, sizeof(uint32_t), 1, f); fwrite(&props->data_abs_relocs, sizeof(uint32_t), 1, f); fwrite(&props->data_rel_relocs, sizeof(uint32_t), 1, f); fclose(f); // Additional writing of segments/reloc entries can be added as needed } // Example usage: // int main() { // ThreeDSXProperties props; // read_3dsx("example.3dsx", &props); // print_properties(&props); // write_3dsx("output.3dsx", &props); // return 0; // } // ===== end task-002 .3DSX ===== // ===== task-161 .DXF [C++] ===== #include #include #include #include #include #include class DXFHandler { private: std::string filepath; std::map properties; std::string content; public: DXFHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file." << std::endl; return; } std::string line; while (std::getline(file, line)) { content += line + "\n"; } file.close(); std::vector lines; size_t pos = 0; std::string token; while ((pos = content.find("\n")) != std::string::npos) { token = content.substr(0, pos); lines.push_back(token.erase(token.find_last_not_of("\r\n") + 1)); content.erase(0, pos + 1); } bool inHeader = false; std::string currentVar; for (size_t i = 0; i < lines.size(); ++i) { std::string trimmed = lines[i]; trimmed.erase(std::remove_if(trimmed.begin(), trimmed.end(), isspace), trimmed.end()); if (trimmed == "0" && i + 3 < lines.size() && lines[i + 3] == "HEADER") { inHeader = true; i += 3; continue; } if (inHeader && trimmed == "0" && i + 1 < lines.size() && lines[i + 1] == "ENDSEC") { break; } if (inHeader && trimmed == "9") { if (i + 1 < lines.size()) { currentVar = lines[i + 1]; currentVar.erase(std::remove_if(currentVar.begin(), currentVar.end(), isspace), currentVar.end()); } ++i; } else if (!currentVar.empty()) { if (i + 1 < lines.size()) { std::string value = lines[i + 1]; value.erase(std::remove_if(value.begin(), value.end(), isspace), value.end()); properties[currentVar] = value; } currentVar.clear(); ++i; } } } void printProperties() const { if (properties.empty()) { std::cout << "No properties found. Call read() first." << std::endl; return; } for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& outputPath = "", const std::map& modify = {}) { std::string out = outputPath.empty() ? filepath : outputPath; if (content.empty()) { std::cout << "No content to write. Call read() first." << std::endl; return; } std::vector lines; std::string tempContent = content; size_t pos; while ((pos = tempContent.find("\n")) != std::string::npos) { lines.push_back(tempContent.substr(0, pos)); tempContent.erase(0, pos + 1); } for (const auto& mod : modify) { std::string key = mod.first; std::string newValue = mod.second; if (properties.find(key) != properties.end()) { properties[key] = newValue; for (size_t i = 0; i < lines.size(); ++i) { std::string trimmed = lines[i]; trimmed.erase(std::remove_if(trimmed.begin(), trimmed.end(), isspace), trimmed.end()); if (trimmed == "9" && i + 1 < lines.size() && lines[i + 1] == key) { i += 2; if (i + 1 < lines.size()) { lines[i + 1] = newValue; } } } } } std::ofstream outfile(out); if (!outfile.is_open()) { std::cerr << "Error writing file." << std::endl; return; } for (const auto& l : lines) { outfile << l << "\n"; } outfile.close(); } }; // Example usage: // int main() { // DXFHandler handler("sample.dxf"); // handler.read(); // handler.printProperties(); // std::map modify = {{"$ACADVER", "AC1027"}}; // handler.write("output.dxf", modify); // return 0; // } // ===== end task-161 .DXF ===== // ===== task-003 .3G2 [C] ===== #include #include #include #include typedef struct { char *filename; uint8_t *data; size_t data_size; size_t pos; // Add property fields, e.g., char brand[5]; uint32_t minor_version; etc. } ThreeG2Parser; void init_parser(ThreeG2Parser *parser, const char *filename) { parser->filename = strdup(filename); FILE *f = fopen(filename, "rb"); fseek(f, 0, SEEK_END); parser->data_size = ftell(f); fseek(f, 0, SEEK_SET); parser->data = malloc(parser->data_size); fread(parser->data, 1, parser->data_size, f); fclose(f); parser->pos = 0; } void parse_boxes(ThreeG2Parser *parser) { while (parser->pos < parser->data_size) { uint32_t size = (parser->data[parser->pos] << 24) | (parser->data[parser->pos+1] << 16) | (parser->data[parser->pos+2] << 8) | parser->data[parser->pos+3]; char type[5] = {0}; strncpy(type, (char*)&parser->data[parser->pos+4], 4); parser->pos += 8; if (size == 1) { // Handle extended size (uint64_t) uint64_t ext_size = 0; // Implement shift and or for 8 bytes parser->pos += 8; size = ext_size; // Simplified } if (strcmp(type, "ftyp") == 0) { // Parse brand, minor_version, compatible_brands // e.g., strncpy(parser->brand, (char*)&parser->data[parser->pos], 4); } parser->pos += size - 8; // Adjust for extended // Extend parsing } } void print_properties(ThreeG2Parser *parser) { printf("Properties of .3G2 file:\n"); // printf("Brand: %s\n", parser->brand); // Print all } void write_file(ThreeG2Parser *parser, const char *output_filename) { FILE *f = fopen(output_filename, "wb"); fwrite(parser->data, 1, parser->data_size, f); fclose(f); } void free_parser(ThreeG2Parser *parser) { free(parser->data); free(parser->filename); } // Example usage: // int main() { // ThreeG2Parser parser; // init_parser(&parser, "sample.3g2"); // parse_boxes(&parser); // print_properties(&parser); // write_file(&parser, "output.3g2"); // free_parser(&parser); // return 0; // } // ===== end task-003 .3G2 ===== // ===== task-375 .MA [C] ===== #include #include #include #include typedef struct { char *header; char **file_references; int file_references_count; char **requirements; int requirements_count; char *units; char **file_information; int file_information_count; char **nodes; int nodes_count; char **attributes; int attributes_count; char **script_nodes; int script_nodes_count; char **disconnections; int disconnections_count; char **connections; int connections_count; char **geometry; int geometry_count; char **appearance; int appearance_count; char **scene; int scene_count; char **animation; int animation_count; } MAProperties; typedef struct { char *filepath; char *content; MAProperties properties; } MAFileHandler; void init_properties(MAProperties *props) { props->header = NULL; props->file_references = NULL; props->file_references_count = 0; props->requirements = NULL; props->requirements_count = 0; props->units = NULL; props->file_information = NULL; props->file_information_count = 0; props->nodes = NULL; props->nodes_count = 0; props->attributes = NULL; props->attributes_count = 0; props->script_nodes = NULL; props->script_nodes_count = 0; props->disconnections = NULL; props->disconnections_count = 0; props->connections = NULL; props->connections_count = 0; props->geometry = NULL; props->geometry_count = 0; props->appearance = NULL; props->appearance_count = 0; props->scene = NULL; props->scene_count = 0; props->animation = NULL; props->animation_count = 0; } void add_string_to_list(char ***list, int *count, const char *str) { *list = realloc(*list, sizeof(char*) * (*count + 1)); (*list)[*count] = strdup(str); (*count)++; } void read_ma(MAFileHandler *handler) { FILE *f = fopen(handler->filepath, "r"); if (f == NULL) { perror("Failed to open file"); return; } fseek(f, 0, SEEK_END); long length = ftell(f); fseek(f, 0, SEEK_SET); handler->content = malloc(length + 1); fread(handler->content, 1, length, f); handler->content[length] = '\0'; fclose(f); // Decode init_properties(&handler->properties); char *line = strtok(handler->content, "\n"); while (line != NULL) { char *trimmed = line; while (*trimmed == ' ') trimmed++; if (strstr(trimmed, "//Maya") == trimmed) { handler->properties.header = strdup(trimmed); } else if (strstr(trimmed, "file -r") == trimmed) { add_string_to_list(&handler->properties.file_references, &handler->properties.file_references_count, trimmed); } else if (strstr(trimmed, "requires") == trimmed) { add_string_to_list(&handler->properties.requirements, &handler->properties.requirements_count, trimmed); } else if (strstr(trimmed, "currentUnit") == trimmed) { handler->properties.units = strdup(trimmed); } else if (strstr(trimmed, "fileInfo") == trimmed) { add_string_to_list(&handler->properties.file_information, &handler->properties.file_information_count, trimmed); } else if (strstr(trimmed, "createNode") == trimmed) { add_string_to_list(&handler->properties.nodes, &handler->properties.nodes_count, trimmed); } else if (strstr(trimmed, "setAttr") == trimmed) { add_string_to_list(&handler->properties.attributes, &handler->properties.attributes_count, trimmed); } else if (strstr(trimmed, "scriptNode") == trimmed) { add_string_to_list(&handler->properties.script_nodes, &handler->properties.script_nodes_count, trimmed); } else if (strstr(trimmed, "disconnectAttr") == trimmed) { add_string_to_list(&handler->properties.disconnections, &handler->properties.disconnections_count, trimmed); } else if (strstr(trimmed, "connectAttr") == trimmed) { add_string_to_list(&handler->properties.connections, &handler->properties.connections_count, trimmed); } else if (strstr(trimmed, "translate") || strstr(trimmed, "scale") || strstr(trimmed, "rotate")) { add_string_to_list(&handler->properties.geometry, &handler->properties.geometry_count, trimmed); } else if (strstr(trimmed, "color") || strstr(trimmed, "texture") || strstr(trimmed, "material") || strstr(trimmed, "shading")) { add_string_to_list(&handler->properties.appearance, &handler->properties.appearance_count, trimmed); } else if (strstr(trimmed, "light") || strstr(trimmed, "camera")) { add_string_to_list(&handler->properties.scene, &handler->properties.scene_count, trimmed); } else if (strstr(trimmed, "keyframe") || strstr(trimmed, "animation")) { add_string_to_list(&handler->properties.animation, &handler->properties.animation_count, trimmed); } line = strtok(NULL, "\n"); } } void print_properties(MAProperties *props) { printf("Header:\n%s\n----------------------------------------\n", props->header ? props->header : ""); printf("FileReferences:\n"); for (int i = 0; i < props->file_references_count; i++) { printf("%s\n", props->file_references[i]); } printf("----------------------------------------\n"); // Similarly for other properties... // (Omitted for brevity, add similar blocks for each property) } void write_ma(MAFileHandler *handler, const char *new_filepath) { const char *path = new_filepath ? new_filepath : handler->filepath; FILE *f = fopen(path, "w"); if (f == NULL) { perror("Failed to open file for writing"); return; } fprintf(f, "%s", handler->content); fclose(f); } void free_properties(MAProperties *props) { free(props->header); for (int i = 0; i < props->file_references_count; i++) free(props->file_references[i]); free(props->file_references); // Similarly for other lists... // (Omitted for brevity) } int main() { MAFileHandler handler = {.filepath = "path/to/file.ma"}; read_ma(&handler); print_properties(&handler.properties); write_ma(&handler, "path/to/newfile.ma"); free(handler.content); free_properties(&handler.properties); return 0; } // ===== end task-375 .MA ===== // ===== task-210 .F95 [C++] ===== #include #include #include #include class F95Handler { private: std::vector properties = { "File extension: .f95 (case-insensitive, but often lowercase).", "File type: Plain text.", "MIME type: text/x-fortran.", "Encoding: Typically ASCII or UTF-8.", "Source form: Free-form (preferred for .f95 to indicate modern Fortran).", "Line length: Up to 132 characters in free-form.", "Continuation lines: Up to 39 in free-form, 19 in fixed-form.", "Continuation character: Ampersand (&) at the end of the line.", "Comment character: Exclamation mark (!).", "Case insensitivity: Keywords and identifiers are case-insensitive.", "Format specifications can be repeated (e.g., for printing arrays).", "Supports allocatable arrays with automatic deallocation.", "Supports pointers and target attributes.", "Supports modules for encapsulation.", "Supports generic procedures and operator overloading.", "Supports pure and elemental procedures.", "Supports array operations and whole-array arithmetic.", "Supports enhanced argument passing (e.g., optional arguments, intent attributes).", "Supports dynamic memory allocation.", "Supports structured data types (derived types)." }; public: void openAndPrintProperties(const std::string& filepath) { std::ifstream file(filepath); if (!file) { std::cout << "File not found." << std::endl; return; } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); std::cout << "File opened and read successfully." << std::endl; std::cout << "F95 Properties:" << std::endl; for (const auto& prop : properties) { std::cout << prop << std::endl; } } void writeSampleFile(const std::string& filepath) { std::ofstream file(filepath); if (!file) { std::cout << "Error opening file for writing." << std::endl; return; } file << "program sample" << std::endl; file << "print *, \"Hello from Fortran 95\"" << std::endl; file << "end program sample" << std::endl; file.close(); std::cout << "Sample .F95 file written successfully." << std::endl; } }; // Example usage: // int main() { // F95Handler handler; // handler.openAndPrintProperties("example.f95"); // handler.writeSampleFile("new.f95"); // return 0; // } // ===== end task-210 .F95 ===== // ===== task-004 .3GP [C] ===== #include #include #include #include #include // For htonl/ntohl typedef struct { char *filename; uint8_t *data; size_t size; // Properties would be stored in a struct or map; for simplicity, print directly } ThreeGPParser; uint64_t read_uint64_be(FILE *f) { uint32_t high, low; fread(&high, 4, 1, f); fread(&low, 4, 1, f); high = ntohl(high); low = ntohl(low); return ((uint64_t)high << 32) | low; } uint32_t read_uint32_be(FILE *f) { uint32_t val; fread(&val, 4, 1, f); return ntohl(val); } uint16_t read_uint16_be(FILE *f) { uint16_t val; fread(&val, 2, 1, f); return ntohs(val); } void parse_box(FILE *f, long box_size, char *box_type) { printf("Box: %s\n", box_type); if (strcmp(box_type, "ftyp") == 0) { char major[5]; fread(major, 4, 1, f); major[4] = '\0'; uint32_t minor = read_uint32_be(f); printf(" Major Brand: %s, Minor Version: %u\n", major, minor); // Read compatible brands until end while (ftell(f) < box_size) { char brand[5]; fread(brand, 4, 1, f); brand[4] = '\0'; printf(" Compatible Brand: %s\n", brand); } } else if (strcmp(box_type, "mvhd") == 0) { uint8_t version; fread(&version, 1, 1, f); fseek(f, 3, SEEK_CUR); // Flags long ts_off = version ? 20 : 12; fseek(f, ts_off - 4, SEEK_CUR); // Skip to timescale uint32_t timescale = read_uint32_be(f); uint64_t duration = version ? read_uint64_be(f) : read_uint32_be(f); printf(" Timescale: %u, Duration: %llu\n", timescale, duration); fseek(f, box_size - ftell(f), SEEK_CUR); // Skip rest } else if (strcmp(box_type, "tkhd") == 0) { uint8_t version; fread(&version, 1, 1, f); fseek(f, 3, SEEK_CUR); // Flags long id_off = version ? 20 : 12; fseek(f, id_off - 4, SEEK_CUR); // Skip to ID uint32_t track_id = read_uint32_be(f); fseek(f, box_size - 8 - ftell(f), SEEK_CUR); // To width/height float width = read_uint32_be(f) / 65536.0f; float height = read_uint32_be(f) / 65536.0f; printf(" Track ID: %u, Width: %.2f, Height: %.2f\n", track_id, width, height); } else if (strcmp(box_type, "udta") == 0) { // Recursive parse for udta subboxes long udta_end = ftell(f) + box_size - 8; while (ftell(f) < udta_end) { uint32_t sub_size = read_uint32_be(f); char sub_type[5]; fread(sub_type, 4, 1, f); sub_type[4] = '\0'; if (sub_size == 1) sub_size = (uint32_t) read_uint64_be(f); long sub_start = ftell(f); printf(" Udta Subbox: %s\n", sub_type); uint16_t lang = read_uint16_be(f) & 0x7FFF; if (strstr("titl dscp cprt perf auth gnre albm coll", sub_type)) { char value[1024]; // Assume max fread(value, sub_size - 10, 1, f); value[sub_size - 10] = '\0'; printf(" Language: 0x%x, Value: %s\n", lang, value); } else if (strcmp(sub_type, "yrrc") == 0) { uint16_t year = read_uint16_be(f); printf(" Year: %u\n", year); } // Add more fseek(f, sub_start + sub_size - 8, SEEK_SET); } } else { fseek(f, box_size - 8, SEEK_CUR); // Skip unknown } } void read_and_print(ThreeGPParser *parser) { FILE *f = fopen(parser->filename, "rb"); if (!f) return; fseek(f, 0, SEEK_END); parser->size = ftell(f); fseek(f, 0, SEEK_SET); parser->data = malloc(parser->size); fread(parser->data, parser->size, 1, f); // For write fseek(f, 0, SEEK_SET); while (!feof(f)) { uint32_t size = read_uint32_be(f); char type[5]; fread(type, 4, 1, f); type[4] = '\0'; if (size == 1) size = (uint32_t) read_uint64_be(f); long start = ftell(f); parse_box(f, start + size - 8, type); // Adjust for header fseek(f, start + size - 8, SEEK_SET); } fclose(f); } void write(ThreeGPParser *parser, char *new_filename) { if (!new_filename) { new_filename = malloc(strlen(parser->filename) + 10); sprintf(new_filename, "%s.modified.3gp", parser->filename); } FILE *out = fopen(new_filename, "wb"); fwrite(parser->data, parser->size, 1, out); fclose(out); printf("File written to %s\n", new_filename); if (strstr(new_filename, ".modified")) free(new_filename); } int main(int argc, char **argv) { if (argc < 2) return 1; ThreeGPParser parser = {.filename = argv[1]}; read_and_print(&parser); write(&parser, NULL); free(parser.data); return 0; } // ===== end task-004 .3GP ===== // ===== task-384 .MCTEMPLATE [C++] ===== #include #include #include #include #include // Assume minizip library #include // For JSON parsing class MCTemplateHandler { private: std::string filepath; std::map properties; // Simplified to string values public: MCTemplateHandler(const std::string& fp) : filepath(fp) { read(); } void read() { zip_t* z = zip_open(filepath.c_str(), ZIP_RDONLY, nullptr); if (!z) return; // ZIP properties struct stat st; stat(filepath.c_str(), &st); properties["zip_filename"] = filepath.substr(filepath.find_last_of("/\\") + 1); properties["zip_size"] = std::to_string(st.st_size); int num_entries = zip_get_num_entries(z, 0); for (int i = 0; i < num_entries; ++i) { const char* name = zip_get_name(z, i, 0); if (std::string(name) == "manifest.json") { zip_file_t* f = zip_fopen_index(z, i, 0); char buf[4096]; zip_fread(f, buf, sizeof(buf)); zip_fclose(f); cJSON* json = cJSON_Parse(buf); properties["manifest"] = cJSON_Print(json); cJSON_Delete(json); } else if (std::string(name) == "texts/en_US.lang") { zip_file_t* f = zip_fopen_index(z, i, 0); char buf[4096]; zip_fread(f, buf, sizeof(buf)); zip_fclose(f); properties["en_US_lang"] = buf; } // Add similar for others, check existence for level.dat, db, etc. } zip_close(z); } void printProperties() { for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } void write(const std::string& newFilepath) { zip_t* z = zip_open(newFilepath.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); if (!z) return; if (properties.find("manifest") != properties.end()) { zip_source_t* src = zip_source_buffer(z, properties["manifest"].c_str(), properties["manifest"].size(), 0); zip_file_add(z, "manifest.json", src, ZIP_FL_OVERWRITE); } // Add similar for other files zip_close(z); } }; // Example usage // int main() { // MCTemplateHandler handler("example.mctemplate"); // handler.printProperties(); // handler.write("new.mctemplate"); // return 0; // } // ===== end task-384 .MCTEMPLATE ===== // ===== task-005 .3GX [C] ===== #include #include #include #include #include // For htonl/ntohl typedef struct { char *filename; uint8_t *data; size_t size; // Properties would be stored in a struct or map; for simplicity, print directly } ThreeGPParser; uint64_t read_uint64_be(FILE *f) { uint32_t high, low; fread(&high, 4, 1, f); fread(&low, 4, 1, f); high = ntohl(high); low = ntohl(low); return ((uint64_t)high << 32) | low; } uint32_t read_uint32_be(FILE *f) { uint32_t val; fread(&val, 4, 1, f); return ntohl(val); } uint16_t read_uint16_be(FILE *f) { uint16_t val; fread(&val, 2, 1, f); return ntohs(val); } void parse_box(FILE *f, long box_size, char *box_type) { printf("Box: %s\n", box_type); if (strcmp(box_type, "ftyp") == 0) { char major[5]; fread(major, 4, 1, f); major[4] = '\0'; uint32_t minor = read_uint32_be(f); printf(" Major Brand: %s, Minor Version: %u\n", major, minor); // Read compatible brands until end while (ftell(f) < box_size) { char brand[5]; fread(brand, 4, 1, f); brand[4] = '\0'; printf(" Compatible Brand: %s\n", brand); } } else if (strcmp(box_type, "mvhd") == 0) { uint8_t version; fread(&version, 1, 1, f); fseek(f, 3, SEEK_CUR); // Flags long ts_off = version ? 20 : 12; fseek(f, ts_off - 4, SEEK_CUR); // Skip to timescale uint32_t timescale = read_uint32_be(f); uint64_t duration = version ? read_uint64_be(f) : read_uint32_be(f); printf(" Timescale: %u, Duration: %llu\n", timescale, duration); fseek(f, box_size - ftell(f), SEEK_CUR); // Skip rest } else if (strcmp(box_type, "tkhd") == 0) { uint8_t version; fread(&version, 1, 1, f); fseek(f, 3, SEEK_CUR); // Flags long id_off = version ? 20 : 12; fseek(f, id_off - 4, SEEK_CUR); // Skip to ID uint32_t track_id = read_uint32_be(f); fseek(f, box_size - 8 - ftell(f), SEEK_CUR); // To width/height float width = read_uint32_be(f) / 65536.0f; float height = read_uint32_be(f) / 65536.0f; printf(" Track ID: %u, Width: %.2f, Height: %.2f\n", track_id, width, height); } else if (strcmp(box_type, "udta") == 0) { // Recursive parse for udta subboxes long udta_end = ftell(f) + box_size - 8; while (ftell(f) < udta_end) { uint32_t sub_size = read_uint32_be(f); char sub_type[5]; fread(sub_type, 4, 1, f); sub_type[4] = '\0'; if (sub_size == 1) sub_size = (uint32_t) read_uint64_be(f); long sub_start = ftell(f); printf(" Udta Subbox: %s\n", sub_type); uint16_t lang = read_uint16_be(f) & 0x7FFF; if (strstr("titl dscp cprt perf auth gnre albm coll", sub_type)) { char value[1024]; // Assume max fread(value, sub_size - 10, 1, f); value[sub_size - 10] = '\0'; printf(" Language: 0x%x, Value: %s\n", lang, value); } else if (strcmp(sub_type, "yrrc") == 0) { uint16_t year = read_uint16_be(f); printf(" Year: %u\n", year); } // Add more fseek(f, sub_start + sub_size - 8, SEEK_SET); } } else { fseek(f, box_size - 8, SEEK_CUR); // Skip unknown } } void read_and_print(ThreeGPParser *parser) { FILE *f = fopen(parser->filename, "rb"); if (!f) return; fseek(f, 0, SEEK_END); parser->size = ftell(f); fseek(f, 0, SEEK_SET); parser->data = malloc(parser->size); fread(parser->data, parser->size, 1, f); // For write fseek(f, 0, SEEK_SET); while (!feof(f)) { uint32_t size = read_uint32_be(f); char type[5]; fread(type, 4, 1, f); type[4] = '\0'; if (size == 1) size = (uint32_t) read_uint64_be(f); long start = ftell(f); parse_box(f, start + size - 8, type); // Adjust for header fseek(f, start + size - 8, SEEK_SET); } fclose(f); } void write(ThreeGPParser *parser, char *new_filename) { if (!new_filename) { new_filename = malloc(strlen(parser->filename) + 10); sprintf(new_filename, "%s.modified.3gp", parser->filename); } FILE *out = fopen(new_filename, "wb"); fwrite(parser->data, parser->size, 1, out); fclose(out); printf("File written to %s\n", new_filename); if (strstr(new_filename, ".modified")) free(new_filename); } int main(int argc, char **argv) { if (argc < 2) return 1; ThreeGPParser parser = {.filename = argv[1]}; read_and_print(&parser); write(&parser, NULL); free(parser.data); return 0; } // ===== end task-005 .3GX ===== // ===== task-419 .MPEG [C] ===== #include #include #include #include typedef struct { char* filepath; // Use a map-like array or struct for properties (simplified as char buffer for print) char properties[4096]; // Buffer for printed properties } MPEGHandler; void init_mpeg_handler(MPEGHandler* handler, const char* filepath) { handler->filepath = strdup(filepath); memset(handler->properties, 0, sizeof(handler->properties)); } void read_decode(MPEGHandler* handler) { FILE* f = fopen(handler->filepath, "rb"); if (!f) return; fseek(f, 0, SEEK_END); long len = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(len); fread(data, 1, len, f); fclose(f); int offset = 0; char buf[1024] = {0}; while (offset < len - 4) { uint32_t start_code = (data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]; if (start_code == 0x000001BA) { // Pack header // Parse SCR, mux rate, etc. uint32_t mux_rate = (((data[offset+9] & 0x01) << 21) | ((data[offset+10] << 8 | data[offset+11]) >> 1)) * 50; int stuffing_len = data[offset+11] & 0x07; sprintf(buf, "Pack: Mux Rate %u, Stuffing %d\n", mux_rate, stuffing_len); strcat(handler->properties, buf); offset += 12 + stuffing_len; } else if (start_code == 0x000001BB) { // System header uint16_t header_len = (data[offset+4] << 8) | data[offset+5]; // Parse more sprintf(buf, "System: Header Len %hu\n", header_len); strcat(handler->properties, buf); offset += 6 + header_len; } else if ((start_code & 0xFFFFFF00) == 0x00000100) { uint8_t stream_id = start_code & 0xFF; uint16_t packet_len = (data[offset+4] << 8) | data[offset+5]; sprintf(buf, "Packet: Stream ID 0x%02X, Len %hu\n", stream_id, packet_len); strcat(handler->properties, buf); offset += 6; // Extend } else { offset++; } } free(data); } void print_properties(MPEGHandler* handler) { printf("MPEG Properties:\n%s", handler->properties); } void write_file(MPEGHandler* handler, const char* output_path) { FILE* f_in = fopen(handler->filepath, "rb"); FILE* f_out = fopen(output_path, "wb"); if (f_in && f_out) { char buf[4096]; size_t read; while ((read = fread(buf, 1, sizeof(buf), f_in)) > 0) { fwrite(buf, 1, read, f_out); } fclose(f_in); fclose(f_out); printf("Wrote to %s\n", output_path); } } void free_mpeg_handler(MPEGHandler* handler) { free(handler->filepath); } // Example usage: // int main() { // MPEGHandler handler; // init_mpeg_handler(&handler, "sample.mpeg"); // read_decode(&handler); // print_properties(&handler); // write_file(&handler, "output.mpeg"); // free_mpeg_handler(&handler); // return 0; // } // ===== end task-419 .MPEG ===== // ===== task-006 .3mf [C++] ===== #include #include #include #include #include class ThreeMF { private: std::map properties; const char* ns = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02"; public: ThreeMF(const char* filename = nullptr) { if (filename) read(filename); } void read(const char* filename) { zip_t* za = zip_open(filename, ZIP_RDONLY, nullptr); if (!za) return; zip_file_t* modelFile = zip_fopen(za, "3dmodel.model", 0); if (modelFile) { std::string modelXml; char buf[1024]; zip_int64_t len; while ((len = zip_fread(modelFile, buf, sizeof(buf))) > 0) modelXml.append(buf, len); zip_fclose(modelFile); tinyxml2::XMLDocument modelDoc; modelDoc.Parse(modelXml.c_str()); tinyxml2::XMLElement* model = modelDoc.FirstChildElement("model"); if (model) { properties["File Extension"] = ".3mf"; properties["MIME Type"] = "model/3mf"; properties["Package Format"] = "ZIP (OPC)"; properties["Model Unit"] = model->Attribute("unit"); properties["Language"] = model->Attribute("xml:lang"); for (tinyxml2::XMLElement* meta = model->FirstChildElement("metadata"); meta; meta = meta->NextSiblingElement("metadata")) { properties[meta->Attribute("name")] = meta->GetText() ? meta->GetText() : ""; } } } zip_file_t* coreFile = zip_fopen(za, "metadata/core-properties.xml", 0); if (coreFile) { std::string coreXml; char buf[1024]; zip_int64_t len; while ((len = zip_fread(coreFile, buf, sizeof(buf))) > 0) coreXml.append(buf, len); zip_fclose(coreFile); tinyxml2::XMLDocument coreDoc; coreDoc.Parse(coreXml.c_str()); tinyxml2::XMLElement* core = coreDoc.FirstChildElement("cp:coreProperties"); if (core) { const char* tags[] = {"dc:title", "dc:creator", "dcterms:created", "dcterms:modified"}; for (const char* tag : tags) { tinyxml2::XMLElement* elem = core->FirstChildElement(tag); if (elem) properties[tag] = elem->GetText() ? elem->GetText() : ""; } } } zip_close(za); } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const char* filename) { zip_t* za = zip_open(filename, ZIP_CREATE | ZIP_TRUNCATE, nullptr); if (!za) return; const char* modelXml = "Sample Model"; zip_source_t* src = zip_source_buffer(za, modelXml, strlen(modelXml), 0); zip_file_add(za, "3dmodel.model", src, ZIP_FL_ENC_UTF_8); const char* coreXml = "Sample TitleSample Creator"; src = zip_source_buffer(za, coreXml, strlen(coreXml), 0); zip_file_add(za, "metadata/core-properties.xml", src, ZIP_FL_ENC_UTF_8); const char* contentTypes = ""; src = zip_source_buffer(za, contentTypes, strlen(contentTypes), 0); zip_file_add(za, "[Content_Types].xml", src, ZIP_FL_ENC_UTF_8); const char* rels = ""; src = zip_source_buffer(za, rels, strlen(rels), 0); zip_file_add(za, "_rels/.rels", src, ZIP_FL_ENC_UTF_8); zip_close(za); } }; // ===== end task-006 .3mf ===== // ===== task-423 .MRSH [C] ===== #include #include #include #include #define MAX_LINE 1024 #define MAX_TYPES 100 #define MAX_FUNCS 100 #define MAX_FIELDS 50 #define MAX_VALUES 100 #define MAX_EXAMPLES 100 typedef struct { char *name; char *path; char **fields; int field_count; char ***values; int value_count; } MrshType; typedef struct { char *name; char **inputs; int input_count; char *output; char *description; char **examples; int example_count; } MrshFunction; typedef struct { char *filename; char *content; MrshType types[MAX_TYPES]; int type_count; MrshFunction functions[MAX_FUNCS]; int func_count; } MrshParser; void init_parser(MrshParser *parser, char *filename) { parser->filename = strdup(filename); parser->content = NULL; parser->type_count = 0; parser->func_count = 0; } void free_parser(MrshParser *parser) { free(parser->filename); if (parser->content) free(parser->content); // Free types and functions memory (omitted for brevity; add free for each alloc) } void read_file(MrshParser *parser) { FILE *fp = fopen(parser->filename, "r"); if (!fp) { perror("File open failed"); return; } fseek(fp, 0, SEEK_END); long size = ftell(fp); fseek(fp, 0, SEEK_SET); parser->content = malloc(size + 1); fread(parser->content, 1, size, fp); parser->content[size] = '\0'; fclose(fp); } void decode(MrshParser *parser) { if (!parser->content) return; char *line = strtok(parser->content, "\n"); char *current_section = NULL; MrshType *last_type = NULL; MrshFunction *current_func = NULL; while (line) { char trimmed[MAX_LINE]; strcpy(trimmed, line); // Trim logic (omit for brevity) if (strstr(trimmed, "# type ") == trimmed) { // Parse type (similar to Python/JS logic, alloc memory) // Add to parser->types current_section = "type"; } else if (strstr(trimmed, "# func ") == trimmed) { // Use regex to parse func def regex_t regex; regcomp(®ex, "(\\w+)\\(([^)]*)\\): (.*)", REG_EXTENDED); regmatch_t matches[4]; if (regexec(®ex, trimmed + 7, 4, matches, 0) == 0) { // Extract name, inputs, output // Add to parser->functions current_section = "func_desc"; } regfree(®ex); } else if (strstr(trimmed, "* ") == trimmed && current_func) { current_section = "func_examples"; // Add to current_func->examples } else if (strcmp(current_section, "func_desc") == 0 && strlen(trimmed) > 0 && current_func) { // Append to description } else if (strcmp(current_section, "type") == 0 && strlen(trimmed) > 0 && last_type) { // Parse fields or values } line = strtok(NULL, "\n"); } } void print_properties(MrshParser *parser) { printf("Data Types:\n"); for (int i = 0; i < parser->type_count; i++) { MrshType t = parser->types[i]; printf("- Name: %s\n", t.name); if (t.path) printf(" Path: %s\n", t.path); if (t.field_count) { printf(" Fields: "); for (int j = 0; j < t.field_count; j++) printf("%s%s", t.fields[j], j < t.field_count - 1 ? ", " : "\n"); } if (t.value_count) { printf(" Values:\n"); for (int j = 0; j < t.value_count; j++) { printf(" "); for (int k = 0; k < t.field_count; k++) printf("%s%s", t.values[j][k], k < t.field_count - 1 ? ", " : "\n"); } } } printf("\nFunctions:\n"); for (int i = 0; i < parser->func_count; i++) { MrshFunction f = parser->functions[i]; printf("- Name: %s\n", f.name); printf(" Inputs: "); for (int j = 0; j < f.input_count; j++) printf("%s%s", f.inputs[j], j < f.input_count - 1 ? ", " : "\n"); printf(" Output: %s\n", f.output); printf(" Description: %s\n", f.description); printf(" Examples:\n"); for (int j = 0; j < f.example_count; j++) printf(" %s\n", f.examples[j]); } } void write_file(MrshParser *parser, char *new_filename) { if (!new_filename) new_filename = parser->filename; FILE *fp = fopen(new_filename, "w"); if (fp) { fprintf(fp, "%s", parser->content); // Writes original; modify content to change fclose(fp); } } // Usage example: // int main() { // MrshParser parser; // init_parser(&parser, "example.mrsh"); // read_file(&parser); // decode(&parser); // print_properties(&parser); // write_file(&parser, "output.mrsh"); // free_parser(&parser); // return 0; // } // ===== end task-423 .MRSH ===== // ===== task-007 .4TH [C] ===== #include #include #include #include #include #include #include struct FourthFileHandler { char *filename; }; struct FourthFileHandler* createFourthFileHandler(const char *filename) { if (strstr(filename, ".4th") == NULL && strstr(filename, ".4TH") == NULL) { fprintf(stderr, "File must have .4th extension\n"); exit(1); } struct FourthFileHandler *handler = malloc(sizeof(struct FourthFileHandler)); handler->filename = strdup(filename); return handler; } void destroyFourthFileHandler(struct FourthFileHandler *handler) { free(handler->filename); free(handler); } void printProperties(struct FourthFileHandler *handler) { struct stat st; if (stat(handler->filename, &st) != 0) { perror("stat"); return; } printf("File Properties:\n"); printf("File name: %s\n", handler->filename); printf("File size (in bytes): %ld\n", (long)st.st_size); printf("Creation time: %s", ctime(&st.st_ctime)); // ctime as proxy for creation printf("Last modification time: %s", ctime(&st.st_mtime)); printf("Last access time: %s", ctime(&st.st_atime)); printf("Permissions (mode): %o\n", st.st_mode & 0777); printf("Owner user ID (UID): %d\n", st.st_uid); printf("Group ID (GID): %d\n", st.st_gid); printf("Inode number: %ld\n", (long)st.st_ino); printf("Number of hard links: %ld\n", (long)st.st_nlink); printf("Device ID: %ld\n", (long)st.st_dev); } void writeExampleFile(const char *newFilename) { if (strstr(newFilename, ".4th") == NULL && strstr(newFilename, ".4TH") == NULL) { fprintf(stderr, "New file must have .4th extension\n"); return; } FILE *f = fopen(newFilename, "w"); if (f == NULL) { perror("fopen"); return; } fprintf(f, ": HELLO CR .\" Hello, Forth! \" CR ;\nHELLO\n"); fclose(f); chmod(newFilename, 0644); } // Example usage: // int main() { // struct FourthFileHandler *handler = createFourthFileHandler("example.4th"); // printProperties(handler); // writeExampleFile("new_example.4th"); // destroyFourthFileHandler(handler); // return 0; // } // ===== end task-007 .4TH ===== // ===== task-742 .TXT [C++] ===== #include #include #include #include #include class TxtFileHandler { private: std::string filePath; std::string content; public: TxtFileHandler(const std::string& fp) : filePath(fp) {} std::string openAndRead() { std::ifstream file(filePath); if (file) { content.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); } return content; } void printProperties() { struct stat st; if (stat(filePath.c_str(), &st) == 0) { std::cout << "File path: " << filePath << std::endl; std::cout << "File size (bytes): " << st.st_size << std::endl; std::cout << "Creation timestamp: " << std::ctime(&st.st_ctime); std::cout << "Last modification timestamp: " << std::ctime(&st.st_mtime); std::cout << "Last access timestamp: " << std::ctime(&st.st_atime); std::cout << "File mode (permissions): " << std::oct << st.st_mode << std::endl; std::cout << "User ID of owner: " << st.st_uid << std::endl; std::cout << "Group ID of owner: " << st.st_gid << std::endl; std::cout << "Inode number: " << st.st_ino << std::endl; std::cout << "Device ID: " << st.st_dev << std::endl; std::cout << "Number of hard links: " << st.st_nlink << std::endl; } else { std::cerr << "Error retrieving properties." << std::endl; } } void write(const std::string& newContent) { std::ofstream file(filePath); if (file) { file << newContent; file.close(); } } }; // Example usage: // int main() { // TxtFileHandler handler("example.txt"); // handler.openAndRead(); // handler.printProperties(); // handler.write("New content"); // return 0; // } // ===== end task-742 .TXT ===== // ===== task-503 .P10 [C] ===== #include #include #include #include typedef struct { char *filename; PKCS10 *csr; } P10Handler; P10Handler* createP10Handler(const char *filename) { P10Handler *handler = malloc(sizeof(P10Handler)); handler->filename = strdup(filename); handler->csr = NULL; return handler; } void openP10(P10Handler *handler) { FILE *fp = fopen(handler->filename, "rb"); if (fp) { handler->csr = d2i_PKCS10_fp(fp, NULL); fclose(fp); } } void decodeRead(P10Handler *handler) { if (!handler->csr) { openP10(handler); } if (handler->csr) { // Print properties printf("Version: %d\n", PKCS10_get_version(handler->csr)); X509_NAME_print_ex_fp(stdout, PKCS10_get_subject_name(handler->csr), 0, 0); printf("\nPublic Key Algorithm: %s\n", OBJ_nid2sn(EVP_PKEY_id(PKCS10_get0_pubkey(handler->csr)))); EVP_PKEY_print_public_fp(stdout, PKCS10_get0_pubkey(handler->csr), 0, NULL); printf("Attributes: "); // Simplified, attributes are in CSR REQ_INFO // For attributes, use PKCS10_get_req(handler->csr)->req_info->attributes printf("\nSignature Algorithm: %s\n", OBJ_nid2sn(PKCS10_get0_signature_alg(handler->csr)->algorithm->nid)); printf("Signature: "); // Print hex const unsigned char *sig = PKCS10_get0_signature(handler->csr); int sig_len = PKCS10_get0_signature_len(handler->csr); for (int i = 0; i < sig_len; i++) { printf("%02x ", sig[i]); } printf("\n"); } else { printf("Error loading CSR\n"); } } void printProperties(P10Handler *handler) { decodeRead(handler); } void writeP10(P10Handler *handler, const char *newFilename) { if (handler->csr) { FILE *fp = fopen(newFilename, "wb"); if (fp) { i2d_PKCS10_fp(fp, handler->csr); fclose(fp); } } else { printf("No CSR loaded to write.\n"); } } void destroyP10Handler(P10Handler *handler) { if (handler->csr) PKCS10_free(handler->csr); free(handler->filename); free(handler); } // Example usage // int main() { // P10Handler *handler = createP10Handler("sample.p10"); // printProperties(handler); // writeP10(handler, "output.p10"); // destroyP10Handler(handler); // return 0; // } // ===== end task-503 .P10 ===== // ===== task-008 .7z [C++] ===== #include #include #include #include #include #include class SevenZipHandler { private: std::string filepath; std::map properties; std::vector> files; public: SevenZipHandler(const std::string& fp) : filepath(fp) {} void openAndDecode() { std::ifstream file(filepath, std::ios::binary); if (!file) throw std::runtime_error("Cannot open file"); std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); parse(data.data(), data.size()); } void parse(const char* data, size_t size) { // Signature check std::string sig(data, 6); if (sig != "7z\xbc\xaf\x27\x1c") throw std::runtime_error("Invalid signature"); // Version uint8_t major = static_cast(data[6]); uint8_t minor = static_cast(data[7]); properties["version"] = (static_cast(major) << 8) | minor; // Start CRC uint32_t start_crc = *reinterpret_cast(data + 8); properties["start_crc"] = start_crc; // Next offset, size, CRC (manual little-endian read) uint64_t next_offset = readUint64(data + 12); uint64_t next_size = readUint64(data + 20); uint32_t next_crc = *reinterpret_cast(data + 28); properties["next_offset"] = next_offset; properties["next_size"] = next_size; properties["next_crc"] = next_crc; // Parse header size_t header_start = 32 + next_offset; parseHeader(data + header_start, next_size); } uint64_t readUint64(const char* ptr) { uint64_t val = 0; for (int i = 0; i < 8; ++i) val |= (static_cast(static_cast(ptr[i])) << (i * 8)); return val; } void parseHeader(const char* data, size_t size) { // Simplified parsing // ... (Implement property ID loop, extract fields) } void printProperties() { std::cout << "Archive Properties:" << std::endl; for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } std::cout << "\nFile Properties:" << std::endl; for (const auto& f : files) { for (const auto& fp : f) { std::cout << fp.first << ": " << fp.second << std::endl; } std::cout << "---" << std::endl; } } void write(const std::string& newFilepath) { // Serialize (simplified) // ... (Reconstruct data, write to file) std::ofstream out(newFilepath, std::ios::binary); // Placeholder } }; // Usage example // int main() { // SevenZipHandler handler("sample.7z"); // handler.openAndDecode(); // handler.printProperties(); // handler.write("modified.7z"); // return 0; // } // ===== end task-008 .7z ===== // ===== task-529 .PDN [C++] ===== #include #include #include #include #include class PDNHandler { private: std::map properties; public: void read(const std::string& filename) { std::ifstream file(filename); std::string text((std::istreambuf_iterator(file)), std::istreambuf_iterator()); std::regex regex(R"(\[(\w+)\s+"(.*?)"\])"); std::sregex_iterator iter(text.begin(), text.end(), regex); std::sregex_iterator end; for (; iter != end; ++iter) { properties[(*iter)[1].str()] = (*iter)[2].str(); } printProperties(); } void printProperties() { std::cout << "PDN Properties:" << std::endl; for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& filename, const std::string& moves) { std::ofstream file(filename); for (const auto& pair : properties) { file << "[" << pair.first << " \"" << pair.second << "\"]" << std::endl; } file << std::endl << moves << std::endl << "*"; } }; // Example usage: // int main() { // PDNHandler handler; // handler.read("example.pdn"); // handler.properties["Event"] = "New Event"; // handler.write("new.pdn", "1. 32-28 19-23"); // return 0; // } // ===== end task-529 .PDN ===== // ===== task-009 .A [C] ===== #include #include #include #include #include #include #include #define MAGIC "!\n" #define HEADER_SIZE 60 typedef struct { char *name; char *data; size_t data_size; long timestamp; int uid; int gid; mode_t mode; } Member; typedef struct { char *filepath; Member *members; size_t member_count; } AFileHandler; void init_a_file_handler(AFileHandler *handler, const char *filepath) { handler->filepath = strdup(filepath); handler->members = NULL; handler->member_count = 0; } void free_a_file_handler(AFileHandler *handler) { free(handler->filepath); for (size_t i = 0; i < handler->member_count; i++) { free(handler->members[i].name); free(handler->members[i].data); } free(handler->members); } int read_a_file(AFileHandler *handler) { FILE *f = fopen(handler->filepath, "rb"); if (!f) return -1; fseek(f, 0, SEEK_END); long file_size = ftell(f); fseek(f, 0, SEEK_SET); char *data = malloc(file_size); fread(data, 1, file_size, f); fclose(f); long offset = 0; if (strncmp(data + offset, MAGIC, 8) != 0) { free(data); return -1; } offset += 8; while (offset < file_size) { if (offset + HEADER_SIZE > file_size) break; char header[HEADER_SIZE]; memcpy(header, data + offset, HEADER_SIZE); char name_str[17] = {0}; strncpy(name_str, header, 16); char *name = strdup(strtok(name_str, " ")); long timestamp = atol(strndup(header + 16, 12)); int uid = atoi(strndup(header + 28, 6)); int gid = atoi(strndup(header + 34, 6)); mode_t mode = strtol(strndup(header + 40, 8), NULL, 8); size_t size = atol(strndup(header + 48, 10)); if (header[58] != '`' || header[59] != '\n') { free(name); free(data); return -1; } char *member_data = malloc(size); memcpy(member_data, data + offset + HEADER_SIZE, size); handler->members = realloc(handler->members, sizeof(Member) * (handler->member_count + 1)); handler->members[handler->member_count].name = name; handler->members[handler->member_count].data = member_data; handler->members[handler->member_count].data_size = size; handler->members[handler->member_count].timestamp = timestamp; handler->members[handler->member_count].uid = uid; handler->members[handler->member_count].gid = gid; handler->members[handler->member_count].mode = mode; handler->member_count++; offset += HEADER_SIZE + size; if (size % 2 != 0) offset += 1; } free(data); return 0; } void print_properties(const AFileHandler *handler) { printf("Magic Signature: !\\n\n"); for (size_t i = 0; i < handler->member_count; i++) { Member m = handler->members[i]; struct tm *tm = localtime(&m.timestamp); char time_buf[32]; strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", tm); printf("Member: %s\n", m.name); printf(" Timestamp: %ld (%s)\n", m.timestamp, time_buf); printf(" UID: %d\n", m.uid); printf(" GID: %d\n", m.gid); printf(" Mode: %o\n", m.mode); printf(" Size: %zu bytes\n\n", m.data_size); } } int write_a_file(const AFileHandler *handler, const char *output_path) { FILE *f = fopen(output_path, "wb"); if (!f) return -1; fwrite(MAGIC, 1, 8, f); for (size_t i = 0; i < handler->member_count; i++) { Member m = handler->members[i]; char header[HEADER_SIZE]; snprintf(header, sizeof(header), "%-16s%12ld%6d%6d%8o%10zu`\n", m.name, m.timestamp, m.uid, m.gid, m.mode, m.data_size); fwrite(header, 1, HEADER_SIZE, f); fwrite(m.data, 1, m.data_size, f); if (m.data_size % 2 != 0) { fputc('\n', f); } } fclose(f); return 0; } // Example usage: // int main() { // AFileHandler handler; // init_a_file_handler(&handler, "example.a"); // if (read_a_file(&handler) == 0) { // print_properties(&handler); // } // // Add a new member // Member new_member; // new_member.name = strdup("newfile.txt"); // new_member.data = strdup("content"); // new_member.data_size = strlen(new_member.data); // new_member.timestamp = time(NULL); // new_member.uid = getuid(); // new_member.gid = getgid(); // new_member.mode = 0644; // handler.members = realloc(handler.members, sizeof(Member) * (handler.member_count + 1)); // handler.members[handler.member_count] = new_member; // handler.member_count++; // write_a_file(&handler, "new.a"); // free_a_file_handler(&handler); // return 0; // } // ===== end task-009 .A ===== // ===== task-546 .PHY [C++] ===== #include #include #include #include #include using namespace std; class PHYFile { private: int numTaxa; int numChars; vector taxonNames; vector sequences; public: PHYFile(string filepath = "") { numTaxa = 0; numChars = 0; if (!filepath.empty()) { read(filepath); } } void read(string filepath) { ifstream file(filepath); string line; getline(file, line); stringstream header(line); header >> numTaxa >> numChars; while (getline(file, line)) { if (!line.empty()) { string name = line.substr(0, 10); name.erase(remove(name.begin(), name.end(), ' '), name.end()); // trim spaces string seq = line.substr(10); seq.erase(remove(seq.begin(), seq.end(), ' '), seq.end()); taxonNames.push_back(name); sequences.push_back(seq); } } file.close(); } void write(string filepath) { ofstream file(filepath); file << numTaxa << " " << numChars << endl; for (size_t i = 0; i < taxonNames.size(); ++i) { file << left << setw(10) << taxonNames[i] << sequences[i] << endl; } file.close(); } void printProperties() { cout << "Number of taxa: " << numTaxa << endl; cout << "Number of characters: " << numChars << endl; cout << "Taxon names:" << endl; for (const string& name : taxonNames) { cout << name << endl; } cout << "Sequences:" << endl; for (const string& seq : sequences) { cout << seq << endl; } } }; int main(int argc, char* argv[]) { if (argc > 1) { PHYFile phy(argv[1]); phy.printProperties(); phy.write("output.phy"); // Example write } return 0; } // ===== end task-546 .PHY ===== // ===== task-589 .QOI [C] ===== #include #include #include #include #define QOI_MAGIC 'q'<<24 | 'o'<<16 | 'i'<<8 | 'f' typedef struct { uint32_t magic; uint32_t width; uint32_t height; uint8_t channels; uint8_t colorspace; uint8_t *pixels; // RGBA bytes, width * height * 4 } QOI_t; QOI_t* qoi_create() { QOI_t* q = (QOI_t*)malloc(sizeof(QOI_t)); if (!q) return NULL; memset(q, 0, sizeof(QOI_t)); q->magic = QOI_MAGIC; q->channels = 4; q->colorspace = 0; return q; } void qoi_destroy(QOI_t* q) { if (q->pixels) free(q->pixels); free(q); } int qoi_load(QOI_t* q, const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) return -1; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = (uint8_t*)malloc(size); fread(data, 1, size, f); fclose(f); int ret = qoi_decode(q, data, size); free(data); return ret; } int qoi_decode(QOI_t* q, const uint8_t* data, int size) { if (size < 14) return -1; q->magic = data[0]<<24 | data[1]<<16 | data[2]<<8 | data[3]; if (q->magic != QOI_MAGIC) return -1; q->width = data[4]<<24 | data[5]<<16 | data[6]<<8 | data[7]; q->height = data[8]<<24 | data[9]<<16 | data[10]<<8 | data[11]; q->channels = data[12]; q->colorspace = data[13]; if (q->channels != 3 && q->channels != 4 || (q->colorspace != 0 && q->colorspace != 1)) return -1; int p = 14; int px_len = q->width * q->height * 4; q->pixels = (uint8_t*)malloc(px_len); if (!q->pixels) return -1; int run = 0; uint8_t index[64][4] = {0}; uint8_t px[4] = {0, 0, 0, 255}; int px_pos = 0; while (px_pos < px_len) { if (run > 0) { run--; } else { if (p >= size - 8) { free(q->pixels); return -1; } uint8_t b1 = data[p++]; if (b1 == 0xfe) { // QOI_OP_RGB px[0] = data[p++]; px[1] = data[p++]; px[2] = data[p++]; } else if (b1 == 0xff) { // QOI_OP_RGBA px[0] = data[p++]; px[1] = data[p++]; px[2] = data[p++]; px[3] = data[p++]; } else if ((b1 & 0xc0) == 0x00) { // QOI_OP_INDEX memcpy(px, index[b1], 4); } else if ((b1 & 0xc0) == 0x40) { // QOI_OP_DIFF px[0] = (px[0] + ((b1 >> 4) & 0x03) - 2) & 0xff; px[1] = (px[1] + ((b1 >> 2) & 0x03) - 2) & 0xff; px[2] = (px[2] + (b1 & 0x03) - 2) & 0xff; } else if ((b1 & 0xc0) == 0x80) { // QOI_OP_LUMA uint8_t b2 = data[p++]; int dg = (b1 & 0x3f) - 32; px[0] = (px[0] + dg - 8 + ((b2 >> 4) & 0x0f)) & 0xff; px[1] = (px[1] + dg) & 0xff; px[2] = (px[2] + dg - 8 + (b2 & 0x0f)) & 0xff; } else if ((b1 & 0xc0) == 0xc0) { // QOI_OP_RUN run = (b1 & 0x3f) + 1 - 1; } int idx = (px[0] * 3 + px[1] * 5 + px[2] * 7 + px[3] * 11) % 64; memcpy(index[idx], px, 4); } memcpy(q->pixels + px_pos, px, 4); px_pos += 4; } // Check end marker if (memcmp(data + p, "\x00\x00\x00\x00\x00\x00\x00\x01", 8) != 0) { free(q->pixels); return -1; } return 0; } void qoi_print_properties(const QOI_t* q) { printf("QOI File Properties:\n"); printf("Magic bytes: qoif\n"); printf("Width: %u\n", q->width); printf("Height: %u\n", q->height); printf("Channels: %u\n", q->channels); printf("Colorspace: %u\n", q->colorspace); } int qoi_encode(const QOI_t* q, uint8_t** out_data, int* out_size) { if (!q->pixels) return -1; int max_size = q->width * q->height * (q->channels + 1) + 14 + 8; uint8_t* data = (uint8_t*)malloc(max_size); if (!data) return -1; int p = 0; data[p++] = 'q'; data[p++] = 'o'; data[p++] = 'i'; data[p++] = 'f'; data[p++] = (q->width >> 24) & 0xff; data[p++] = (q->width >> 16) & 0xff; data[p++] = (q->width >> 8) & 0xff; data[p++] = q->width & 0xff; data[p++] = (q->height >> 24) & 0xff; data[p++] = (q->height >> 16) & 0xff; data[p++] = (q->height >> 8) & 0xff; data[p++] = q->height & 0xff; data[p++] = q->channels; data[p++] = q->colorspace; uint8_t index[64][4] = {0}; uint8_t px[4] = {0, 0, 0, 255}; int run = 0; int px_len = q->width * q->height * 4; for (int px_pos = 0; px_pos < px_len; px_pos += 4) { uint8_t px_new[4]; memcpy(px_new, q->pixels + px_pos, 4); if (memcmp(px_new, px, 4) == 0) { run++; if (run == 62 || px_pos + 4 == px_len) { data[p++] = 0xc0 | (run - 1); run = 0; } continue; } if (run > 0) { data[p++] = 0xc0 | (run - 1); run = 0; } int idx = (px_new[0] * 3 + px_new[1] * 5 + px_new[2] * 7 + px_new[3] * 11) % 64; if (memcmp(index[idx], px_new, 4) == 0) { data[p++] = 0x00 | idx; } else { memcpy(index[idx], px_new, 4); if (px_new[3] == px[3]) { int dr = px_new[0] - px[0]; int dg = px_new[1] - px[1]; int db = px_new[2] - px[2]; if (dr >= -2 && dr <= 1 && dg >= -2 && dg <= 1 && db >= -2 && db <= 1) { data[p++] = 0x40 | ((dr + 2) << 4) | ((dg + 2) << 2) | (db + 2); } else if (dg >= -32 && dg <= 31 && dr - dg >= -8 && dr - dg <= 7 && db - dg >= -8 && db - dg <= 7) { data[p++] = 0x80 | (dg + 32); data[p++] = ((dr - dg + 8) << 4) | (db - dg + 8); } else { data[p++] = 0xfe; data[p++] = px_new[0]; data[p++] = px_new[1]; data[p++] = px_new[2]; } } else { data[p++] = 0xff; data[p++] = px_new[0]; data[p++] = px_new[1]; data[p++] = px_new[2]; data[p++] = px_new[3]; } } memcpy(px, px_new, 4); } memset(data + p, 0, 7); data[p + 7] = 1; p += 8; *out_data = data; *out_size = p; return 0; } int qoi_save(const QOI_t* q, const char* filename) { uint8_t* data; int size; if (qoi_encode(q, &data, &size) != 0) return -1; FILE* f = fopen(filename, "wb"); if (!f) { free(data); return -1; } fwrite(data, 1, size, f); fclose(f); free(data); return 0; } // Example usage: // int main() { // QOI_t* q = qoi_create(); // if (qoi_load(q, "example.qoi") == 0) { // qoi_print_properties(q); // qoi_save(q, "output.qoi"); // } // qoi_destroy(q); // return 0; // } // ===== end task-589 .QOI ===== // ===== task-011 .ACCDB [C++] ===== #include #include #include #include #include #include class AccdbFileHandler { private: std::string filepath; struct stat properties; public: AccdbFileHandler(const std::string& fp) : filepath(fp) { if (fp.substr(fp.find_last_of(".") + 1) != "accdb") { throw std::invalid_argument("File must be of .ACCDB format."); } std::ifstream file(fp, std::ios::binary); char header[21]; file.read(header, 21); char sig[4] = {0x00, 0x01, 0x00, 0x00}; char type[] = "Standard ACE DB"; if (std::memcmp(header, sig, 4) != 0 || std::memcmp(header + 4, type, 16) != 0) { throw std::invalid_argument("Invalid .ACCDB signature."); } if (stat(fp.c_str(), &properties) != 0) { throw std::runtime_error("Failed to retrieve file properties."); } } void printProperties() { std::cout << "File Size: " << properties.st_size << " bytes" << std::endl; std::cout << "Creation Time: " << std::ctime(&properties.st_ctime); std::cout << "Last Modification Time: " << std::ctime(&properties.st_mtime); std::cout << "Last Access Time: " << std::ctime(&properties.st_atime); std::cout << "File Mode: " << std::oct << properties.st_mode << std::endl; std::cout << "Owner User ID: " << properties.st_uid << std::endl; std::cout << "Group ID: " << properties.st_gid << std::endl; // Permissions can be derived from st_mode. } void setModificationTime(time_t newMtime) { struct utimbuf ut; ut.actime = properties.st_atime; ut.modtime = newMtime; utime(filepath.c_str(), &ut); stat(filepath.c_str(), &properties); } void setPermissions(mode_t newMode) { chmod(filepath.c_str(), newMode); stat(filepath.c_str(), &properties); } }; // ===== end task-011 .ACCDB ===== // ===== task-012 .ACCFT [C++] ===== #include #include #include #include #include #include class AccftHandler { private: std::string filepath; std::vector data; public: AccftHandler(const std::string& fp) : filepath(fp) {} void openAndRead() { if (filepath.substr(filepath.find_last_of(".") + 1) != "accft") { throw std::invalid_argument("Invalid .ACCFT file path."); } std::ifstream file(filepath, std::ios::binary); if (!file) { throw std::runtime_error("File not found."); } data.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); } void decode() { if (data.empty()) { throw std::runtime_error("File not read."); } std::cout << "Decoding not possible: Format specifications unavailable." << std::endl; // Example: Print hex preview std::cout << "Binary Preview (Hex, first 32 bytes): "; for (size_t i = 0; i < std::min(32, data.size()); ++i) { printf("%02X ", static_cast(data[i])); } std::cout << std::endl; } void write(const std::string& outputPath) { if (data.empty()) { throw std::runtime_error("No data to write."); } std::ofstream out(outputPath, std::ios::binary); out.write(data.data(), data.size()); std::cout << "File written to " << outputPath << std::endl; } void printProperties() { struct stat stats; if (stat(filepath.c_str(), &stats) != 0) { throw std::runtime_error("File not found."); } std::cout << "File Properties:" << std::endl; std::cout << " - Path: " << filepath << std::endl; std::cout << " - Size: " << stats.st_size << " bytes" << std::endl; std::cout << " - Created: " << std::asctime(std::localtime(&stats.st_ctime)); std::cout << " - Modified: " << std::asctime(std::localtime(&stats.st_mtime)); std::cout << " - MIME Type: application/msaccess" << std::endl; std::cout << " - Extension: .accft" << std::endl; } }; // Example usage: // int main() { // try { // AccftHandler handler("example.accft"); // handler.openAndRead(); // handler.printProperties(); // handler.decode(); // handler.write("output.accft"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-012 .ACCFT ===== // ===== task-013 .ACO [C] ===== #include #include #include #include #include // For wide chars typedef struct { uint16_t space; uint16_t w, x, y, z; } ColorEntry; typedef struct { ColorEntry base; wchar_t *name; // UTF-16 as wide char } ColorEntryV2; typedef struct { uint16_t v1_version; uint16_t v1_count; ColorEntry *v1_colors; uint16_t v2_version; uint16_t v2_count; ColorEntryV2 *v2_colors; } ACOHandler; void aco_init(ACOHandler *handler) { memset(handler, 0, sizeof(ACOHandler)); handler->v2_version = -1; } void aco_free(ACOHandler *handler) { free(handler->v1_colors); if (handler->v2_version != -1) { for (int i = 0; i < handler->v2_count; i++) { free(handler->v2_colors[i].name); } free(handler->v2_colors); } } int aco_read(ACOHandler *handler, const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) return -1; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); int offset = 0; // Helper to get big-endian uint16 #define GET_UINT16() ((data[offset] << 8) | data[offset + 1]); offset += 2 // Version 1 handler->v1_version = GET_UINT16(); handler->v1_count = GET_UINT16(); handler->v1_colors = malloc(sizeof(ColorEntry) * handler->v1_count); for (int i = 0; i < handler->v1_count; i++) { handler->v1_colors[i].space = GET_UINT16(); handler->v1_colors[i].w = GET_UINT16(); handler->v1_colors[i].x = GET_UINT16(); handler->v1_colors[i].y = GET_UINT16(); handler->v1_colors[i].z = GET_UINT16(); } // Version 2 if present if (offset < size) { handler->v2_version = GET_UINT16(); handler->v2_count = GET_UINT16(); handler->v2_colors = malloc(sizeof(ColorEntryV2) * handler->v2_count); for (int i = 0; i < handler->v2_count; i++) { handler->v2_colors[i].base.space = GET_UINT16(); handler->v2_colors[i].base.w = GET_UINT16(); handler->v2_colors[i].base.x = GET_UINT16(); handler->v2_colors[i].base.y = GET_UINT16(); handler->v2_colors[i].base.z = GET_UINT16(); uint16_t name_len = GET_UINT16(); handler->v2_colors[i].name = malloc(sizeof(wchar_t) * name_len); for (int j = 0; j < name_len; j++) { handler->v2_colors[i].name[j] = GET_UINT16(); } handler->v2_colors[i].name[name_len - 1] = 0; // Ensure null } } free(data); return 0; } void aco_print_properties(const ACOHandler *handler) { printf("ACO File Properties:\n\n"); printf("Version 1 Section:\n"); printf("- Version: %u\n", handler->v1_version); printf("- Color Count: %u\n", handler->v1_count); for (int i = 0; i < handler->v1_count; i++) { const ColorEntry *color = &handler->v1_colors[i]; printf(" Color %d:\n", i + 1); printf(" - Space: %u\n", color->space); printf(" - w: %u\n", color->w); printf(" - x: %u\n", color->x); printf(" - y: %u\n", color->y); printf(" - z: %u\n", color->z); } if (handler->v2_version != -1) { printf("\nVersion 2 Section:\n"); printf("- Version: %u\n", handler->v2_version); printf("- Color Count: %u\n", handler->v2_count); for (int i = 0; i < handler->v2_count; i++) { const ColorEntryV2 *color = &handler->v2_colors[i]; printf(" Color %d:\n", i + 1); printf(" - Space: %u\n", color->base.space); printf(" - w: %u\n", color->base.w); printf(" - x: %u\n", color->base.x); printf(" - y: %u\n", color->base.y); printf(" - z: %u\n", color->base.z); wprintf(L" - Name: %ls\n", color->name); } } } int aco_write(const ACOHandler *handler, const char *filename, int include_v2) { FILE *f = fopen(filename, "wb"); if (!f) return -1; // Helper to put big-endian uint16 #define PUT_UINT16(val) { uint8_t b[2] = {(val >> 8) & 0xFF, val & 0xFF}; fwrite(b, 1, 2, f); } // Write Version 1 PUT_UINT16(1); PUT_UINT16(handler->v1_count); for (int i = 0; i < handler->v1_count; i++) { const ColorEntry *color = &handler->v1_colors[i]; PUT_UINT16(color->space); PUT_UINT16(color->w); PUT_UINT16(color->x); PUT_UINT16(color->y); PUT_UINT16(color->z); } // Write Version 2 if requested if (include_v2 && handler->v2_version != -1) { PUT_UINT16(2); PUT_UINT16(handler->v2_count); for (int i = 0; i < handler->v2_count; i++) { const ColorEntryV2 *color = &handler->v2_colors[i]; PUT_UINT16(color->base.space); PUT_UINT16(color->base.w); PUT_UINT16(color->base.x); PUT_UINT16(color->base.y); PUT_UINT16(color->base.z); size_t name_len = wcslen(color->name) + 1; // Include null PUT_UINT16((uint16_t)name_len); for (size_t j = 0; j < name_len; j++) { PUT_UINT16(color->name[j]); } } } fclose(f); return 0; } // Example usage: // int main() { // ACOHandler handler; // aco_init(&handler); // aco_read(&handler, "example.aco"); // aco_print_properties(&handler); // aco_write(&handler, "output.aco", 1); // aco_free(&handler); // return 0; // } // ===== end task-013 .ACO ===== // ===== task-014 .ADT [C++] ===== #include #include #include #include class ADTParser { private: std::string filepath; std::vector data; public: ADTParser(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { std::cerr << "Failed to open file." << std::endl; return; } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(reinterpret_cast(data.data()), size); } void printProperties() { size_t offset = 0; int frameCount = 0; while (offset + 7 < data.size()) { uint16_t syncword = ((data[offset] << 8) | data[offset + 1]) >> 4; if (syncword != 0xFFF) { offset++; continue; } frameCount++; uint8_t byte1 = data[offset + 1]; uint8_t byte2 = data[offset + 2]; uint8_t byte3 = data[offset + 3]; uint8_t byte4 = data[offset + 4]; uint8_t byte5 = data[offset + 5]; uint8_t byte6 = data[offset + 6]; int id = (byte1 >> 3) & 0x01; int layer = (byte1 >> 1) & 0x03; int protectionAbsent = byte1 & 0x01; int profile = (byte2 >> 6) & 0x03; int samplingFreqIndex = (byte2 >> 2) & 0x0F; int privateBit = (byte2 >> 1) & 0x01; int channelConfig = ((byte2 & 0x01) << 2) | ((byte3 >> 6) & 0x03); int originalCopy = (byte3 >> 5) & 0x01; int home = (byte3 >> 4) & 0x01; int copyrightIdBit = (byte3 >> 3) & 0x01; int copyrightIdStart = (byte3 >> 2) & 0x01; int frameLength = ((byte3 & 0x03) << 11) | (byte4 << 3) | ((byte5 >> 5) & 0x07); int bufferFullness = ((byte5 & 0x1F) << 6) | ((byte6 >> 2) & 0x3F); int numRawBlocks = byte6 & 0x03; uint16_t crc = 0; int headerSize = protectionAbsent ? 7 : 9; if (!protectionAbsent && offset + 9 <= data.size()) { crc = (data[offset + 7] << 8) | data[offset + 8]; } std::cout << "Frame " << frameCount << ":" << std::endl; std::cout << " Syncword: 0xFFF" << std::endl; std::cout << " ID: " << id << std::endl; std::cout << " Layer: " << layer << std::endl; std::cout << " Protection Absent: " << protectionAbsent << std::endl; std::cout << " Profile: " << profile << std::endl; std::cout << " Sampling Frequency Index: " << samplingFreqIndex << std::endl; std::cout << " Private Bit: " << privateBit << std::endl; std::cout << " Channel Configuration: " << channelConfig << std::endl; std::cout << " Original/Copy: " << originalCopy << std::endl; std::cout << " Home: " << home << std::endl; std::cout << " Copyright Identification Bit: " << copyrightIdBit << std::endl; std::cout << " Copyright Identification Start: " << copyrightIdStart << std::endl; std::cout << " Frame Length: " << frameLength << std::endl; std::cout << " Buffer Fullness: " << bufferFullness << std::endl; std::cout << " Number of Raw Data Blocks: " << (numRawBlocks + 1) << std::endl; if (!protectionAbsent) { std::cout << " CRC: 0x" << std::hex << crc << std::dec << std::endl; } std::cout << std::endl; if (frameLength < headerSize) break; offset += frameLength; } } void write(const std::string& outputPath) { std::ofstream file(outputPath, std::ios::binary); if (!file) { std::cerr << "Failed to write file." << std::endl; return; } file.write(reinterpret_cast(data.data()), data.size()); } }; int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Usage: " << argv[0] << " " << std::endl; return 1; } ADTParser parser(argv[1]); parser.read(); parser.printProperties(); parser.write("output.adt"); return 0; } // ===== end task-014 .ADT ===== // ===== task-015 .ADX [C++] ===== #include #include #include #include class AdxFile { private: std::string filepath; uint16_t magic; uint16_t dataOffset; uint8_t encodingType; uint8_t blockSize; uint8_t sampleBitdepth; uint8_t channelCount; uint32_t sampleRate; uint32_t totalSamples; uint16_t highpassFreq; uint8_t version; uint8_t flags; uint32_t loopFlag; uint32_t loopStartSample; uint32_t loopStartByte; uint32_t loopEndSample; uint32_t loopEndByte; std::string copyrightStr; char* audioData; size_t audioSize; public: AdxFile(const std::string& fp) : filepath(fp), audioData(nullptr), audioSize(0) {} ~AdxFile() { delete[] audioData; } void read() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); size_t size = file.tellg(); file.seekg(0); char* buffer = new char[size]; file.read(buffer, size); magic = *reinterpret_cast(buffer); dataOffset = *reinterpret_cast(buffer + 2); encodingType = *(buffer + 4); blockSize = *(buffer + 5); sampleBitdepth = *(buffer + 6); channelCount = *(buffer + 7); sampleRate = *reinterpret_cast(buffer + 8); totalSamples = *reinterpret_cast(buffer + 12); highpassFreq = *reinterpret_cast(buffer + 16); version = *(buffer + 18); flags = *(buffer + 19); if (version == 4) { loopFlag = *reinterpret_cast(buffer + 36); loopStartSample = *reinterpret_cast(buffer + 40); loopStartByte = *reinterpret_cast(buffer + 44); loopEndSample = *reinterpret_cast(buffer + 48); loopEndByte = *reinterpret_cast(buffer + 52); } char copyBuf[7] = {0}; memcpy(copyBuf, buffer + dataOffset - 4, 6); copyrightStr = std::string(copyBuf); audioSize = size - (dataOffset + 2); audioData = new char[audioSize]; memcpy(audioData, buffer + dataOffset + 2, audioSize); delete[] buffer; printProperties(); } void printProperties() { std::cout << "Magic Number: 0x" << std::hex << magic << std::dec << std::endl; std::cout << "Data Offset: " << dataOffset << std::endl; std::cout << "Encoding Type: 0x" << std::hex << static_cast(encodingType) << std::dec << std::endl; std::cout << "Block Size: " << static_cast(blockSize) << std::endl; std::cout << "Sample Bitdepth: " << static_cast(sampleBitdepth) << std::endl; std::cout << "Channel Count: " << static_cast(channelCount) << std::endl; std::cout << "Sample Rate: " << sampleRate << std::endl; std::cout << "Total Samples: " << totalSamples << std::endl; std::cout << "Highpass Frequency: " << highpassFreq << std::endl; std::cout << "Version: 0x" << std::hex << static_cast(version) << std::dec << std::endl; std::cout << "Flags: 0x" << std::hex << static_cast(flags) << std::dec << std::endl; if (version == 4) { std::cout << "Loop Flag: " << loopFlag << std::endl; std::cout << "Loop Start Sample: " << loopStartSample << std::endl; std::cout << "Loop Start Byte: " << loopStartByte << std::endl; std::cout << "Loop End Sample: " << loopEndSample << std::endl; std::cout << "Loop End Byte: " << loopEndByte << std::endl; } std::cout << "Copyright String: " << copyrightStr << std::endl; } void write(const std::string& newFilepath) { std::ofstream file(newFilepath, std::ios::binary); uint16_t tempMagic = 0x8000; file.write(reinterpret_cast(&tempMagic), 2); uint16_t tempOffset = 0x20; file.write(reinterpret_cast(&tempOffset), 2); uint8_t tempType = 0x03; file.write(reinterpret_cast(&tempType), 1); uint8_t tempBlock = 18; file.write(reinterpret_cast(&tempBlock), 1); uint8_t tempBit = 4; file.write(reinterpret_cast(&tempBit), 1); uint8_t tempChan = 1; file.write(reinterpret_cast(&tempChan), 1); uint32_t tempRate = 44100; file.write(reinterpret_cast(&tempRate), 4); uint32_t tempSamples = 0; file.write(reinterpret_cast(&tempSamples), 4); uint16_t tempHigh = 500; file.write(reinterpret_cast(&tempHigh), 2); uint8_t tempVer = 3; file.write(reinterpret_cast(&tempVer), 1); uint8_t tempFlags = 0; file.write(reinterpret_cast(&tempFlags), 1); char padding[4] = {0}; file.write(padding, 4); file.write("(c)CRI", 6); if (audioData) file.write(audioData, audioSize); } }; // Example usage // int main() { // AdxFile adx("path/to/file.adx"); // adx.read(); // adx.write("path/to/new_file.adx"); // return 0; // } // ===== end task-015 .ADX ===== // ===== task-016 .ADZ [C] ===== #include #include #include #include #include typedef struct { unsigned char *data; size_t size; // Properties map simulation (array of key-value) char *keys[50]; char *values[50]; int prop_count; } ADZFile; void adz_init(ADZFile *adz, const char *filename) { FILE *f = fopen(filename, "rb"); fseek(f, 0, SEEK_END); size_t compressed_size = ftell(f); fseek(f, 0, SEEK_SET); unsigned char *compressed = malloc(compressed_size); fread(compressed, 1, compressed_size, f); fclose(f); uLongf dest_len = 901120; // Typical ADF size adz->data = malloc(dest_len); if (uncompress(adz->data, &dest_len, compressed, compressed_size) != Z_OK) { fprintf(stderr, "Decompression failed\n"); free(compressed); return; } adz->size = dest_len; free(compressed); adz->prop_count = 0; // Parse properties unsigned int *dv = (unsigned int *)adz->data; char buf[256]; // Boot block snprintf(buf, 256, "%c%c%c", adz->data[0], adz->data[1], adz->data[2]); adz->keys[adz->prop_count] = strdup("DOS Identifier"); adz->values[adz->prop_count++] = strdup(buf); unsigned char dos_flags = adz->data[3]; snprintf(buf, 256, "%u", dos_flags); adz->keys[adz->prop_count] = strdup("DOS Flags"); adz->values[adz->prop_count++] = strdup(buf); char fs_type[32] = ""; strcat(fs_type, (dos_flags & 1) ? "FFS" : "OFS"); if (dos_flags & 2) strcat(fs_type, " INTL"); if (dos_flags & 4) strcat(fs_type, " DIRC"); adz->keys[adz->prop_count] = strdup("File System Type"); adz->values[adz->prop_count++] = strdup(fs_type); snprintf(buf, 256, "%08x", dv[1]); adz->keys[adz->prop_count] = strdup("Boot Checksum"); adz->values[adz->prop_count++] = strdup(buf); unsigned int root_block = dv[2]; snprintf(buf, 256, "%u", root_block); adz->keys[adz->prop_count] = strdup("Root Block Pointer"); adz->values[adz->prop_count++] = strdup(buf); int boot_code_present = 0; for (int i = 12; i < 1024; i++) { if (adz->data[i] != 0) { boot_code_present = 1; break; } } snprintf(buf, 256, "%s", boot_code_present ? "true" : "false"); adz->keys[adz->prop_count] = strdup("Boot Code Present"); adz->values[adz->prop_count++] = strdup(buf); unsigned int *root_dv = (unsigned int *)(adz->data + root_block * 512); snprintf(buf, 256, "%u", root_dv[0]); adz->keys[adz->prop_count] = strdup("Type"); adz->values[adz->prop_count++] = strdup(buf); snprintf(buf, 256, "%u", root_dv[1]); adz->keys[adz->prop_count] = strdup("Header Key"); adz->values[adz->prop_count++] = strdup(buf); snprintf(buf, 256, "%u", root_dv[3]); adz->keys[adz->prop_count] = strdup("Hash Table Size"); adz->values[adz->prop_count++] = strdup(buf); snprintf(buf, 256, "%u", root_dv[4]); adz->keys[adz->prop_count] = strdup("First Data"); adz->values[adz->prop_count++] = strdup(buf); snprintf(buf, 256, "%08x", root_dv[5]); adz->keys[adz->prop_count] = strdup("Root Checksum"); adz->values[adz->prop_count++] = strdup(buf); char ht_buf[1024] = ""; for (int i = 0; i < root_dv[3]; i++) { if (root_dv[6 + i] != 0) { char temp[16]; snprintf(temp, 16, "%u ", root_dv[6 + i]); strcat(ht_buf, temp); } } adz->keys[adz->prop_count] = strdup("Hash Table"); adz->values[adz->prop_count++] = strdup(ht_buf); int bitmap_flag = (int)root_dv[78 -1]; // Adjust for index snprintf(buf, 256, "%d", bitmap_flag); adz->keys[adz->prop_count] = strdup("Bitmap Flag"); adz->values[adz->prop_count++] = strdup(buf); char bm_pages_buf[1024] = ""; unsigned int bm_pages[25]; for (int i = 0; i < 25; i++) { bm_pages[i] = root_dv[78 + i]; if (bm_pages[i] != 0) { char temp[16]; snprintf(temp, 16, "%u ", bm_pages[i]); strcat(bm_pages_buf, temp); } } adz->keys[adz->prop_count] = strdup("Bitmap Pages"); adz->values[adz->prop_count++] = strdup(bm_pages_buf); snprintf(buf, 256, "%u", root_dv[103]); adz->keys[adz->prop_count] = strdup("Bitmap Extension"); adz->values[adz->prop_count++] = strdup(buf); unsigned int r_days = root_dv[105]; unsigned int r_mins = root_dv[106]; unsigned int r_ticks = root_dv[107]; struct tm tm = {0}; tm.tm_year = 78; tm.tm_mon = 0; tm.tm_mday = 1; time_t r_time = mktime(&tm) + r_days * 86400 + r_mins * 60 + r_ticks / 50; strftime(buf, 64, "%Y-%m-%d", localtime(&r_time)); adz->keys[adz->prop_count] = strdup("Last Root Alteration Date"); adz->values[adz->prop_count++] = strdup(buf); unsigned char name_len = adz->data[root_block * 512 + 432]; snprintf(buf, 256, "%u", name_len); adz->keys[adz->prop_count] = strdup("Volume Name Length"); adz->values[adz->prop_count++] = strdup(buf); char volume_name[31]; memcpy(volume_name, adz->data + root_block * 512 + 433, name_len); volume_name[name_len] = '\0'; adz->keys[adz->prop_count] = strdup("Volume Name"); adz->values[adz->prop_count++] = strdup(volume_name); unsigned int v_days = root_dv[118]; unsigned int v_mins = root_dv[119]; unsigned int v_ticks = root_dv[120]; time_t v_time = mktime(&tm) + v_days * 86400 + v_mins * 60 + v_ticks / 50; strftime(buf, 64, "%Y-%m-%d", localtime(&v_time)); adz->keys[adz->prop_count] = strdup("Last Volume Alteration Date"); adz->values[adz->prop_count++] = strdup(buf); unsigned int c_days = root_dv[121]; unsigned int c_mins = root_dv[122]; unsigned int c_ticks = root_dv[123]; time_t c_time = mktime(&tm) + c_days * 86400 + c_mins * 60 + c_ticks / 50; strftime(buf, 64, "%Y-%m-%d", localtime(&c_time)); adz->keys[adz->prop_count] = strdup("Creation Date"); adz->values[adz->prop_count++] = strdup(buf); snprintf(buf, 256, "%u", root_dv[124]); adz->keys[adz->prop_count] = strdup("First Directory Cache Block"); adz->values[adz->prop_count++] = strdup(buf); snprintf(buf, 256, "%u", root_dv[127]); adz->keys[adz->prop_count] = strdup("Secondary Type"); adz->values[adz->prop_count++] = strdup(buf); // Bitmap block unsigned int bitmap_block = bm_pages[0]; unsigned int *bitmap_dv = (unsigned int *)(adz->data + bitmap_block * 512); snprintf(buf, 256, "%08x", bitmap_dv[0]); adz->keys[adz->prop_count] = strdup("Bitmap Checksum"); adz->values[adz->prop_count++] = strdup(buf); int free_blocks = 0; for (int i = 1; i < 128; i++) { // 127 words unsigned int word = bitmap_dv[i]; while (word) { free_blocks += word & 1; word >>= 1; } } snprintf(buf, 256, "%d", free_blocks); adz->keys[adz->prop_count] = strdup("Free Blocks"); adz->values[adz->prop_count++] = strdup(buf); snprintf(buf, 256, "%d", 1760 - free_blocks - 2); adz->keys[adz->prop_count] = strdup("Allocated Blocks"); adz->values[adz->prop_count++] = strdup(buf); } void adz_print_properties(ADZFile *adz) { for (int i = 0; i < adz->prop_count; i++) { printf("%s: %s\n", adz->keys[i], adz->values[i]); } } void adz_write(ADZFile *adz, const char *filename) { uLongf compressed_len = compressBound(adz->size); unsigned char *compressed = malloc(compressed_len); if (compress(compressed, &compressed_len, adz->data, adz->size) != Z_OK) { fprintf(stderr, "Compression failed\n"); free(compressed); return; } FILE *f = fopen(filename, "wb"); fwrite(compressed, 1, compressed_len, f); fclose(f); free(compressed); } void adz_free(ADZFile *adz) { free(adz->data); for (int i = 0; i < adz->prop_count; i++) { free(adz->keys[i]); free(adz->values[i]); } } // Example: ADZFile adz; adz_init(&adz, "example.adz"); adz_print_properties(&adz); adz_write(&adz, "modified.adz"); adz_free(&adz); // ===== end task-016 .ADZ ===== // ===== task-017 .AGDA [C] ===== #include #include #include #include #include #include #include struct AgdaFileHandler { char *filename; char *content; // Raw bytes char *decoded; // Assuming UTF-8, same as content for simplicity size_t size; }; struct AgdaFileHandler* create_handler(const char *filename) { size_t len = strlen(filename); if (len < 5 || strcasecmp(filename + len - 5, ".agda") != 0) { fprintf(stderr, "File must have .AGDA extension.\n"); exit(1); } struct AgdaFileHandler *handler = malloc(sizeof(struct AgdaFileHandler)); handler->filename = strdup(filename); handler->content = NULL; handler->decoded = NULL; handler->size = 0; return handler; } void read_and_decode(struct AgdaFileHandler *handler) { int fd = open(handler->filename, O_RDONLY); if (fd == -1) { perror("open"); exit(1); } struct stat st; fstat(fd, &st); handler->size = st.st_size; handler->content = malloc(handler->size + 1); read(fd, handler->content, handler->size); handler->content[handler->size] = '\0'; handler->decoded = handler->content; // UTF-8 decoding not needed for printing close(fd); } void print_properties(struct AgdaFileHandler *handler) { struct stat st; if (stat(handler->filename, &st) == -1) { perror("stat"); exit(1); } printf("dev: %ld\n", (long)st.st_dev); printf("ino: %ld\n", (long)st.st_ino); printf("mode: %o\n", (unsigned int)st.st_mode); printf("nlink: %ld\n", (long)st.st_nlink); printf("uid: %ld\n", (long)st.st_uid); printf("gid: %ld\n", (long)st.st_gid); printf("rdev: %ld\n", (long)st.st_rdev); printf("size: %ld\n", (long)st.st_size); printf("blksize: %ld\n", (long)st.st_blksize); printf("blocks: %ld\n", (long)st.st_blocks); printf("atime: %ld\n", (long)st.st_atime); printf("mtime: %ld\n", (long)st.st_mtime); printf("ctime: %ld\n", (long)st.st_ctime); } void write_file(struct AgdaFileHandler *handler, const char *new_content) { FILE *f = fopen(handler->filename, "w"); if (f == NULL) { perror("fopen"); exit(1); } const char *content_to_write = new_content ? new_content : handler->decoded; fprintf(f, "%s", content_to_write); fclose(f); } void destroy_handler(struct AgdaFileHandler *handler) { free(handler->filename); free(handler->content); free(handler); } // ===== end task-017 .AGDA ===== // ===== task-018 .AGR [C++] ===== #include #include #include #include #include class AGRFileHandler { private: std::string filepath; std::vector> properties; public: AGRFileHandler(const std::string& fp) : filepath(fp) {} void readAndDecode() { std::ifstream file(filepath); if (!file.is_open()) { throw std::runtime_error("File " + filepath + " not found."); } properties.clear(); std::string line; while (std::getline(file, line)) { std::istringstream iss(line); std::string token; iss >> token; if (token.starts_with('@')) { std::string command = token.substr(1); std::string value; std::getline(iss, value); value.erase(0, value.find_first_not_of(" \t")); // Trim leading whitespace properties.emplace_back(command, value); } } file.close(); } void printProperties() const { if (properties.empty()) { std::cout << "No properties loaded. Call readAndDecode() first." << std::endl; return; } std::cout << "Properties from .AGR file:" << std::endl; for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& newFilepath = "") const { std::string targetPath = newFilepath.empty() ? filepath : newFilepath; std::ofstream outFile(targetPath); if (!outFile.is_open()) { throw std::runtime_error("Unable to write to " + targetPath); } for (const auto& prop : properties) { outFile << "@" << prop.first << " " << prop.second << std::endl; } outFile.close(); std::cout << "File written to " << targetPath << std::endl; } }; // Example usage: // int main() { // try { // AGRFileHandler handler("example.agr"); // handler.readAndDecode(); // handler.printProperties(); // handler.write("modified.agr"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-018 .AGR ===== // ===== task-019 .AHK [C] ===== #include #include #include #include #include #include #include typedef struct { char *filepath; struct stat stats; } AhkFileHandler; void init_ahk_handler(AhkFileHandler *handler, const char *filepath) { handler->filepath = strdup(filepath); if (strstr(handler->filepath, ".ahk") != handler->filepath + strlen(handler->filepath) - 4) { fprintf(stderr, "File must have .ahk extension\n"); exit(1); } if (stat(handler->filepath, &handler->stats) != 0) { perror("stat"); exit(1); } } void read_and_print_properties(AhkFileHandler *handler) { if (stat(handler->filepath, &handler->stats) != 0) { perror("stat"); return; } printf("File Name: %s\n", handler->filepath); printf("File Size: %ld\n", handler->stats.st_size); printf("Last Access Time: %s", ctime(&handler->stats.st_atime)); printf("Last Modification Time: %s", ctime(&handler->stats.st_mtime)); printf("Creation Time: %s", ctime(&handler->stats.st_ctime)); printf("Permissions: %o\n", handler->stats.st_mode & 0777); printf("User ID: %d\n", handler->stats.st_uid); printf("Group ID: %d\n", handler->stats.st_gid); } void write_properties(AhkFileHandler *handler, time_t atime, time_t mtime, mode_t permissions) { struct utimbuf times = {atime, mtime}; if (atime != -1 && mtime != -1) { if (utime(handler->filepath, ×) != 0) { perror("utime"); } } if (permissions != -1) { if (chmod(handler->filepath, permissions) != 0) { perror("chmod"); } } stat(handler->filepath, &handler->stats); // Refresh } void free_ahk_handler(AhkFileHandler *handler) { free(handler->filepath); } // Example usage: // int main() { // AhkFileHandler handler; // init_ahk_handler(&handler, "example.ahk"); // read_and_print_properties(&handler); // time_t now = time(NULL); // write_properties(&handler, now, now, 0644); // free_ahk_handler(&handler); // return 0; // } // ===== end task-019 .AHK ===== // ===== task-020 .AI [C++] ===== #include #include #include #include #include #include class AIFileHandler { private: std::string filepath; std::string content; std::map header; std::vector> layers; // Simplified for C++ std::vector palettes; std::vector images; std::vector> texts; std::vector customColors; std::vector patterns; std::vector overprints; int groups; int clippings; std::vector guides; std::vector objectTags; std::map attributes; bool nonPrinting; std::string byteOrder; std::string encoding; public: AIFileHandler(const std::string& fp) : filepath(fp), groups(0), clippings(0), nonPrinting(false), byteOrder("big-endian (assumed for binary sections)"), encoding("ASCII with platform specifics") {} void readDecode() { std::ifstream file(filepath); std::stringstream ss; ss << file.rdbuf(); content = ss.str(); parseProperties(); } void parseProperties() { std::stringstream ss(content); std::string line; std::map currentLayer; bool inLayer = false; bool inPalette = false; bool inNonPrinting = false; while (std::getline(ss, line)) { // Trim line (simplified) size_t start = line.find_first_not_of(" \t"); if (start == std::string::npos) continue; line = line.substr(start); size_t end = line.find_last_not_of(" \t"); line = line.substr(0, end + 1); // Header if (line.rfind("%%Creator:", 0) == 0) header["creator"] = line.substr(10); else if (line.rfind("%%For:", 0) == 0) header["for"] = line.substr(6); else if (line.rfind("%%Title:", 0) == 0) header["title"] = line.substr(8); else if (line.rfind("%%CreationDate:", 0) == 0) header["creationDate"] = line.substr(15); else if (line.rfind("%%DocumentProcSets:", 0) == 0) header["documentProcSets"] = line.substr(19); else if (line.rfind("%%DocumentSuppliedProcSets:", 0) == 0) header["documentSuppliedProcSets"] = line.substr(27); else if (line.rfind("%%DocumentFonts:", 0) == 0) header["documentFonts"] = line.substr(16); else if (line.rfind("%%BoundingBox:", 0) == 0) header["boundingBox"] = line.substr(14); else if (line.rfind("%%TemplateBox:", 0) == 0) header["templateBox"] = line.substr(14); else if (line.rfind("%AI5_FileFormat", 0) == 0) header["aiFileFormat"] = line.substr(15); // Layer (simplified parsing) if (line == "%AI5_BeginLayer") inLayer = true; if (inLayer && line.rfind("Lb", 0) == 0) { currentLayer["properties"] = line.substr(2); layers.push_back(currentLayer); currentLayer.clear(); } if (inLayer && line.rfind("Ln", 0) == 0) layers.back()["name"] = line.substr(2); if (line == "%AI5_EndLayer") inLayer = false; // Palette if (line == "%AI5_BeginPalette") inPalette = true; if (inPalette && line.rfind("Pb", 0) == 0) palettes.push_back(line.substr(2)); if (line == "%AI5_EndPalette") inPalette = false; // Image if (line.rfind("XI", 0) == 0 || line.rfind("XF", 0) == 0) images.push_back(line); // Text if (line.rfind("To", 0) == 0) { std::map text; text["type"] = line.substr(2); texts.push_back(text); } if (line.rfind("Tf", 0) == 0) if (!texts.empty()) texts.back()["font"] = line.substr(2); // Custom Color if (line.rfind("Xx", 0) == 0 || line.rfind("XX", 0) == 0) customColors.push_back(line); // Pattern if (line.rfind("p", 0) == 0 || line.rfind("P", 0) == 0) patterns.push_back(line); // Overprint if (line.rfind("O", 0) == 0 || line.rfind("R", 0) == 0) overprints.push_back(line); // Group and Clipping if (line == "u") ++groups; if (line == "U") --groups; if (line == "q") ++clippings; if (line == "Q") --clippings; // Guide if (line.find('*') != std::string::npos) guides.push_back(line); // Object Tag if (line.rfind("XT", 0) == 0) objectTags.push_back(line); // Attributes if (line.rfind("Ap", 0) == 0) attributes["showCenter"] = line.substr(2); if (line.rfind("Ar", 0) == 0) attributes["resolution"] = line.substr(2); // Non-Printing if (line == "%AI5_Begin_NonPrinting") inNonPrinting = true; if (line == "%AI5_End_NonPrinting--") inNonPrinting = false; } nonPrinting = inNonPrinting; } void printProperties() { std::cout << "{\n"; std::cout << " \"header\": {\n"; for (const auto& kv : header) { std::cout << " \"" << kv.first << "\": \"" << kv.second << "\",\n"; } std::cout << " },\n"; std::cout << " \"layers\": [ /* simplified */ ],\n"; // Omit detailed print for brevity std::cout << " \"palettes\": [ /* ... */ ],\n"; std::cout << " \"images\": [ /* ... */ ],\n"; std::cout << " \"texts\": [ /* ... */ ],\n"; std::cout << " \"customColors\": [ /* ... */ ],\n"; std::cout << " \"patterns\": [ /* ... */ ],\n"; std::cout << " \"overprints\": [ /* ... */ ],\n"; std::cout << " \"groups\": " << groups << ",\n"; std::cout << " \"clippings\": " << clippings << ",\n"; std::cout << " \"guides\": [ /* ... */ ],\n"; std::cout << " \"objectTags\": [ /* ... */ ],\n"; std::cout << " \"attributes\": {\n"; for (const auto& kv : attributes) { std::cout << " \"" << kv.first << "\": \"" << kv.second << "\",\n"; } std::cout << " },\n"; std::cout << " \"nonPrinting\": " << (nonPrinting ? "true" : "false") << ",\n"; std::cout << " \"byteOrder\": \"" << byteOrder << "\",\n"; std::cout << " \"encoding\": \"" << encoding << "\"\n"; std::cout << "}\n"; } void write(const std::string& newFilepath = "") { std::string path = newFilepath.empty() ? filepath : newFilepath; std::ofstream out(path); out << content; } }; // Example usage: // int main() { // AIFileHandler handler("sample.ai"); // handler.readDecode(); // handler.printProperties(); // handler.write("output.ai"); // return 0; // } // ===== end task-020 .AI ===== // ===== task-021 .AIFC [C++] ===== #include #include #include #include #include #include #include #include class AIFCFile { private: std::map properties; // Use string for simplicity in print std::vector soundData; std::string toHex(const std::vector& data) { std::ostringstream oss; for (char c : data) { oss << std::hex << std::setw(2) << std::setfill('0') << (int)(unsigned char)c << " "; } std::string s = oss.str(); if (!s.empty()) s.pop_back(); return s; } int32_t readLong(std::ifstream& f) { int32_t val; f.read(reinterpret_cast(&val), 4); return __builtin_bswap32(val); } uint32_t readULong(std::ifstream& f) { uint32_t val; f.read(reinterpret_cast(&val), 4); return __builtin_bswap32(val); } int16_t readShort(std::ifstream& f) { int16_t val; f.read(reinterpret_cast(&val), 2); return __builtin_bswap16(val); } uint16_t readUShort(std::ifstream& f) { uint16_t val; f.read(reinterpret_cast(&val), 2); return __builtin_bswap16(val); } double readExtended(std::ifstream& f) { int16_t exp; f.read(reinterpret_cast(&exp), 2); exp = __builtin_bswap16(exp) - 16383; uint64_t mant = 0; f.read(reinterpret_cast(&mant), 8); mant = __builtin_bswap64(mant); return (mant / static_cast(1LL << 63)) * std::pow(2, exp); } std::string readID(std::ifstream& f) { char id[5] = {0}; f.read(id, 4); return std::string(id); } std::string readPString(std::ifstream& f) { uint8_t len; f.read(reinterpret_cast(&len), 1); std::string str(len, 0); f.read(&str[0], len); if (len % 2 == 1) { char pad; f.read(&pad, 1); } return str; } std::string readString(std::ifstream& f, int len) { std::string str(len, 0); f.read(&str[0], len); if (len % 2 == 1) { char pad; f.read(&pad, 1); } return str; } std::string readBytes(std::ifstream& f, int len) { std::vector bytes(len); f.read(bytes.data(), len); if (len % 2 == 1) { char pad; f.read(&pad, 1); } return toHex(bytes); } void parseChunk(std::ifstream& f, const std::string& ckID, int ckSize) { if (ckID == "FVER") { properties["formatVersionTimestamp"] = std::to_string(readULong(f)); } else if (ckID == "COMM") { properties["numChannels"] = std::to_string(readShort(f)); properties["numSampleFrames"] = std::to_string(readULong(f)); properties["sampleSize"] = std::to_string(readShort(f)); properties["sampleRate"] = std::to_string(readExtended(f)); properties["compressionType"] = readID(f); properties["compressionName"] = readPString(f); } else if (ckID == "SSND") { properties["soundDataOffset"] = std::to_string(readULong(f)); properties["soundDataBlockSize"] = std::to_string(readULong(f)); int dataSize = ckSize - 8; soundData.resize(dataSize); f.read(soundData.data(), dataSize); if (dataSize % 2 == 1) { char pad; f.read(&pad, 1); } } else if (ckID == "MARK") { uint16_t numMarkers = readUShort(f); std::ostringstream oss; oss << "["; for (int i = 0; i < numMarkers; ++i) { int16_t id = readShort(f); uint32_t pos = readULong(f); std::string name = readPString(f); oss << "{id:" << id << ", pos:" << pos << ", name:\"" << name << "\"}"; if (i < numMarkers - 1) oss << ", "; } oss << "]"; properties["markers"] = oss.str(); } else if (ckID == "COMT") { uint16_t numComments = readUShort(f); std::ostringstream oss; oss << "["; for (int i = 0; i < numComments; ++i) { uint32_t ts = readULong(f); int16_t marker = readShort(f); uint16_t count = readUShort(f); std::string text = readString(f, count); oss << "{ts:" << ts << ", marker:" << marker << ", text:\"" << text << "\"}"; if (i < numComments - 1) oss << ", "; } oss << "]"; properties["comments"] = oss.str(); } else if (ckID == "SAXL") { uint16_t numSaxels = readUShort(f); std::ostringstream oss; oss << "["; for (int i = 0; i < numSaxels; ++i) { int16_t id = readShort(f); uint16_t size = readUShort(f); std::string data = readBytes(f, size); oss << "{id:" << id << ", size:" << size << ", data:\"" << data << "\"}"; if (i < numSaxels - 1) oss << ", "; } oss << "]"; properties["saxels"] = oss.str(); } else if (ckID == "INST") { char baseNote, detune, lowNote, highNote, lowVel, highVel; f.read(&baseNote, 1); f.read(&detune, 1); f.read(&lowNote, 1); f.read(&highNote, 1); f.read(&lowVel, 1); f.read(&highVel, 1); properties["instrumentBaseNote"] = std::to_string(static_cast(baseNote)); properties["instrumentDetune"] = std::to_string(static_cast(detune)); properties["instrumentLowNote"] = std::to_string(static_cast(lowNote)); properties["instrumentHighNote"] = std::to_string(static_cast(highNote)); properties["instrumentLowVelocity"] = std::to_string(static_cast(lowVel)); properties["instrumentHighVelocity"] = std::to_string(static_cast(highVel)); properties["instrumentGain"] = std::to_string(readShort(f)); properties["sustainLoopPlayMode"] = std::to_string(readShort(f)); properties["sustainLoopBegin"] = std::to_string(readShort(f)); properties["sustainLoopEnd"] = std::to_string(readShort(f)); properties["releaseLoopPlayMode"] = std::to_string(readShort(f)); properties["releaseLoopBegin"] = std::to_string(readShort(f)); properties["releaseLoopEnd"] = std::to_string(readShort(f)); } else if (ckID == "MIDI") { std::string midi = readBytes(f, ckSize); std::string& curr = properties["midiData"]; if (!curr.empty()) curr += ", "; curr += "\"" + midi + "\""; if (curr.front() != '[') curr = "[" + curr + "]"; } else if (ckID == "AESD") { properties["aesData"] = readBytes(f, 24); } else if (ckID == "APPL") { std::string sig = readID(f); std::string data = readBytes(f, ckSize - 4); std::string& curr = properties["appSpecific"]; if (!curr.empty()) curr += ", "; curr += "{sig:\"" + sig + "\", data:\"" + data + "\"}"; if (curr.front() != '[') curr = "[" + curr + "]"; } else if (ckID == "NAME") { properties["soundName"] = readString(f, ckSize); } else if (ckID == "AUTH") { properties["author"] = readString(f, ckSize); } else if (ckID == "(c) ") { properties["copyright"] = readString(f, ckSize); } else if (ckID == "ANNO") { std::string anno = readString(f, ckSize); std::string& curr = properties["annotations"]; if (!curr.empty()) curr += ", "; curr += "\"" + anno + "\""; if (curr.front() != '[') curr = "[" + curr + "]"; } else { f.seekg(ckSize, std::ios::cur); if (ckSize % 2 == 1) { char pad; f.read(&pad, 1); } } } public: AIFCFile() { properties["markers"] = ""; properties["comments"] = ""; properties["saxels"] = ""; properties["midiData"] = ""; properties["appSpecific"] = ""; properties["annotations"] = ""; } void load(const std::string& filename) { std::ifstream f(filename, std::ios::binary); if (!f) { std::cout << "Cannot open file" << std::endl; return; } if (readID(f) != "FORM") { std::cout << "Not a valid AIFC file" << std::endl; return; } readLong(f); // form size if (readID(f) != "AIFC") { std::cout << "Not AIFC form type" << std::endl; return; } while (f) { std::string ckID = readID(f); if (f.eof()) break; int ckSize = readLong(f); parseChunk(f, ckID, ckSize); } } void printProperties() { for (const auto& p : properties) { if (!p.second.empty()) { std::cout << p.first << ": " << p.second << std::endl; } } } void save(const std::string& filename) { std::ofstream f(filename, std::ios::binary); if (!f) return; // Placeholder write, similar logic as above but for output // Implement writing each chunk based on properties // For brevity, stubbed as full implementation is lengthy } }; int main() { AIFCFile aifc; aifc.load("example.aifc"); aifc.printProperties(); aifc.save("output.aifc"); return 0; } #include #include #include #include #include #include class AIFCFile { public: uint32_t format_version_timestamp = 0; int16_t num_channels = 0; uint32_t num_sample_frames = 0; int16_t sample_size = 0; double sample_rate = 0.0; // Approximate char compression_type[4] = {0}; std::string compression_name; uint32_t sound_data_offset = 0; uint32_t sound_data_block_size = 0; struct Marker { int16_t id; uint32_t position; std::string name; }; std::vector markers; struct Comment { uint32_t timestamp; int16_t marker_id; std::string text; }; std::vector comments; struct Loop { int16_t play_mode = 0; int16_t begin = 0; int16_t end = 0; }; struct Instrument { uint8_t base_note = 0; int8_t detune = 0; uint8_t low_note = 0; uint8_t high_note = 0; uint8_t low_velocity = 0; uint8_t high_velocity = 0; int16_t gain = 0; Loop sustain_loop; Loop release_loop; } instrument; std::string name; std::string author; std::string copyright_str; std::vector annotations; uint8_t aes_data[24] = {0}; std::vector midi_data; struct AppSpecific { char signature[4]; std::vector data; }; std::vector app_specific; std::vector sound_data; AIFCFile() {} double read_extended(std::ifstream& f) { int16_t exp; uint32_t hi, lo; f.read(reinterpret_cast(&exp), 2); f.read(reinterpret_cast(&hi), 4); f.read(reinterpret_cast(&lo), 4); if (f.fail()) return 0.0; exp = __builtin_bswap16(exp); hi = __builtin_bswap32(hi); lo = __builtin_bswap32(lo); double mant = (static_cast(hi) * (1LL << 32) + lo) / pow(2, 63); return mant * pow(2, exp - 16383); } void write_extended(std::ofstream& f, double value) { if (value == 0.0) { char zeros[10] = {0}; f.write(zeros, 10); return; } bool sign = value < 0; value = std::abs(value); int exp = static_cast(std::floor(std::log2(value))) + 16383; double mant = value / std::pow(2, exp - 16383); uint32_t hi = static_cast(mant * (1LL << 31)); uint32_t lo = static_cast((mant * (1LL << 31) - hi) * (1LL << 32)); int16_t sign_exp = (sign ? 0x8000 : 0) | (exp & 0x7FFF); sign_exp = __builtin_bswap16(sign_exp); hi = __builtin_bswap32(hi); lo = __builtin_bswap32(lo); f.write(reinterpret_cast(&sign_exp), 2); f.write(reinterpret_cast(&hi), 4); f.write(reinterpret_cast(&lo), 4); } std::string read_pstring(std::ifstream& f) { uint8_t count; f.read(reinterpret_cast(&count), 1); std::string s(count, ' '); f.read(&s[0], count); if (count % 2 == 0) { char pad; f.read(&pad, 1); } return s; } void write_pstring(std::ofstream& f, const std::string& s) { uint8_t count = static_cast(s.size()); f.write(reinterpret_cast(&count), 1); f.write(s.c_str(), count); if (count % 2 == 0) { char pad = 0; f.write(&pad, 1); } } std::string read_string(std::ifstream& f, uint32_t size) { std::string s(size, ' '); f.read(&s[0], size); if (size % 2 == 1) { char pad; f.read(&pad, 1); } size_t null_pos = s.find('\0'); if (null_pos != std::string::npos) s.resize(null_pos); return s; } void write_string(std::ofstream& f, const std::string& s) { f.write(s.c_str(), s.size()); if (s.size() % 2 == 1) { char pad = 0; f.write(&pad, 1); } } void read(const std::string& file_path) { std::ifstream f(file_path, std::ios::binary); if (!f) throw std::runtime_error("Cannot open file"); char ck_id[5] = {0}; f.read(ck_id, 4); if (std::strcmp(ck_id, "FORM") != 0) throw std::runtime_error("Not AIFC"); uint32_t ck_size; f.read(reinterpret_cast(&ck_size), 4); ck_size = __builtin_bswap32(ck_size); f.read(ck_id, 4); if (std::strcmp(ck_id, "AIFC") != 0) throw std::runtime_error("Not AIFC"); auto start = f.tellg(); auto end_pos = start + static_cast(ck_size - 4); while (f.tellg() < end_pos) { f.read(ck_id, 4); if (ck_id[0] == 0) break; f.read(reinterpret_cast(&ck_size), 4); ck_size = __builtin_bswap32(ck_size); auto chunk_start = f.tellg(); if (std::strcmp(ck_id, "FVER") == 0) { f.read(reinterpret_cast(&format_version_timestamp), 4); format_version_timestamp = __builtin_bswap32(format_version_timestamp); } else if (std::strcmp(ck_id, "COMM") == 0) { f.read(reinterpret_cast(&num_channels), 2); num_channels = __builtin_bswap16(num_channels); f.read(reinterpret_cast(&num_sample_frames), 4); num_sample_frames = __builtin_bswap32(num_sample_frames); f.read(reinterpret_cast(&sample_size), 2); sample_size = __builtin_bswap16(sample_size); sample_rate = read_extended(f); f.read(compression_type, 4); compression_name = read_pstring(f); } else if (std::strcmp(ck_id, "SSND") == 0) { f.read(reinterpret_cast(&sound_data_offset), 4); sound_data_offset = __builtin_bswap32(sound_data_offset); f.read(reinterpret_cast(&sound_data_block_size), 4); sound_data_block_size = __builtin_bswap32(sound_data_block_size); f.seekg(sound_data_offset, std::ios::cur); uint32_t data_size = ck_size - 8 - sound_data_offset; sound_data.resize(data_size); f.read(reinterpret_cast(sound_data.data()), data_size); } else if (std::strcmp(ck_id, "MARK") == 0) { uint16_t num_markers; f.read(reinterpret_cast(&num_markers), 2); num_markers = __builtin_bswap16(num_markers); for (uint16_t i = 0; i < num_markers; ++i) { Marker m; f.read(reinterpret_cast(&m.id), 2); m.id = __builtin_bswap16(m.id); f.read(reinterpret_cast(&m.position), 4); m.position = __builtin_bswap32(m.position); m.name = read_pstring(f); markers.push_back(m); } } else if (std::strcmp(ck_id, "COMT") == 0) { uint16_t num_comm; f.read(reinterpret_cast(&num_comm), 2); num_comm = __builtin_bswap16(num_comm); for (uint16_t i = 0; i < num_comm; ++i) { Comment c; f.read(reinterpret_cast(&c.timestamp), 4); c.timestamp = __builtin_bswap32(c.timestamp); f.read(reinterpret_cast(&c.marker_id), 2); c.marker_id = __builtin_bswap16(c.marker_id); uint16_t count; f.read(reinterpret_cast(&count), 2); count = __builtin_bswap16(count); c.text = read_string(f, count); comments.push_back(c); } } else if (std::strcmp(ck_id, "INST") == 0) { f.read(reinterpret_cast(&instrument.base_note), 1); f.read(reinterpret_cast(&instrument.detune), 1); f.read(reinterpret_cast(&instrument.low_note), 1); f.read(reinterpret_cast(&instrument.high_note), 1); f.read(reinterpret_cast(&instrument.low_velocity), 1); f.read(reinterpret_cast(&instrument.high_velocity), 1); f.read(reinterpret_cast(&instrument.gain), 2); instrument.gain = __builtin_bswap16(instrument.gain); f.read(reinterpret_cast(&instrument.sustain_loop.play_mode), 2); instrument.sustain_loop.play_mode = __builtin_bswap16(instrument.sustain_loop.play_mode); f.read(reinterpret_cast(&instrument.sustain_loop.begin), 2); instrument.sustain_loop.begin = __builtin_bswap16(instrument.sustain_loop.begin); f.read(reinterpret_cast(&instrument.sustain_loop.end), 2); instrument.sustain_loop.end = __builtin_bswap16(instrument.sustain_loop.end); f.read(reinterpret_cast(&instrument.release_loop.play_mode), 2); instrument.release_loop.play_mode = __builtin_bswap16(instrument.release_loop.play_mode); f.read(reinterpret_cast(&instrument.release_loop.begin), 2); instrument.release_loop.begin = __builtin_bswap16(instrument.release_loop.begin); f.read(reinterpret_cast(&instrument.release_loop.end), 2); instrument.release_loop.end = __builtin_bswap16(instrument.release_loop.end); } else if (std::strcmp(ck_id, "NAME") == 0) { name = read_string(f, ck_size); } else if (std::strcmp(ck_id, "AUTH") == 0) { author = read_string(f, ck_size); } else if (std::strcmp(ck_id, "(c) ") == 0) { copyright_str = read_string(f, ck_size); } else if (std::strcmp(ck_id, "ANNO") == 0) { annotations.push_back(read_string(f, ck_size)); } else if (std::strcmp(ck_id, "AESD") == 0) { f.read(reinterpret_cast(aes_data), 24); } else if (std::strcmp(ck_id, "MIDI") == 0) { midi_data.resize(ck_size); f.read(reinterpret_cast(midi_data.data()), ck_size); } else if (std::strcmp(ck_id, "APPL") == 0) { AppSpecific app; f.read(app.signature, 4); app.data.resize(ck_size - 4); f.read(reinterpret_cast(app.data.data()), ck_size - 4); app_specific.push_back(app); } else { f.seekg(ck_size, std::ios::cur); } auto read_bytes = f.tellg() - chunk_start; if (static_cast(read_bytes) % 2 == 1) { char pad; f.read(&pad, 1); } } } void write(const std::string& file_path) { std::ofstream f(file_path, std::ios::binary); if (!f) throw std::runtime_error("Cannot open file"); std::vector chunks; // Helper to append chunk auto append_chunk = [&](const char* id, const std::vector& data) { uint32_t size_be = __builtin_bswap32(static_cast(data.size())); chunks.insert(chunks.end(), id, id + 4); chunks.insert(chunks.end(), reinterpret_cast(&size_be), reinterpret_cast(&size_be) + 4); chunks.insert(chunks.end(), data.begin(), data.end()); }; // FVER std::vector fver_data(4); uint32_t ts_be = __builtin_bswap32(format_version_timestamp); std::memcpy(fver_data.data(), &ts_be, 4); append_chunk("FVER", fver_data); // COMM std::vector comm_data; int16_t nc_be = __builtin_bswap16(num_channels); comm_data.insert(comm_data.end(), reinterpret_cast(&nc_be), reinterpret_cast(&nc_be) + 2); uint32_t nsf_be = __builtin_bswap32(num_sample_frames); comm_data.insert(comm_data.end(), reinterpret_cast(&nsf_be), reinterpret_cast(&nsf_be) + 4); int16_t ss_be = __builtin_bswap16(sample_size); comm_data.insert(comm_data.end(), reinterpret_cast(&ss_be), reinterpret_cast(&ss_be) + 2); // Extended std::vector ext(10); // Simulate write_extended by buffering std::stringstream ss; write_extended(ss, sample_rate); ss.read(reinterpret_cast(ext.data()), 10); comm_data.insert(comm_data.end(), ext.begin(), ext.end()); comm_data.insert(comm_data.end(), compression_type, compression_type + 4); // Pstring uint8_t count = static_cast(compression_name.size()); comm_data.push_back(count); comm_data.insert(comm_data.end(), compression_name.begin(), compression_name.end()); if (count % 2 == 0) comm_data.push_back(0); append_chunk("COMM", comm_data); // SSND std::vector ssnd_data; uint32_t off_be = __builtin_bswap32(sound_data_offset); ssnd_data.insert(ssnd_data.end(), reinterpret_cast(&off_be), reinterpret_cast(&off_be) + 4); uint32_t bs_be = __builtin_bswap32(sound_data_block_size); ssnd_data.insert(ssnd_data.end(), reinterpret_cast(&bs_be), reinterpret_cast(&bs_be) + 4); ssnd_data.insert(ssnd_data.end(), sound_data.begin(), sound_data.end()); if (ssnd_data.size() % 2 == 1) ssnd_data.push_back(0); append_chunk("SSND", ssnd_data); // MARK if (!markers.empty()) { std::vector mark_data; uint16_t num_be = __builtin_bswap16(static_cast(markers.size())); mark_data.insert(mark_data.end(), reinterpret_cast(&num_be), reinterpret_cast(&num_be) + 2); for (const auto& m : markers) { int16_t id_be = __builtin_bswap16(m.id); mark_data.insert(mark_data.end(), reinterpret_cast(&id_be), reinterpret_cast(&id_be) + 2); uint32_t pos_be = __builtin_bswap32(m.position); mark_data.insert(mark_data.end(), reinterpret_cast(&pos_be), reinterpret_cast(&pos_be) + 4); uint8_t cnt = static_cast(m.name.size()); mark_data.push_back(cnt); mark_data.insert(mark_data.end(), m.name.begin(), m.name.end()); if (cnt % 2 == 0) mark_data.push_back(0); } append_chunk("MARK", mark_data); } // COMT if (!comments.empty()) { std::vector comt_data; uint16_t num_be = __builtin_bswap16(static_cast(comments.size())); comt_data.insert(comt_data.end(), reinterpret_cast(&num_be), reinterpret_cast(&num_be) + 2); for (const auto& c : comments) { uint32_t ts_be = __builtin_bswap32(c.timestamp); comt_data.insert(comt_data.end(), reinterpret_cast(&ts_be), reinterpret_cast(&ts_be) + 4); int16_t mid_be = __builtin_bswap16(c.marker_id); comt_data.insert(comt_data.end(), reinterpret_cast(&mid_be), reinterpret_cast(&mid_be) + 2); uint16_t cnt_be = __builtin_bswap16(static_cast(c.text.size())); comt_data.insert(comt_data.end(), reinterpret_cast(&cnt_be), reinterpret_cast(&cnt_be) + 2); comt_data.insert(comt_data.end(), c.text.begin(), c.text.end()); if (c.text.size() % 2 == 1) comt_data.push_back(0); } append_chunk("COMT", comt_data); } // INST if (instrument.base_note != 0 || instrument.gain != 0 /* etc. */) { std::vector inst_data(20); inst_data[0] = instrument.base_note; inst_data[1] = static_cast(instrument.detune); inst_data[2] = instrument.low_note; inst_data[3] = instrument.high_note; inst_data[4] = instrument.low_velocity; inst_data[5] = instrument.high_velocity; int16_t gain_be = __builtin_bswap16(instrument.gain); std::memcpy(&inst_data[6], &gain_be, 2); int16_t pm_be = __builtin_bswap16(instrument.sustain_loop.play_mode); std::memcpy(&inst_data[8], &pm_be, 2); int16_t b_be = __builtin_bswap16(instrument.sustain_loop.begin); std::memcpy(&inst_data[10], &b_be, 2); int16_t e_be = __builtin_bswap16(instrument.sustain_loop.end); std::memcpy(&inst_data[12], &e_be, 2); pm_be = __builtin_bswap16(instrument.release_loop.play_mode); std::memcpy(&inst_data[14], &pm_be, 2); b_be = __builtin_bswap16(instrument.release_loop.begin); std::memcpy(&inst_data[16], &b_be, 2); e_be = __builtin_bswap16(instrument.release_loop.end); std::memcpy(&inst_data[18], &e_be, 2); append_chunk("INST", inst_data); } // NAME if (!name.empty()) { std::vector name_data(name.begin(), name.end()); if (name_data.size() % 2 == 1) name_data.push_back(0); append_chunk("NAME", name_data); } // AUTH if (!author.empty()) { std::vector auth_data(author.begin(), author.end()); if (auth_data.size() % 2 == 1) auth_data.push_back(0); append_chunk("AUTH", auth_data); } // (c) if (!copyright_str.empty()) { std::vector copy_data(copyright_str.begin(), copyright_str.end()); if (copy_data.size() % 2 == 1) copy_data.push_back(0); append_chunk("(c) ", copy_data); } // ANNO for (const auto& anno : annotations) { std::vector anno_data(anno.begin(), anno.end()); if (anno_data.size() % 2 == 1) anno_data.push_back(0); append_chunk("ANNO", anno_data); } // AESD if (std::any_of(std::begin(aes_data), std::end(aes_data), [](uint8_t b){return b != 0;})) { std::vector aes_vec(std::begin(aes_data), std::end(aes_data)); append_chunk("AESD", aes_vec); } // MIDI if (!midi_data.empty()) { std::vector midi_copy = midi_data; if (midi_copy.size() % 2 == 1) midi_copy.push_back(0); append_chunk("MIDI", midi_copy); } // APPL for (const auto& app : app_specific) { std::vector app_data; app_data.insert(app_data.end(), app.signature, app.signature + 4); app_data.insert(app_data.end(), app.data.begin(), app.data.end()); if (app_data.size() % 2 == 1) app_data.push_back(0); append_chunk("APPL", app_data); } // Write FORM f.write("FORM", 4); uint32_t form_size = static_cast(chunks.size()) + 4; // + AIFC uint32_t form_size_be = __builtin_bswap32(form_size); f.write(reinterpret_cast(&form_size_be), 4); f.write("AIFC", 4); f.write(reinterpret_cast(chunks.data()), chunks.size()); } }; // ===== end task-021 .AIFC ===== // ===== task-022 .AIFF [C++] ===== #include #include #include #include #include #include #include class AIFFHandler { private: std::string filename; std::map properties; std::vector audioData; double readExtended(std::ifstream& f) { char buf[10]; f.read(buf, 10); // Approximate to double double val; std::memcpy(&val, buf, 8); return val; } std::string readPString(std::ifstream& f) { uint8_t len; f.read(reinterpret_cast(&len), 1); std::string s(len, '\0'); f.read(&s[0], len); if ((len + 1) % 2 != 0) { char pad; f.read(&pad, 1); } return s; } public: AIFFHandler(const std::string& fn) : filename(fn) { std::ifstream f(filename, std::ios::binary); if (!f) throw std::runtime_error("File not found"); char id[5] = {}; f.read(id, 4); if (std::string(id) != "FORM") throw std::runtime_error("Not AIFF"); uint32_t formSize; f.read(reinterpret_cast(&formSize), 4); formSize = __builtin_bswap32(formSize); // To little-endian if needed, but assume big f.read(id, 4); properties["Form Type"] = std::string(id); while (f.tellg() < formSize + 8) { f.read(id, 4); std::string chunkID(id); uint32_t chunkSize; f.read(reinterpret_cast(&chunkSize), 4); chunkSize = __builtin_bswap32(chunkSize); std::streampos pos = f.tellg(); if (chunkID == "FVER") { uint32_t ver; f.read(reinterpret_cast(&ver), 4); ver = __builtin_bswap32(ver); properties["Format Version"] = ver; } else if (chunkID == "COMM") { uint16_t channels; f.read(reinterpret_cast(&channels), 2); channels = __builtin_bswap16(channels); properties["Number of Channels"] = channels; uint32_t frames; f.read(reinterpret_cast(&frames), 4); frames = __builtin_bswap32(frames); properties["Number of Sample Frames"] = frames; uint16_t size; f.read(reinterpret_cast(&size), 2); size = __builtin_bswap16(size); properties["Sample Size"] = size; properties["Sample Rate"] = readExtended(f); if (std::any_cast(properties["Form Type"]) == "AIFC") { f.read(id, 4); properties["Compression Type"] = std::string(id); properties["Compression Name"] = readPString(f); } } else if (chunkID == "SSND") { uint32_t offsetVal; f.read(reinterpret_cast(&offsetVal), 4); offsetVal = __builtin_bswap32(offsetVal); properties["Sound Data Offset"] = offsetVal; uint32_t blockSize; f.read(reinterpret_cast(&blockSize), 4); blockSize = __builtin_bswap32(blockSize); properties["Sound Data Block Size"] = blockSize; f.seekg(offsetVal, std::ios::cur); uint32_t dataSize = chunkSize - 8 - offsetVal; audioData.resize(dataSize); f.read(reinterpret_cast(audioData.data()), dataSize); } else if (chunkID == "MARK") { std::vector> markers; uint16_t num; f.read(reinterpret_cast(&num), 2); num = __builtin_bswap16(num); for (uint16_t i = 0; i < num; ++i) { std::map m; uint16_t mid; f.read(reinterpret_cast(&mid), 2); mid = __builtin_bswap16(mid); m["id"] = mid; uint32_t posVal; f.read(reinterpret_cast(&posVal), 4); posVal = __builtin_bswap32(posVal); m["position"] = posVal; m["name"] = readPString(f); markers.push_back(m); } properties["Markers"] = markers; } else if (chunkID == "INST") { int8_t val; f.read(reinterpret_cast(&val), 1); properties["Base Note"] = val; f.read(reinterpret_cast(&val), 1); properties["Detune"] = val; f.read(reinterpret_cast(&val), 1); properties["Low Note"] = val; f.read(reinterpret_cast(&val), 1); properties["High Note"] = val; f.read(reinterpret_cast(&val), 1); properties["Low Velocity"] = val; f.read(reinterpret_cast(&val), 1); properties["High Velocity"] = val; int16_t gain; f.read(reinterpret_cast(&gain), 2); gain = __builtin_bswap16(gain); properties["Gain"] = gain; std::map sLoop; int16_t pm; f.read(reinterpret_cast(&pm), 2); sLoop["playMode"] = __builtin_bswap16(pm); int16_t begin; f.read(reinterpret_cast(&begin), 2); sLoop["begin"] = __builtin_bswap16(begin); int16_t end; f.read(reinterpret_cast(&end), 2); sLoop["end"] = __builtin_bswap16(end); properties["Sustain Loop"] = sLoop; std::map rLoop; f.read(reinterpret_cast(&pm), 2); rLoop["playMode"] = __builtin_bswap16(pm); f.read(reinterpret_cast(&begin), 2); rLoop["begin"] = __builtin_bswap16(begin); f.read(reinterpret_cast(&end), 2); rLoop["end"] = __builtin_bswap16(end); properties["Release Loop"] = rLoop; } else if (chunkID == "COMT") { std::vector> comments; uint16_t num; f.read(reinterpret_cast(&num), 2); num = __builtin_bswap16(num); for (uint16_t i = 0; i < num; ++i) { std::map c; uint32_t ts; f.read(reinterpret_cast(&ts), 4); ts = __builtin_bswap32(ts); c["timestamp"] = ts; uint16_t mid; f.read(reinterpret_cast(&mid), 2); mid = __builtin_bswap16(mid); c["markerID"] = mid; uint16_t count; f.read(reinterpret_cast(&count), 2); count = __builtin_bswap16(count); std::string text(count, '\0'); f.read(&text[0], count); if (count % 2 != 0) { char pad; f.read(&pad, 1); } c["text"] = text; comments.push_back(c); } properties["Comments"] = comments; } else if (chunkID == "NAME" || chunkID == "AUTH" || chunkID == "(c) " || chunkID == "ANNO") { std::string key = (chunkID == "NAME") ? "Name" : (chunkID == "AUTH") ? "Author" : (chunkID == "(c) ") ? "Copyright" : "Annotations"; std::string val = readPString(f); if (key == "Annotations") { auto annos = std::any_cast>(properties[key]); annos.push_back(val); properties[key] = annos; } else { properties[key] = val; } } else if (chunkID == "AESD") { std::vector aes(24); f.read(reinterpret_cast(aes.data()), 24); properties["AES Channel Status Data"] = aes; } else if (chunkID == "MIDI") { std::vector midi(chunkSize); f.read(reinterpret_cast(midi.data()), chunkSize); properties["MIDI Data"] = midi; } else if (chunkID == "APPL") { char sig[5]; f.read(sig, 4); sig[4] = '\0'; std::vector data(chunkSize - 4); f.read(reinterpret_cast(data.data()), chunkSize - 4); std::map appData; appData["signature"] = std::string(sig); appData["data"] = data; properties["Application Specific Data"] = appData; } f.seekg(pos + static_cast(chunkSize)); if (f.tellg() % 2 != 0) { char pad; f.read(&pad, 1); } } } void printProperties() { for (const auto& [key, value] : properties) { // Simplified print; use type checking for real output std::cout << key << ": " << /* value */ std::endl; } } void write(const std::string& outputFilename) { std::ofstream f(outputFilename, std::ios::binary); if (!f) throw std::runtime_error("Cannot write file"); f.write("FORM", 4); uint32_t sizePlaceholder = 0; f.write(reinterpret_cast(&sizePlaceholder), 4); auto formType = std::any_cast(properties["Form Type"]); f.write(formType.c_str(), 4); // COMM f.write("COMM", 4); uint32_t commSizePlaceholder = 0; f.write(reinterpret_cast(&commSizePlaceholder), 4); std::streampos commStart = f.tellp(); uint16_t channels = std::any_cast(properties["Number of Channels"]); channels = __builtin_bswap16(channels); f.write(reinterpret_cast(&channels), 2); uint32_t frames = std::any_cast(properties["Number of Sample Frames"]); frames = __builtin_bswap32(frames); f.write(reinterpret_cast(&frames), 4); uint16_t sampleSize = std::any_cast(properties["Sample Size"]); sampleSize = __builtin_bswap16(sampleSize); f.write(reinterpret_cast(&sampleSize), 2); double sr = std::any_cast(properties["Sample Rate"]); char ext[10]; std::memcpy(ext, &sr, 8); std::memset(ext + 8, 0, 2); f.write(ext, 10); if (formType == "AIFC") { auto compType = std::any_cast(properties["Compression Type"]); f.write(compType.c_str(), 4); auto compName = std::any_cast(properties["Compression Name"]); uint8_t len = compName.length(); f.write(reinterpret_cast(&len), 1); f.write(compName.c_str(), len); if ((len + 1) % 2 == 0) { uint8_t pad = 0; f.write(reinterpret_cast(&pad), 1); } } uint32_t commSize = static_cast(f.tellp() - commStart); f.seekp(commStart - std::streampos(4)); commSize = __builtin_bswap32(commSize); f.write(reinterpret_cast(&commSize), 4); f.seekp(0, std::ios::end); // SSND f.write("SSND", 4); uint32_t ssndSize = 8 + std::any_cast(properties["Sound Data Offset"]) + audioData.size(); ssndSize = __builtin_bswap32(ssndSize); f.write(reinterpret_cast(&ssndSize), 4); uint32_t offsetVal = std::any_cast(properties["Sound Data Offset"]); offsetVal = __builtin_bswap32(offsetVal); f.write(reinterpret_cast(&offsetVal), 4); uint32_t blockSize = std::any_cast(properties["Sound Data Block Size"]); blockSize = __builtin_bswap32(blockSize); f.write(reinterpret_cast(&blockSize), 4); std::streampos dataPos = f.tellp(); f.seekp(std::any_cast(properties["Sound Data Offset"]), std::ios::cur); f.write(reinterpret_cast(audioData.data()), audioData.size()); // Update form size uint32_t totalSize = static_cast(f.tellp() - std::streampos(8)); f.seekp(4); totalSize = __builtin_bswap32(totalSize); f.write(reinterpret_cast(&totalSize), 4); // TODO: Add other chunks } }; // Example usage: // int main() { // try { // AIFFHandler handler("input.aiff"); // handler.printProperties(); // handler.write("output.aiff"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-022 .AIFF ===== // ===== task-023 .AIO [C++] ===== #include #include #include #include #include #include class AIOFileHandler { private: std::string filepath; std::map static_properties; int records_found; std::string encoding; std::vector> extracted_objects; public: AIOFileHandler(const std::string& fp) : filepath(fp), records_found(0), encoding("Unknown") { static_properties["Fixed Record Length"] = "80 bytes"; static_properties["Line Terminator"] = "CR or CR/LF (inferred)"; static_properties["Serialization Format"] = "Migration/Extended Transfer Form"; static_properties["Object Types Supported"] = "Variables, Functions, Operators, System Variables"; static_properties["File Extension"] = ".AIO"; static_properties["Portability"] = "Character-based cross-system transfer"; read_and_decode(); } void read_and_decode() { std::ifstream file(filepath, std::ios::in); std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); content.erase(std::remove(content.begin(), content.end(), '\r'), content.end()); content.erase(std::remove(content.begin(), content.end(), '\n'), content.end()); std::vector records; for (size_t i = 0; i < content.length(); i += 80) { records.push_back(content.substr(i, 80)); } records_found = records.size(); if (!records.empty()) encoding = detect_encoding(records[0][0]); std::string current_object; for (size_t i = 0; i < records.size(); ++i) { std::string record = records[i]; if (record.length() != 80) std::cerr << "Warning: Record " << i + 1 << " not 80 bytes" << std::endl; char indicator = record[0]; std::string content_area = record.substr(1, 71); content_area.erase(content_area.find_last_not_of(" ") + 1); // Trim std::string seq_num = record.substr(72); seq_num.erase(seq_num.find_last_not_of(" ") + 1); std::map obj; if (indicator == ' ' || indicator == 'X') { current_object += content_area; if (indicator == 'X') { std::regex pattern("([CNF])(.+?)\\s(\\d\\s.*)"); std::smatch match; if (std::regex_match(current_object, match, pattern)) { obj["Parsed Object Type"] = match[1]; obj["Parsed Object Name"] = match[2]; obj["Parsed Object Shape/Value"] = match[3]; } else { obj["Parsed Object Raw"] = current_object; } obj["Record Type Indicator"] = std::string(1, indicator); obj["Content Area"] = content_area; obj["Sequence Number Area"] = seq_num; extracted_objects.push_back(obj); current_object.clear(); } } else if (indicator == '?') { obj["Record Type Indicator"] = std::string(1, indicator); obj["Content Area"] = content_area; obj["Sequence Number Area"] = seq_num; extracted_objects.push_back(obj); } } } void print_properties() { std::cout << "Dumped Properties for .AIO File:" << std::endl; for (const auto& prop : static_properties) { std::cout << prop.first << ": " << prop.second << std::endl; } std::cout << "Records Found: " << records_found << std::endl; std::cout << "Encoding: " << encoding << std::endl; std::cout << "Extracted Objects:" << std::endl; for (size_t i = 0; i < extracted_objects.size(); ++i) { std::cout << " Object " << i + 1 << ":" << std::endl; for (const auto& obj_prop : extracted_objects[i]) { std::cout << " " << obj_prop.first << ": " << obj_prop.second << std::endl; } } } void write(const std::string& new_filepath = "") { std::string out_path = new_filepath.empty() ? filepath : new_filepath; std::ofstream file(out_path); for (const auto& obj : extracted_objects) { std::string record(80, ' '); record[0] = obj.at("Record Type Indicator")[0]; std::string content = obj.at("Content Area"); record.replace(1, content.length(), content); std::string seq = obj.at("Sequence Number Area"); record.replace(72, seq.length(), seq); file << record << "\r\n"; } file.close(); } private: std::string detect_encoding(char first_byte) { if (first_byte == ' ' || first_byte == 'X' || first_byte == '?') return "ASCII"; // EBCDIC checks simplified if (first_byte == '@' || first_byte == (char)231 || first_byte == 'o') return "EBCDIC"; return "Unknown"; } }; // Example usage: // int main() { // AIOFileHandler handler("example.AIO"); // handler.print_properties(); // handler.write("modified.AIO"); // return 0; // } // ===== end task-023 .AIO ===== // ===== task-024 .AMF [C++] ===== #include #include #include #include #include class AMF3ParserCPP { private: std::vector stringTable; std::vector objectTable; // Simplified as string for print std::vector traitTable; uint8_t readU8(std::ifstream& f) { uint8_t value; f.read((char*)&value, 1); return value; } uint32_t readU29(std::ifstream& f) { uint32_t value = 0; int count = 0; uint8_t byte; do { byte = readU8(f); value = (value << 7) | (byte & 0x7F); count++; } while (byte & 0x80 && count < 4); return value; } std::string readString(std::ifstream& f) { uint32_t u29 = readU29(f); if (u29 & 1) { uint32_t len = u29 >> 1; if (len == 0) return ""; char* buf = new char[len]; f.read(buf, len); std::string str(buf, len); delete[] buf; stringTable.push_back(str); return str; } else { uint32_t ref = u29 >> 1; return stringTable[ref]; } } std::string parseValue(std::ifstream& f) { uint8_t marker = readU8(f); switch (marker) { case 0x00: return "undefined"; case 0x01: return "null"; case 0x02: return "false"; case 0x03: return "true"; case 0x04: return std::to_string(readU29(f)); case 0x05: { double value; f.read((char*)&value, 8); return std::to_string(value); } case 0x06: return readString(f); // Similar implementations for other markers as in the Python example // For brevity, omitting full code for all types; implement similarly using the spec default: return "Unknown marker: 0x" + std::to_string(marker); } } public: std::string read(const std::string& filename) { std::ifstream f(filename, std::ios::binary); if (!f) return "Error opening file"; stringTable.clear(); objectTable.clear(); traitTable.clear(); return parseValue(f); } void printProperties(const std::string& filename) { std::cout << read(filename) << std::endl; } void write(const std::string& filename, const std::string& value) { std::ofstream f(filename, std::ios::binary); if (!f) return; // For simplicity, write a sample string f.put(0x06); // marker uint32_t len = value.length(); uint32_t u29 = (len << 1) | 1; f.write((char*)&u29, 4); // simplified f.write(value.c_str(), len); } }; // Example usage // AMF3ParserCPP parser; // parser.printProperties("example.amf"); // parser.write("new.amf", "test string"); // ===== end task-024 .AMF ===== // ===== task-025 .AMG [C] ===== #include #include #include #include typedef struct { uint32_t label; double *coeffs; } BFormatChannel; typedef struct { char *filename; uint32_t version; uint32_t num_bformat; uint32_t decoder_flags; BFormatChannel *bformat_channels; uint32_t n_channels; uint8_t *data; size_t data_size; } AmgFile; AmgFile *amg_create(const char *filename) { AmgFile *amg = malloc(sizeof(AmgFile)); amg->filename = strdup(filename); amg->version = 0; amg->num_bformat = 0; amg->decoder_flags = 0; amg->bformat_channels = NULL; amg->n_channels = 0; amg->data = NULL; amg->data_size = 0; return amg; } void amg_read(AmgFile *amg) { FILE *f = fopen(amg->filename, "rb"); if (!f) { perror("Failed to open file"); return; } fseek(f, 0, SEEK_END); amg->data_size = ftell(f); fseek(f, 0, SEEK_SET); amg->data = malloc(amg->data_size); fread(amg->data, 1, amg->data_size, f); fclose(f); // Check RIFF WAVE if (memcmp(amg->data, "RIFF", 4) != 0 || memcmp(amg->data + 8, "WAVE", 4) != 0) { fprintf(stderr, "Invalid RIFF WAVE file\n"); return; } size_t offset = 12; int found_fmt = 0; int found_ambg = 0; while (offset < amg->data_size - 8) { char *chunk_id = (char *)(amg->data + offset); uint32_t chunk_size = *(uint32_t *)(amg->data + offset + 4); if (memcmp(chunk_id, "fmt ", 4) == 0) { found_fmt = 1; amg->n_channels = *(uint16_t *)(amg->data + offset + 10); } else if (memcmp(chunk_id, "AMBG", 4) == 0) { found_ambg = 1; size_t chunk_offset = offset + 8; amg->version = *(uint32_t *)(amg->data + chunk_offset); amg->num_bformat = *(uint32_t *)(amg->data + chunk_offset + 4); amg->decoder_flags = *(uint32_t *)(amg->data + chunk_offset + 8); amg->bformat_channels = malloc(amg->num_bformat * sizeof(BFormatChannel)); size_t coeff_offset = chunk_offset + 12; for (uint32_t i = 0; i < amg->num_bformat; i++) { amg->bformat_channels[i].label = *(uint32_t *)(amg->data + coeff_offset); coeff_offset += 4; amg->bformat_channels[i].coeffs = malloc(amg->n_channels * sizeof(double)); for (uint32_t j = 0; j < amg->n_channels; j++) { amg->bformat_channels[i].coeffs[j] = *(double *)(amg->data + coeff_offset); coeff_offset += 8; } } } offset += 8 + chunk_size + (chunk_size % 2); } if (!found_fmt || !found_ambg) { fprintf(stderr, "Missing fmt or AMBG chunk\n"); } } void amg_print_properties(const AmgFile *amg) { printf("Version: %u\n", amg->version); printf("Number of B-Format Channels: %u\n", amg->num_bformat); printf("Decoder Flags: 0x%08x\n", amg->decoder_flags); for (uint32_t i = 0; i < amg->num_bformat; i++) { printf("B-Format Channel %u: Label = %u, Coefficients = [", i + 1, amg->bformat_channels[i].label); for (uint32_t j = 0; j < amg->n_channels; j++) { printf("%f ", amg->bformat_channels[i].coeffs[j]); } printf("]\n"); } } void amg_write(const AmgFile *amg, const char *new_filename) { const char *out = new_filename ? new_filename : amg->filename; FILE *f = fopen(out, "wb"); if (!f) { perror("Failed to write file"); return; } fwrite(amg->data, 1, amg->data_size, f); fclose(f); } void amg_destroy(AmgFile *amg) { if (amg->bformat_channels) { for (uint32_t i = 0; i < amg->num_bformat; i++) { free(amg->bformat_channels[i].coeffs); } free(amg->bformat_channels); } free(amg->data); free(amg->filename); free(amg); } // Example usage: // int main() { // AmgFile *amg = amg_create("example.amg"); // amg_read(amg); // amg_print_properties(amg); // amg_write(amg, "modified.amg"); // amg_destroy(amg); // return 0; // } // ===== end task-025 .AMG ===== // ===== task-026 .AML [C++] ===== #include #include #include #include #include class AMLParser { private: std::string signature; uint32_t length; uint8_t revision; uint8_t checksum; std::string oemId; std::string oemTableId; uint32_t oemRevision; std::string creatorId; uint32_t creatorRevision; std::vector body; // AML bytecode after header public: AMLParser(const std::string& filename = "") { if (!filename.empty()) { read(filename); } } void read(const std::string& filename) { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) { throw std::runtime_error("Unable to open file"); } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); std::vector data(size); if (!file.read(reinterpret_cast(data.data()), size)) { throw std::runtime_error("Error reading file"); } if (data.size() < 36) { throw std::runtime_error("File too small to be a valid .AML"); } signature.assign(reinterpret_cast(data.data()), 4); memcpy(&length, data.data() + 4, 4); revision = data[8]; checksum = data[9]; oemId.assign(reinterpret_cast(data.data() + 10), 6); oemId.erase(oemId.find('\0')); oemTableId.assign(reinterpret_cast(data.data() + 16), 8); oemTableId.erase(oemTableId.find('\0')); memcpy(&oemRevision, data.data() + 24, 4); creatorId.assign(reinterpret_cast(data.data() + 28), 4); memcpy(&creatorRevision, data.data() + 32, 4); body.assign(data.begin() + 36, data.end()); // Validate length and checksum (little-endian assumed) if (length != data.size()) { std::cout << "Warning: Length mismatch" << std::endl; } uint8_t computedChecksum = 0; for (uint8_t b : data) { computedChecksum += b; } if (computedChecksum != 0) { std::cout << "Warning: Checksum invalid" << std::endl; } } void printProperties() const { std::cout << "Table Signature: " << signature << std::endl; std::cout << "Table Length: " << length << std::endl; std::cout << "Revision: " << static_cast(revision) << std::endl; std::cout << "Checksum: " << static_cast(checksum) << std::endl; std::cout << "OEM ID: " << oemId << std::endl; std::cout << "OEM Table ID: " << oemTableId << std::endl; std::cout << "OEM Revision: " << oemRevision << std::endl; std::cout << "Creator ID: " << creatorId << std::endl; std::cout << "Creator Revision: " << creatorRevision << std::endl; } void write(const std::string& filename) const { std::vector data(36 + body.size()); memcpy(data.data(), signature.c_str(), 4); memcpy(data.data() + 4, &length, 4); data[8] = revision; data[9] = checksum; std::string paddedOem = oemId + std::string(6 - oemId.size(), '\0'); memcpy(data.data() + 10, paddedOem.c_str(), 6); std::string paddedOemTbl = oemTableId + std::string(8 - oemTableId.size(), '\0'); memcpy(data.data() + 16, paddedOemTbl.c_str(), 8); memcpy(data.data() + 24, &oemRevision, 4); memcpy(data.data() + 28, creatorId.c_str(), 4); memcpy(data.data() + 32, &creatorRevision, 4); std::copy(body.begin(), body.end(), data.begin() + 36); // Update length and checksum uint32_t newLength = static_cast(data.size()); memcpy(data.data() + 4, &newLength, 4); uint8_t newChecksum = 0; for (uint8_t b : data) { newChecksum += b; } newChecksum = -newChecksum; data[9] = newChecksum; std::ofstream file(filename, std::ios::binary); if (!file.write(reinterpret_cast(data.data()), data.size())) { throw std::runtime_error("Error writing file"); } } }; // Example usage: // int main() { // try { // AMLParser parser("example.aml"); // parser.printProperties(); // parser.write("output.aml"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-026 .AML ===== // ===== task-027 .AMLX [C++] ===== #include #include #include #include #include #include class AmlxHandler { private: std::string filename; std::map properties; public: AmlxHandler(const std::string& fn = "") : filename(fn) { if (!fn.empty()) { read(fn); } } void read(const std::string& fn) { filename = fn; std::ifstream file(fn, std::ios::binary); char sig[4]; file.read(sig, 4); properties["File Extension"] = ".amlx"; properties["MIME Type"] = "application/automationml-amlx+zip"; properties["Container Standard"] = "Open Packaging Conventions (OPC)"; properties["File Signature"] = (sig[0] == 'P' && sig[1] == 'K' && sig[2] == 3 && sig[3] == 4) ? "PK\\x03\\x04 (Valid ZIP)" : "Invalid"; // Use libzip to open ZIP int err = 0; zip_t* z = zip_open(fn.c_str(), 0, &err); if (z) { // Content Types File zip_file_t* ct = zip_fopen(z, "[Content_Types].xml", 0); std::string contentTypes; if (ct) { char buf[1024]; zip_int64_t len; while ((len = zip_fread(ct, buf, sizeof(buf))) > 0) { contentTypes.append(buf, len); } zip_fclose(ct); } properties["Content Types File"] = !contentTypes.empty() ? contentTypes : "Not found"; // Package Relationships File zip_file_t* rel = zip_fopen(z, "_rels/.rels", 0); std::string rels; if (rel) { char buf[1024]; zip_int64_t len; while ((len = zip_fread(rel, buf, sizeof(buf))) > 0) { rels.append(buf, len); } zip_fclose(rel); } properties["Package Relationships File"] = !rels.empty() ? rels : "Not found"; // Root Relationship Type and Path properties["Root Relationship Type"] = "http://schemas.automationml.org/container/relationship/RootDocument"; size_t pos = rels.find(properties["Root Relationship Type"]); std::string rootPath = "Not found"; if (pos != std::string::npos) { size_t targetPos = rels.find("Target=\"", pos); if (targetPos != std::string::npos) { targetPos += 8; size_t end = rels.find("\"", targetPos); rootPath = rels.substr(targetPos, end - targetPos); } } properties["Root Document Path"] = rootPath; // Library Document Path (simplified) zip_file_t* rootF = zip_fopen(z, rootPath.c_str(), 0); std::string rootContent; if (rootF) { char buf[1024]; zip_int64_t len; while ((len = zip_fread(rootF, buf, sizeof(buf))) > 0) { rootContent.append(buf, len); } zip_fclose(rootF); } properties["Library Document Path"] = (rootContent.find("Library.aml") != std::string::npos) ? "Library.aml" : "Not found"; // Embedded Files List std::string filesList; zip_int64_t num = zip_get_num_entries(z, 0); for (zip_int64_t i = 0; i < num; ++i) { filesList += zip_get_name(z, i, 0) + std::string(", "); } properties["Embedded Files List"] = filesList; // Container Type properties["Container Type"] = (rootContent.find("http://") != std::string::npos) ? "Free linked" : "Local linked"; // AutomationML Version size_t verPos = rootContent.find("Version=\""); std::string version = "Not found"; if (verPos != std::string::npos) { verPos += 9; size_t end = rootContent.find("\"", verPos); version = rootContent.substr(verPos, end - verPos); } properties["AutomationML Version"] = version; zip_close(z); } } void printProperties() { for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } void write(const std::string& newFn) { zip_t* z = zip_open(newFn.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); if (z) { // Add [Content_Types].xml std::string ct = ""; zip_source_t* src = zip_source_buffer(z, ct.c_str(), ct.size(), 0); zip_file_add(z, "[Content_Types].xml", src, ZIP_FL_OVERWRITE); // Add _rels/.rels std::string rels = ""; src = zip_source_buffer(z, rels.c_str(), rels.size(), 0); zip_file_add(z, "_rels/.rels", src, ZIP_FL_OVERWRITE); // Add root.aml std::string root = ""; src = zip_source_buffer(z, root.c_str(), root.size(), 0); zip_file_add(z, "root.aml", src, ZIP_FL_OVERWRITE); // Add library.aml std::string lib = ""; src = zip_source_buffer(z, lib.c_str(), lib.size(), 0); zip_file_add(z, "library.aml", src, ZIP_FL_OVERWRITE); zip_close(z); } read(newFn); // Reload properties } }; // Example usage: // int main() { // AmlxHandler handler("example.amlx"); // handler.printProperties(); // handler.write("new.amlx"); // return 0; // } // ===== end task-027 .AMLX ===== // ===== task-028 .AMPL [C++] ===== #include #include #include #include #include #include class AmplFileHandler { private: std::string filepath; std::map properties; std::vector parseInts(const std::string& line) { std::vector ints; std::stringstream ss(line); int num; while (ss >> num) { ints.push_back(num); } return ints; } int getOrZero(const std::vector& vec, size_t index) { return index < vec.size() ? vec[index] : 0; } public: AmplFileHandler(const std::string& filepath) : filepath(filepath) {} void readAndDecode() { std::ifstream file(filepath); if (!file.is_open()) { std::cout << "Failed to open file" << std::endl; return; } std::vector lines(10); for (int i = 0; i < 10; ++i) { std::getline(file, lines[i]); // Trim trailing whitespace size_t end = lines[i].find_last_not_of(" \t\r\n"); if (end != std::string::npos) { lines[i] = lines[i].substr(0, end + 1); } } file.close(); if (lines.size() < 10) { std::cout << "Invalid header" << std::endl; return; } properties["Format type"] = (lines[0][0] == 'g') ? "ASCII" : "Binary"; std::string optStr = lines[0].substr(1); // Trim leading spaces size_t start = optStr.find_first_not_of(" \t"); if (start != std::string::npos) { optStr = optStr.substr(start); } std::stringstream optSs(optStr); std::string opts; int opt; while (optSs >> opt) { if (!opts.empty()) opts += ", "; opts += std::to_string(opt); } properties["Option flags"] = opts; auto line2 = parseInts(lines[1]); properties["Number of variables"] = std::to_string(line2[0]); properties["Number of algebraic constraints"] = std::to_string(line2[1]); properties["Number of objectives"] = std::to_string(line2[2]); properties["Number of logical constraints"] = std::to_string(getOrZero(line2, 3)); properties["Number of range constraints"] = std::to_string(getOrZero(line2, 4)); properties["Number of equality constraints"] = std::to_string(getOrZero(line2, 5)); auto line3 = parseInts(lines[2]); properties["Number of nonlinear constraints"] = std::to_string(line3[0]); properties["Number of nonlinear objectives"] = std::to_string(line3[1]); auto line4 = parseInts(lines[3]); properties["Number of nonlinear network constraints"] = std::to_string(line4[0]); properties["Number of linear network constraints"] = std::to_string(line4[1]); auto line5 = parseInts(lines[4]); properties["Number of nonlinear variables in constraints"] = std::to_string(line5[0]); properties["Number of nonlinear variables in objectives"] = std::to_string(line5[1]); properties["Number of nonlinear variables in both"] = std::to_string(getOrZero(line5, 2)); auto line6 = parseInts(lines[5]); properties["Number of linear network variables"] = std::to_string(line6[0]); properties["Number of functions"] = std::to_string(line6[1]); properties["Number of arithmetic expressions"] = std::to_string(line6[2]); properties["Flags"] = std::to_string(getOrZero(line6, 3)); auto line7 = parseInts(lines[6]); properties["Number of binary variables"] = std::to_string(line7[0]); properties["Number of integer variables"] = std::to_string(line7[1]); properties["Number of nonlinear binary/integer variables"] = std::to_string(getOrZero(line7, 2)); auto line8 = parseInts(lines[7]); properties["Number of nonzeros in all Jacobian columns"] = std::to_string(line8[0]); properties["Number of nonzeros in all objective gradients"] = std::to_string(line8[1]); auto line9 = parseInts(lines[8]); properties["Max constraint name length"] = std::to_string(line9[0]); properties["Max variable name length"] = std::to_string(line9[1]); auto line10 = parseInts(lines[9]); properties["Number of common expressions in bounds"] = std::to_string(line10[0]); properties["Number of common expressions in single-variable constraints"] = std::to_string(line10[1]); properties["Number of common expressions in single-variable objectives"] = std::to_string(line10[2]); properties["Number of common expressions in multiple-variable constraints"] = std::to_string(getOrZero(line10, 3)); properties["Number of common expressions in multiple-variable objectives"] = std::to_string(getOrZero(line10, 4)); printProperties(); } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void writeSample(const std::string& outputPath) { std::ofstream file(outputPath); if (!file.is_open()) { std::cout << "Failed to write file" << std::endl; return; } file << "g 1 0\n"; file << "9 4 3 1 1 2\n"; file << "3 3\n"; file << "0 0\n"; file << "7 8 5\n"; file << "0 0 0 0\n"; file << "0 0 0\n"; file << "18 12\n"; file << "5 5\n"; file << "0 0 0 0 0\n"; file.close(); std::cout << "Sample .AMPL file written to " << outputPath << std::endl; } }; // Example usage: // int main() { // AmplFileHandler handler("example.nl"); // handler.readAndDecode(); // handler.writeSample("output.nl"); // return 0; // } // ===== end task-028 .AMPL ===== // ===== task-029 .AMR [C] ===== #include #include #include #include #include typedef struct { char *filepath; char magic[16]; char type[8]; bool is_wb; bool is_multi; char version[4]; int channels; int frame_count; double duration; int unique_ft[16]; // Bitmask for unique, or array int unique_count; int damaged; // For simplicity, not storing all frames; can add if needed } AMRFile; void amr_init(AMRFile *amr, const char *filepath) { amr->filepath = strdup(filepath); memset(amr->magic, 0, 16); strcpy(amr->type, "AMR"); amr->is_wb = false; amr->is_multi = false; strcpy(amr->version, ""); amr->channels = 1; amr->frame_count = 0; amr->duration = 0.0; memset(amr->unique_ft, 0, sizeof(amr->unique_ft)); amr->unique_count = 0; amr->damaged = 0; } void amr_free(AMRFile *amr) { free(amr->filepath); } bool amr_read_decode(AMRFile *amr) { FILE *f = fopen(amr->filepath, "rb"); if (!f) return false; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); int offset = 0; strncpy(amr->magic, (char*)data, 6); amr->magic[6] = '\0'; offset += 6; if (strcmp(amr->magic, "#!AMR\n") == 0) { // Single AMR } else if (strncmp((char*)data, "#!AMR-WB\n", 9) == 0) { strcpy(amr->magic, "#!AMR-WB\n"); amr->is_wb = true; strcpy(amr->type, "AMR-WB"); offset = 9; } else if (strncmp((char*)data, "#!AMR_MC1.0\n", 12) == 0) { strcpy(amr->magic, "#!AMR_MC1.0\n"); amr->is_multi = true; strcpy(amr->version, "1.0"); offset = 12; uint32_t chan_desc = (data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]; offset += 4; amr->channels = chan_desc & 0xF; } else if (strncmp((char*)data, "#!AMR-WB_MC1.0\n", 16) == 0) { strcpy(amr->magic, "#!AMR-WB_MC1.0\n"); amr->is_multi = true; strcpy(amr->version, "1.0"); amr->is_wb = true; strcpy(amr->type, "AMR-WB"); offset = 16; uint32_t chan_desc = (data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]; offset += 4; amr->channels = chan_desc & 0xF; } else { free(data); return false; } int frame_sizes[16]; if (!amr->is_wb) { int sizes[] = {13,14,16,18,20,21,27,32,6,0,0,0,0,0,1,1}; memcpy(frame_sizes, sizes, sizeof(sizes)); } else { int sizes[] = {18,24,33,37,41,47,61,75,85,6,0,0,0,0,6,1}; memcpy(frame_sizes, sizes, sizeof(sizes)); } while (offset < size) { bool block_valid = true; for (int ch = 0; ch < amr->channels; ch++) { if (offset >= size) { block_valid = false; break; } uint8_t header = data[offset++]; int ft = (header >> 4) & 0x0F; int q = (header >> 3) & 0x01; if (!amr->unique_ft[ft]) { amr->unique_ft[ft] = 1; amr->unique_count++; } if (q == 0) amr->damaged++; int data_size = frame_sizes[ft]; offset += data_size; if (offset > size) { block_valid = false; break; } } if (block_valid) amr->frame_count++; } amr->duration = amr->frame_count * 0.02; free(data); return true; } void amr_print_properties(const AMRFile *amr) { printf("Magic number: %s\n", amr->magic); printf("Codec type: %s\n", amr->type); printf("Channel configuration: %s\n", amr->is_multi ? "multi" : "single"); printf("File format version: %s\n", amr->version); printf("Number of channels: %d\n", amr->channels); printf("Total number of frame-blocks: %d\n", amr->frame_count); printf("Total duration in seconds: %.2f\n", amr->duration); printf("Unique frame types used: "); for (int i = 0; i < 16; i++) { if (amr->unique_ft[i]) printf("%d ", i); } printf("\n"); printf("Number of damaged frames: %d\n", amr->damaged); } bool amr_write(const AMRFile *amr, const char *new_filepath) { // For write, we need frames data, but since we didn't store, assume read first and modify if needed. // Here, stub for write same header (empty file for demo) FILE *f = fopen(new_filepath ? new_filepath : "output.amr", "wb"); if (!f) return false; fwrite(amr->magic, 1, strlen(amr->magic), f); if (amr->is_multi) { uint32_t chan_desc = amr->channels; uint8_t bytes[4] = {(chan_desc >> 24) & 0xFF, (chan_desc >> 16) & 0xFF, (chan_desc >> 8) & 0xFF, chan_desc & 0xFF}; fwrite(bytes, 1, 4, f); } fclose(f); printf("Wrote to %s (header only, add frame writing as needed)\n", new_filepath ? new_filepath : "output.amr"); return true; } // Example usage: // int main() { // AMRFile amr; // amr_init(&amr, "sample.amr"); // if (amr_read_decode(&amr)) { // amr_print_properties(&amr); // amr_write(&amr, NULL); // } // amr_free(&amr); // return 0; // } // ===== end task-029 .AMR ===== // ===== task-030 .AMV [C++] ===== #include #include #include #include #include #include #include using namespace std; class AmvFile { private: string filepath; map, map>>> properties; // Simplified, use any for flexibility vector data; public: AmvFile(const string& fp) : filepath(fp) {} void read() { ifstream file(filepath, ios::binary | ios::ate); streamsize size = file.tellg(); file.seekg(0, ios::beg); data.resize(size); file.read(data.data(), size); parse(); } void parse() { // Use char* pointer for offset const char* ptr = data.data(); // RIFF Header string sig( ptr, ptr + 4); properties["signature"] = sig; ptr += 4; uint32_t fileSize = *reinterpret_cast(ptr); properties["fileSize"] = static_cast(fileSize); ptr += 4; string formType(ptr, ptr + 4); properties["formType"] = formType; ptr += 4; if (sig != "RIFF" || formType != "AMV ") { throw runtime_error("Not a valid AMV file"); } // Skip hdrl List details for simplicity (assume positions) ptr += 12; // LIST, size, hdrl // amvh Chunk map>> amvh; ptr += 8; // 'amvh', size amvh["microSecPerFrame"] = *reinterpret_cast(ptr); ptr += 4; amvh["maxBytesPerSec"] = *reinterpret_cast(ptr); ptr += 4; amvh["paddingGranularity"] = *reinterpret_cast(ptr); ptr += 4; amvh["flags"] = *reinterpret_cast(ptr); ptr += 4; amvh["totalFrames"] = *reinterpret_cast(ptr); ptr += 4; amvh["initialFrames"] = *reinterpret_cast(ptr); ptr += 4; uint32_t numStreams = *reinterpret_cast(ptr); amvh["numStreams"] = static_cast(numStreams); ptr += 4; amvh["suggestedBufferSize"] = *reinterpret_cast(ptr); ptr += 4; amvh["width"] = *reinterpret_cast(ptr); ptr += 4; amvh["height"] = *reinterpret_cast(ptr); ptr += 4; vector reserved(4); for (int& r : reserved) { r = *reinterpret_cast(ptr); ptr += 4; } amvh["reserved"] = reserved; properties["amvh"] = amvh; // Streams (simplified, assume parsing) vector>>> streams; for (uint32_t s = 0; s < numStreams; ++s) { map>> stream; ptr += 12; // LIST, size, strl // strh ptr += 8; // 'strh', size string type(ptr, ptr + 4); stream["type"] = type; ptr += 4; string codec(ptr, ptr + 4); stream["codec"] = codec; ptr += 4; stream["flags"] = *reinterpret_cast(ptr); ptr += 4; stream["priority"] = *reinterpret_cast(ptr); ptr += 2; stream["language"] = *reinterpret_cast(ptr); ptr += 2; stream["initialFrames"] = *reinterpret_cast(ptr); ptr += 4; stream["scale"] = *reinterpret_cast(ptr); ptr += 4; stream["rate"] = *reinterpret_cast(ptr); ptr += 4; stream["start"] = *reinterpret_cast(ptr); ptr += 4; stream["length"] = *reinterpret_cast(ptr); ptr += 4; stream["suggestedBufferSize"] = *reinterpret_cast(ptr); ptr += 4; stream["quality"] = *reinterpret_cast(ptr); ptr += 4; stream["sampleSize"] = *reinterpret_cast(ptr); ptr += 4; vector frameRect(4); for (int& fr : frameRect) { fr = *reinterpret_cast(ptr); ptr += 2; } stream["frameRect"] = frameRect; // strf ptr += 4; // 'strf' uint32_t strfSize = *reinterpret_cast(ptr); ptr += 4; map format; if (type == "vids") { format["size"] = *reinterpret_cast(ptr); ptr += 4; format["width"] = *reinterpret_cast(ptr); ptr += 4; format["height"] = *reinterpret_cast(ptr); ptr += 4; format["planes"] = *reinterpret_cast(ptr); ptr += 2; format["bitCount"] = *reinterpret_cast(ptr); ptr += 2; string compression(ptr, ptr + 4); format["compression"] = compression; // Wait, variant is int/string, but for simplicity ptr += 4; ptr += strfSize - 24; // Skip } else if (type == "auds") { format["formatTag"] = *reinterpret_cast(ptr); ptr += 2; format["channels"] = *reinterpret_cast(ptr); ptr += 2; format["samplesPerSec"] = *reinterpret_cast(ptr); ptr += 4; format["avgBytesPerSec"] = *reinterpret_cast(ptr); ptr += 4; format["blockAlign"] = *reinterpret_cast(ptr); ptr += 2; format["bitsPerSample"] = *reinterpret_cast(ptr); ptr += 2; uint16_t extraSize = *reinterpret_cast(ptr); format["extraSize"] = extraSize; ptr += 2; if (extraSize > 0) { format["samplesPerBlock"] = *reinterpret_cast(ptr); ptr += 2; } } stream["format"] = format; streams.push_back(stream); } properties["streams"] = streams; properties["videoCodec"] = string("Motion JPEG variant"); properties["audioCodec"] = string("IMA ADPCM variant"); properties["audioSampleRate"] = 22050; } void printProperties() { // Simplified print, use recursion or visitor for variant cout << "Properties:" << endl; // Implement printing logic for map/variant cout << "signature: " << get(properties["signature"]) << endl; // Add more... } void write(const string& newFilepath = "") { string outPath = newFilepath.empty() ? filepath : newFilepath; ofstream file(outPath, ios::binary); file.write(data.data(), data.size()); cout << "File written to " << outPath << endl; } }; // Example usage: // int main() { // AmvFile amv("sample.amv"); // amv.read(); // amv.printProperties(); // amv.write("output.amv"); // return 0; // } // ===== end task-030 .AMV ===== // ===== task-031 .ANI [C] ===== #include #include #include #include typedef struct { char riff_sig[5]; uint32_t riff_size; char riff_type[5]; struct { uint32_t cbSize; uint32_t cFrames; uint32_t cSteps; uint32_t cx; uint32_t cy; uint32_t cBitCount; uint32_t cPlanes; uint32_t JifRate; uint32_t flags; } anih; char *inam; char *iart; uint32_t *rate; uint32_t rate_count; uint32_t *seq; uint32_t seq_count; uint8_t **frames; uint32_t *frame_sizes; uint32_t frame_count; } ANIFile; void ani_read(ANIFile *ani, const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) return; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); uint32_t pos = 0; memcpy(ani->riff_sig, data + pos, 4); ani->riff_sig[4] = '\0'; pos += 4; ani->riff_size = *(uint32_t*)(data + pos); pos += 4; memcpy(ani->riff_type, data + pos, 4); ani->riff_type[4] = '\0'; pos += 4; while (pos < size) { char chunk_id[5]; memcpy(chunk_id, data + pos, 4); chunk_id[4] = '\0'; pos += 4; uint32_t chunk_size = *(uint32_t*)(data + pos); pos += 4; uint8_t *chunk_data = data + pos; if (strcmp(chunk_id, "anih") == 0) { ani->anih.cbSize = *(uint32_t*)(chunk_data + 0); ani->anih.cFrames = *(uint32_t*)(chunk_data + 4); ani->anih.cSteps = *(uint32_t*)(chunk_data + 8); ani->anih.cx = *(uint32_t*)(chunk_data + 12); ani->anih.cy = *(uint32_t*)(chunk_data + 16); ani->anih.cBitCount = *(uint32_t*)(chunk_data + 20); ani->anih.cPlanes = *(uint32_t*)(chunk_data + 24); ani->anih.JifRate = *(uint32_t*)(chunk_data + 28); ani->anih.flags = *(uint32_t*)(chunk_data + 32); } else if (strcmp(chunk_id, "INAM") == 0) { ani->inam = strndup((char*)chunk_data, chunk_size); } else if (strcmp(chunk_id, "IART") == 0) { ani->iart = strndup((char*)chunk_data, chunk_size); } else if (strcmp(chunk_id, "rate") == 0) { ani->rate_count = chunk_size / 4; ani->rate = malloc(chunk_size); memcpy(ani->rate, chunk_data, chunk_size); } else if (strcmp(chunk_id, "seq ") == 0) { ani->seq_count = chunk_size / 4; ani->seq = malloc(chunk_size); memcpy(ani->seq, chunk_data, chunk_size); } else if (strcmp(chunk_id, "LIST") == 0) { char list_type[5]; memcpy(list_type, chunk_data, 4); list_type[4] = '\0'; if (strcmp(list_type, "fram") == 0) { uint32_t sub_pos = 4; while (sub_pos < chunk_size) { char sub_id[5]; memcpy(sub_id, chunk_data + sub_pos, 4); sub_id[4] = '\0'; sub_pos += 4; uint32_t sub_size = *(uint32_t*)(chunk_data + sub_pos); sub_pos += 4; if (strcmp(sub_id, "icon") == 0) { ani->frame_count++; ani->frames = realloc(ani->frames, ani->frame_count * sizeof(uint8_t*)); ani->frame_sizes = realloc(ani->frame_sizes, ani->frame_count * sizeof(uint32_t)); ani->frames[ani->frame_count - 1] = malloc(sub_size); memcpy(ani->frames[ani->frame_count - 1], chunk_data + sub_pos, sub_size); ani->frame_sizes[ani->frame_count - 1] = sub_size; } sub_pos += sub_size; if (sub_size % 2 != 0) sub_pos++; } } } pos += chunk_size; if (chunk_size % 2 != 0) pos++; } free(data); } void ani_print_properties(ANIFile *ani) { printf("RIFF Signature: %s\n", ani->riff_sig); printf("RIFF Size: %u\n", ani->riff_size); printf("RIFF Type: %s\n", ani->riff_type); printf("anih cbSize: %u\n", ani->anih.cbSize); printf("anih cFrames: %u\n", ani->anih.cFrames); printf("anih cSteps: %u\n", ani->anih.cSteps); printf("anih cx: %u\n", ani->anih.cx); printf("anih cy: %u\n", ani->anih.cy); printf("anih cBitCount: %u\n", ani->anih.cBitCount); printf("anih cPlanes: %u\n", ani->anih.cPlanes); printf("anih JifRate: %u\n", ani->anih.JifRate); printf("anih flags: %u\n", ani->anih.flags); if (ani->inam) printf("INAM: %s\n", ani->inam); if (ani->iart) printf("IART: %s\n", ani->iart); if (ani->rate_count > 0) { printf("rate: "); for (uint32_t i = 0; i < ani->rate_count; i++) printf("%u ", ani->rate[i]); printf("\n"); } if (ani->seq_count > 0) { printf("seq: "); for (uint32_t i = 0; i < ani->seq_count; i++) printf("%u ", ani->seq[i]); printf("\n"); } printf("Number of frames: %u\n", ani->frame_count); } void ani_write(ANIFile *ani, const char *new_filename) { FILE *f = fopen(new_filename, "wb"); if (!f) return; fwrite("RIFF", 1, 4, f); uint32_t placeholder = 0; fwrite(&placeholder, sizeof(uint32_t), 1, f); // riff_size fwrite("ACON", 1, 4, f); // anih fwrite("anih", 1, 4, f); uint32_t anih_size = 36; fwrite(&anih_size, sizeof(uint32_t), 1, f); fwrite(&ani->anih, sizeof(ani->anih), 1, f); // INAM if (ani->inam) { fwrite("INAM", 1, 4, f); uint32_t str_size = strlen(ani->inam) + 1; fwrite(&str_size, sizeof(uint32_t), 1, f); fwrite(ani->inam, 1, str_size - 1, f); fputc(0, f); } // IART if (ani->iart) { fwrite("IART", 1, 4, f); uint32_t str_size = strlen(ani->iart) + 1; fwrite(&str_size, sizeof(uint32_t), 1, f); fwrite(ani->iart, 1, str_size - 1, f); fputc(0, f); } // rate if (ani->rate_count > 0) { fwrite("rate", 1, 4, f); uint32_t data_size = ani->rate_count * 4; fwrite(&data_size, sizeof(uint32_t), 1, f); fwrite(ani->rate, 4, ani->rate_count, f); } // seq if (ani->seq_count > 0) { fwrite("seq ", 1, 4, f); uint32_t data_size = ani->seq_count * 4; fwrite(&data_size, sizeof(uint32_t), 1, f); fwrite(ani->seq, 4, ani->seq_count, f); } // LIST fram fpos_t list_pos; fgetpos(f, &list_pos); fwrite("LIST", 1, 4, f); uint32_t list_size_placeholder = 0; fwrite(&list_size_placeholder, sizeof(uint32_t), 1, f); fwrite("fram", 1, 4, f); uint32_t fram_content_size = 4; // 'fram' for (uint32_t i = 0; i < ani->frame_count; i++) { fwrite("icon", 1, 4, f); fwrite(&ani->frame_sizes[i], sizeof(uint32_t), 1, f); fwrite(ani->frames[i], 1, ani->frame_sizes[i], f); fram_content_size += 8 + ani->frame_sizes[i]; } fpos_t end_pos; fgetpos(f, &end_pos); uint32_t list_size = fram_content_size; fsetpos(f, &list_pos); fseek(f, 4, SEEK_CUR); // Skip 'LIST' fwrite(&list_size, sizeof(uint32_t), 1, f); fsetpos(f, &end_pos); // Update riff_size fseek(f, 0, SEEK_END); long total_size = ftell(f); uint32_t riff_size = total_size - 8; fseek(f, 4, SEEK_SET); fwrite(&riff_size, sizeof(uint32_t), 1, f); fclose(f); } void ani_free(ANIFile *ani) { free(ani->inam); free(ani->iart); free(ani->rate); free(ani->seq); for (uint32_t i = 0; i < ani->frame_count; i++) free(ani->frames[i]); free(ani->frames); free(ani->frame_sizes); } // Example usage: // int main() { // ANIFile ani = {0}; // ani_read(&ani, "input.ani"); // ani_print_properties(&ani); // ani_write(&ani, "output.ani"); // ani_free(&ani); // return 0; // } // ===== end task-031 .ANI ===== // ===== task-032 .ANN [C++] ===== #include #include #include #include #include class AnnFile { private: std::map properties; public: AnnFile(const std::string& filename = "") { if (!filename.empty()) { load(filename); } } void load(const std::string& filename) { std::ifstream file(filename); if (!file.is_open()) { std::cerr << "Error opening file: " << filename << std::endl; return; } std::string line; while (std::getline(file, line)) { line.erase(std::remove_if(line.begin(), line.end(), isspace), line.end()); // Trim whitespace if (line.empty() || line[0] == ';') { continue; } size_t pos = line.find('='); if (pos != std::string::npos) { std::string key = line.substr(0, pos); std::string value = line.substr(pos + 1); // Additional trim if needed key.erase(std::remove_if(key.begin(), key.end(), isspace), key.end()); value.erase(std::remove_if(value.begin(), value.end(), isspace), value.end()); properties[key] = value; } } file.close(); } void printProperties() const { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& filename) const { std::ofstream file(filename); if (!file.is_open()) { std::cerr << "Error opening file for writing: " << filename << std::endl; return; } for (const auto& pair : properties) { file << pair.first << " = " << pair.second << "\n"; } file.close(); } }; // ===== end task-032 .ANN ===== // ===== task-323 .JAVA [C++] ===== #include #include #include #include // May need -D_GNU_SOURCE typedef struct { const char* filepath; uint32_t magic; uint16_t minor_version; uint16_t major_version; uint16_t constant_pool_count; // Add more as needed } JavaClassParser; void read_and_decode(JavaClassParser* parser) { FILE* f = fopen(parser->filepath, "rb"); if (!f) { perror("File open failed"); return; } fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); size_t offset = 0; parser->magic = be32toh(*(uint32_t*)(data + offset)); offset += 4; parser->minor_version = be16toh(*(uint16_t*)(data + offset)); offset += 2; parser->major_version = be16toh(*(uint16_t*)(data + offset)); offset += 2; parser->constant_pool_count = be16toh(*(uint16_t*)(data + offset)); offset += 2; // Skip full parsing free(data); printf("magic: 0x%X\n", parser->magic); printf("minor_version: %u\n", parser->minor_version); printf("major_version: %u\n", parser->major_version); printf("constant_pool_count: %u\n", parser->constant_pool_count); } void write_example(const char* output_path) { FILE* f = fopen(output_path, "wb"); if (!f) { perror("File write failed"); return; } uint32_t magic = htobe32(0xCAFEBABE); uint16_t minor = htobe16(0); uint16_t major = htobe16(52); uint16_t cp_count = htobe16(1); fwrite(&magic, sizeof(uint32_t), 1, f); fwrite(&minor, sizeof(uint16_t), 1, f); fwrite(&major, sizeof(uint16_t), 1, f); fwrite(&cp_count, sizeof(uint16_t), 1, f); fclose(f); printf("Wrote basic .class to %s\n", output_path); } // Usage example in main: // int main() { // JavaClassParser parser = {.filepath = "example.class"}; // read_and_decode(&parser); // write_example("output.class"); // return 0; // } // ===== end task-323 .JAVA ===== // ===== task-033 .APE [C] ===== #include #include #include #include typedef struct { char cID[5]; uint16_t nVersion; uint32_t nDescriptorBytes; uint32_t nHeaderBytes; uint32_t nSeekTableBytes; uint32_t nHeaderDataBytes; uint32_t nAPEFrameDataBytes; uint32_t nAPEFrameDataBytesHigh; uint32_t nTerminatingDataBytes; uint8_t cFileMD5[16]; uint16_t nCompressionLevel; uint16_t nFormatFlags; uint32_t nBlocksPerFrame; uint32_t nFinalFrameBlocks; uint32_t nTotalFrames; uint16_t nBitsPerSample; uint16_t nChannels; uint32_t nSampleRate; uint8_t* data; size_t data_size; } APEFile; APEFile* ape_open(const char* filename) { APEFile* ape = malloc(sizeof(APEFile)); FILE* f = fopen(filename, "rb"); fseek(f, 0, SEEK_END); ape->data_size = ftell(f); fseek(f, 0, SEEK_SET); ape->data = malloc(ape->data_size); fread(ape->data, 1, ape->data_size, f); fclose(f); int offset = 0; memcpy(ape->cID, ape->data + offset, 4); ape->cID[4] = '\0'; offset += 4; memcpy(&ape->nVersion, ape->data + offset, 2); offset += 2; offset += 2; // Padding memcpy(&ape->nDescriptorBytes, ape->data + offset, 4); offset += 4; memcpy(&ape->nHeaderBytes, ape->data + offset, 4); offset += 4; memcpy(&ape->nSeekTableBytes, ape->data + offset, 4); offset += 4; memcpy(&ape->nHeaderDataBytes, ape->data + offset, 4); offset += 4; memcpy(&ape->nAPEFrameDataBytes, ape->data + offset, 4); offset += 4; memcpy(&ape->nAPEFrameDataBytesHigh, ape->data + offset, 4); offset += 4; memcpy(&ape->nTerminatingDataBytes, ape->data + offset, 4); offset += 4; memcpy(ape->cFileMD5, ape->data + offset, 16); offset += 16; // APE_HEADER memcpy(&ape->nCompressionLevel, ape->data + offset, 2); offset += 2; memcpy(&ape->nFormatFlags, ape->data + offset, 2); offset += 2; memcpy(&ape->nBlocksPerFrame, ape->data + offset, 4); offset += 4; memcpy(&ape->nFinalFrameBlocks, ape->data + offset, 4); offset += 4; memcpy(&ape->nTotalFrames, ape->data + offset, 4); offset += 4; memcpy(&ape->nBitsPerSample, ape->data + offset, 2); offset += 2; memcpy(&ape->nChannels, ape->data + offset, 2); offset += 2; memcpy(&ape->nSampleRate, ape->data + offset, 4); return ape; } void ape_print_properties(APEFile* ape) { printf("cID: %s\n", ape->cID); printf("nVersion: %u\n", ape->nVersion); printf("nDescriptorBytes: %u\n", ape->nDescriptorBytes); printf("nHeaderBytes: %u\n", ape->nHeaderBytes); printf("nSeekTableBytes: %u\n", ape->nSeekTableBytes); printf("nHeaderDataBytes: %u\n", ape->nHeaderDataBytes); printf("nAPEFrameDataBytes: %u\n", ape->nAPEFrameDataBytes); printf("nAPEFrameDataBytesHigh: %u\n", ape->nAPEFrameDataBytesHigh); printf("nTerminatingDataBytes: %u\n", ape->nTerminatingDataBytes); printf("cFileMD5: "); for (int i = 0; i < 16; i++) printf("%02x%s", ape->cFileMD5[i], (i < 15 ? ":" : "\n")); printf("nCompressionLevel: %u\n", ape->nCompressionLevel); printf("nFormatFlags: %u\n", ape->nFormatFlags); printf("nBlocksPerFrame: %u\n", ape->nBlocksPerFrame); printf("nFinalFrameBlocks: %u\n", ape->nFinalFrameBlocks); printf("nTotalFrames: %u\n", ape->nTotalFrames); printf("nBitsPerSample: %u\n", ape->nBitsPerSample); printf("nChannels: %u\n", ape->nChannels); printf("nSampleRate: %u\n", ape->nSampleRate); } void ape_write(APEFile* ape, const char* new_filename) { FILE* f = fopen(new_filename, "wb"); fwrite(ape->data, 1, ape->data_size, f); fclose(f); } void ape_free(APEFile* ape) { free(ape->data); free(ape); } // Example usage // int main() { // APEFile* ape = ape_open("example.ape"); // ape_print_properties(ape); // ape_write(ape, "new.ape"); // ape_free(ape); // return 0; // } // ===== end task-033 .APE ===== // ===== task-034 .APK [C++] ===== #include #include #include #include #include #include #include class ApkParser { private: std::string filepath; std::vector data; std::map globalProps; std::vector> filePropsList; public: ApkParser(const std::string& fp) : filepath(fp) { parse(); } void parse() { std::ifstream file(filepath, std::ios::binary); if (!file) return; data = std::vector((std::istreambuf_iterator(file)), std::istreambuf_iterator()); // Find EOCD size_t eocdOffset = data.size() - 22; while (eocdOffset > 0) { uint32_t sig = *reinterpret_cast(&data[eocdOffset]); if (sig == 0x06054b50) break; eocdOffset--; } if (eocdOffset == 0) return; // Invalid // Parse EOCD (little-endian) uint16_t diskNum = *reinterpret_cast(&data[eocdOffset + 4]); globalProps["disk_number"] = std::to_string(diskNum); // ... (parse all global, signing block, and file props similarly using reinterpret_cast) // For signing block and CD, similar byte reading } void printProperties() { std::cout << "Global Properties:" << std::endl; for (const auto& kv : globalProps) { std::cout << " " << kv.first << ": " << kv.second << std::endl; } std::cout << "\nFile Properties:" << std::endl; for (size_t i = 0; i < filePropsList.size(); ++i) { std::cout << "File " << i + 1 << ": " << filePropsList[i].at("file_name") << std::endl; for (const auto& kv : filePropsList[i]) { if (kv.first != "file_name") std::cout << " " << kv.first << ": " << kv.second << std::endl; } } } void write(const std::string& newFilepath, const std::string& newComment) { std::ofstream out(newFilepath, std::ios::binary); out.write(reinterpret_cast(data.data()), data.size()); // Modify logic here } }; // Usage: ApkParser parser("example.apk"); parser.printProperties(); parser.write("modified.apk", "new"); // ===== end task-034 .APK ===== // ===== task-035 .ARC [C++] ===== #include #include #include #include #include struct ArcEntry { uint8_t method; char filename[14]; uint32_t compressed_size; uint32_t timestamp; uint16_t crc; uint32_t original_size; }; class ArcFile { private: std::string filename; std::vector entries; public: ArcFile(const std::string& fn) : filename(fn) {} void readAndPrint() { std::ifstream file(filename, std::ios::binary | std::ios::ate); std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); std::vector buffer(size); if (file.read(buffer.data(), size)) { size_t offset = 0; while (offset < size) { if (static_cast(buffer[offset]) != 0x1A) break; uint8_t method = static_cast(buffer[offset + 1]); if (method == 0) break; ArcEntry entry; entry.method = method; std::memcpy(entry.filename, &buffer[offset + 2], 13); entry.filename[13] = '\0'; std::memcpy(&entry.compressed_size, &buffer[offset + 15], 4); std::memcpy(&entry.timestamp, &buffer[offset + 19], 4); std::memcpy(&entry.crc, &buffer[offset + 23], 2); std::memcpy(&entry.original_size, &buffer[offset + 25], 4); std::cout << "File: " << entry.filename << std::endl; std::cout << "Method: " << static_cast(method) << std::endl; std::cout << "Compressed Size: " << entry.compressed_size << std::endl; std::cout << "Timestamp (MS-DOS): " << entry.timestamp << std::endl; std::cout << "CRC: " << entry.crc << std::endl; std::cout << "Original Size: " << entry.original_size << std::endl; std::cout << "---" << std::endl; entries.push_back(entry); offset += 29 + entry.compressed_size; } } } void write(const std::string& output_filename) { std::ofstream file(output_filename, std::ios::binary); for (const auto& entry : entries) { file.put(0x1A); file.put(entry.method); file.write(entry.filename, 13); file.write(reinterpret_cast(&entry.compressed_size), 4); file.write(reinterpret_cast(&entry.timestamp), 4); file.write(reinterpret_cast(&entry.crc), 2); file.write(reinterpret_cast(&entry.original_size), 4); // Data not written; extend for full support. } file.put(0x1A); file.put(0); } }; // ===== end task-035 .ARC ===== // ===== task-357 .LL [C] ===== #include #include #include #include typedef struct { const char *filepath; unsigned char magic[8]; unsigned char expected_clsids[2][16]; const char *internal_app_names; const char *typical_size; const char *common_filename; const char *content_description; } LLFile; void llfile_init(LLFile *self, const char *filepath) { self->filepath = filepath; unsigned char m[] = {0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1}; memcpy(self->magic, m, 8); unsigned char c1[] = {0x00, 0xB0, 0x08, 0x80, 0xC7, 0xDC, 0xD0, 0x11, 0xB1, 0x83, 0x00, 0x40, 0xE9, 0x94, 0xB5, 0x7C}; unsigned char c2[] = {0x01, 0xB0, 0x08, 0x80, 0xC7, 0xDC, 0xD0, 0x11, 0xB1, 0x83, 0x00, 0x40, 0xE9, 0x94, 0xB5, 0x7C}; memcpy(self->expected_clsids[0], c1, 16); memcpy(self->expected_clsids[1], c2, 16); self->internal_app_names = "cmll10.dll [10,30,0,0 (05-08-02 1117)], CM32L8.DLL [8,7,0,0 (01-08-21 1348)], cm32L8.dll [8,7,0,0 (01-08-21 1348)]"; self->typical_size = "32 KB - 2 MB (up to 160 MB)"; self->common_filename = "preview.ll"; self->content_description = "Contains printed pages as graphics for preview"; } void llfile_read(LLFile *self) { FILE *f = fopen(self->filepath, "rb"); if (!f) { printf("Failed to open file.\n"); return; } unsigned char header[8]; fread(header, 1, 8, f); if (memcmp(header, self->magic, 8) != 0) { printf("Not a valid .LL file (invalid magic header).\n"); fclose(f); return; } fseek(f, 48, SEEK_SET); unsigned char clsid[16]; fread(clsid, 1, 16, f); fclose(f); int match = 0; for (int i = 0; i < 2; i++) { if (memcmp(clsid, self->expected_clsids[i], 16) == 0) { match = 1; break; } } if (!match) { printf("Not a matching .LL file CLSID.\n"); return; } struct stat st; stat(self->filepath, &st); printf("Magic Header: "); for (int i = 0; i < 8; i++) printf("%02X ", header[i]); printf("\n"); printf("CLSID/GUID: "); for (int i = 0; i < 16; i++) printf("%02X ", clsid[i]); printf("\n"); printf("Internal App Names: %s\n", self->internal_app_names); printf("Typical Size: %s\n", self->typical_size); printf("Common Filename: %s\n", self->common_filename); printf("Content Description: %s\n", self->content_description); printf("File Size: %ld bytes\n", st.st_size); } void llfile_write(LLFile *self, const char *output_path) { FILE *f = fopen(output_path, "wb"); if (!f) { printf("Failed to create file.\n"); return; } fwrite(self->magic, 1, 8, f); fseek(f, 48, SEEK_SET); fwrite(self->expected_clsids[0], 1, 16, f); fseek(f, 512, SEEK_SET); // Minimal size fclose(f); printf("Minimal .LL stub written to %s\n", output_path); } // Example usage // int main() { // LLFile ll; // llfile_init(&ll, "example.ll"); // llfile_read(&ll); // llfile_write(&ll, "new.ll"); // return 0; // } // ===== end task-357 .LL ===== // ===== task-036 .ART [C++] ===== #include #include #include #include #include class ArtFileHandler { private: std::string filename; char signature[3]; // Null-terminated unsigned char version; unsigned char unknown1; unsigned char padding[9]; unsigned short width; unsigned short height; std::vector compressedData; public: ArtFileHandler(const std::string& fn) : filename(fn), version(0), unknown1(0), width(0), height(0) { std::memset(signature, 0, sizeof(signature)); std::memset(padding, 0, sizeof(padding)); } void openAndDecode() { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file.is_open()) { throw std::runtime_error("Unable to open file"); } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); if (size < 17) { throw std::runtime_error("File too small for .ART header"); } std::vector data(size); file.read(reinterpret_cast(data.data()), size); signature[0] = data[0]; signature[1] = data[1]; signature[2] = '\0'; version = data[2]; unknown1 = data[3]; std::memcpy(padding, &data[4], 9); width = static_cast(data[13]) | (static_cast(data[14]) << 8); height = static_cast(data[15]) | (static_cast(data[16]) << 8); compressedData.assign(data.begin() + 17, data.end()); } void printProperties() { std::cout << "Signature: " << signature << std::endl; std::cout << "Version: 0x" << std::hex << std::setw(2) << std::setfill('0') << static_cast(version) << std::dec << std::endl; std::cout << "Unknown field 1: 0x" << std::hex << std::setw(2) << std::setfill('0') << static_cast(unknown1) << std::dec << std::endl; std::cout << "Padding: "; for (int i = 0; i < 9; ++i) { std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast(padding[i]) << " "; } std::cout << std::dec << std::endl; std::cout << "Width: " << width << std::endl; std::cout << "Height: " << height << std::endl; std::cout << "Compressed image data size: " << compressedData.size() << " bytes" << std::endl; } void write(const std::string& newFilename) { if (std::strlen(signature) == 0) { throw std::runtime_error("No data decoded yet"); } std::ofstream file(newFilename, std::ios::binary); if (!file.is_open()) { throw std::runtime_error("Unable to write file"); } file.write(signature, 2); file.write(reinterpret_cast(&version), 1); file.write(reinterpret_cast(&unknown1), 1); file.write(reinterpret_cast(padding), 9); unsigned char widthBytes[2] = { static_cast(width & 0xFF), static_cast(width >> 8) }; file.write(reinterpret_cast(widthBytes), 2); unsigned char heightBytes[2] = { static_cast(height & 0xFF), static_cast(height >> 8) }; file.write(reinterpret_cast(heightBytes), 2); file.write(reinterpret_cast(compressedData.data()), compressedData.size()); } }; // Example usage: // int main() { // try { // ArtFileHandler handler("example.ART"); // handler.openAndDecode(); // handler.printProperties(); // handler.write("new.ART"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-036 .ART ===== // ===== task-037 .ASAX [C++] ===== #include #include #include #include #include #include #include class AsaxHandler { private: // File path std::string filepath; // Vectors for extracted properties std::vector directives; std::vector declaration_blocks; std::vector render_blocks; // Defaults for language and inheritance std::string language = "Any .NET language"; std::string inherits = "HttpApplication (default)"; // Set for detected events std::set detected_events; // List of all events const std::vector events_list = { "Application_Init", "Application_Start", "Application_End", "Application_BeginRequest", "Application_EndRequest", "Application_AuthenticateRequest", "Application_AuthorizeRequest", "Application_ResolveRequestCache", "Application_AcquireRequestState", "Application_PreRequestHandlerExecute", "Application_PostRequestHandlerExecute", "Application_ReleaseRequestState", "Application_UpdateRequestCache", "Application_Error", "Application_PreSendRequestHeaders", "Application_PreSendRequestContent", "Session_Start", "Session_End" }; public: // Constructor AsaxHandler(const std::string& fp) : filepath(fp) {} // Read and decode method void read_and_decode() { // Open file std::ifstream file(filepath); if (!file.is_open()) { throw std::runtime_error("File " + filepath + " not found."); } // Read content std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); // Extract directives std::regex dir_regex(R"(< %@[\s\S]*?%>)"); std::sregex_iterator dir_iter(content.begin(), content.end(), dir_regex); for (std::sregex_iterator i = dir_iter; i != std::sregex_iterator(); ++i) { directives.push_back(i->str()); } // Extract declaration blocks std::regex decl_regex(R"()", std::regex::icase); std::sregex_iterator decl_iter(content.begin(), content.end(), decl_regex); for (std::sregex_iterator i = decl_iter; i != std::sregex_iterator(); ++i) { declaration_blocks.push_back(i->str()); } // Extract render blocks std::regex rend_regex(R"(<%(?!@)([\s\S]*?)%>)"); std::sregex_iterator rend_iter(content.begin(), content.end(), rend_regex); for (std::sregex_iterator i = rend_iter; i != std::sregex_iterator(); ++i) { render_blocks.push_back(i->str()); } // Extract language and inherits std::regex lang_regex(R"(Language\s*=\s*"([^"]+)")", std::regex::icase); std::regex inh_regex(R"(Inherits\s*=\s*"([^"]+)")", std::regex::icase); for (const auto& dir : directives) { std::smatch lang_match; if (std::regex_search(dir, lang_match, lang_regex)) { language = lang_match[1].str(); } std::smatch inh_match; if (std::regex_search(dir, inh_match, inh_regex)) { inherits = inh_match[1].str(); } } // Extract events for (const auto& block : declaration_blocks) { for (const auto& event : events_list) { std::regex event_regex(R"((void|Sub)\s+)" + event + R"(\s*\()", std::regex::icase); if (std::regex_search(block, event_regex)) { detected_events.insert(event); } } } } // Print properties method void print_properties() { // Print directives std::cout << "Application Directives:" << std::endl; if (directives.empty()) { std::cout << "None found" << std::endl; } else { for (const auto& dir : directives) { std::cout << dir << std::endl; } } // Print declaration blocks std::cout << "\nCode Declaration Blocks:" << std::endl; if (declaration_blocks.empty()) { std::cout << "None found" << std::endl; } else { for (const auto& block : declaration_blocks) { std::cout << block << std::endl << std::endl; } } // Print render blocks std::cout << "\nCode Render Blocks:" << std::endl; if (render_blocks.empty()) { std::cout << "None found" << std::endl; } else { for (const auto& block : render_blocks) { std::cout << block << std::endl; } } // Print events std::cout << "\nEvent Handling Capability:" << std::endl; if (detected_events.empty()) { std::cout << "None detected" << std::endl; } else { bool first = true; for (const auto& event : detected_events) { if (!first) std::cout << ", "; std::cout << event; first = false; } std::cout << std::endl; } // Print fixed properties std::cout << "\nSingle Instance Restriction:" << std::endl; std::cout << "Only one Global.asax file per ASP.NET application" << std::endl; std::cout << "\nAutomatic Parsing:" << std::endl; std::cout << "Automatically detected and processed by the ASP.NET runtime" << std::endl; std::cout << "\nInheritance from HttpApplication:" << std::endl; std::cout << "The associated class inherits from " << inherits << std::endl; std::cout << "\nSecurity Restriction:" << std::endl; std::cout << "The file cannot be directly requested or downloaded via a web browser" << std::endl; std::cout << "\nRecompilation Trigger:" << std::endl; std::cout << "Modifications to the file prompt automatic recompilation of the application" << std::endl; std::cout << "\nLanguage Flexibility:" << std::endl; std::cout << "Supports " << language << std::endl; } // Write method void write(const std::string& new_filepath, const std::vector& new_directives = {}, const std::vector& new_declaration_blocks = {}, const std::vector& new_render_blocks = {}) { // Open output file std::ofstream file(new_filepath); if (!file.is_open()) { throw std::runtime_error("Unable to write to " + new_filepath); } // Write directives for (const auto& dir : new_directives) { file << dir << "\n"; } // Write declaration blocks for (const auto& block : new_declaration_blocks) { file << "\n"; } // Write render blocks for (const auto& block : new_render_blocks) { file << "<% " << block << " %>\n"; } // Close file file.close(); } }; // Example usage: // int main() { // try { // AsaxHandler handler("path/to/global.asax"); // handler.read_and_decode(); // handler.print_properties(); // std::vector dirs = {"<%@ Application Language=\"C#\" Inherits=\"MyApp.Global\" %>"}; // handler.write("path/to/new.asax", dirs); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-037 .ASAX ===== // ===== task-038 .ASCX [C++] ===== #include #include #include #include #include class AscxHandler { private: std::string filepath; std::map properties; std::string content; void read() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file." << std::endl; return; } content = std::string((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); std::regex directiveRegex(R"(<\%\@\s*Control\s+([^\%>]+)\%\>)", std::regex::icase); std::smatch directiveMatch; if (std::regex_search(content, directiveMatch, directiveRegex)) { std::string attrs = directiveMatch[1].str(); std::regex attrRegex(R"((\w+)\s*=\s*["']?([^"']+)["']?)"); std::sregex_iterator iter(attrs.begin(), attrs.end(), attrRegex); std::sregex_iterator end; for (; iter != end; ++iter) { properties[(*iter)[1].str()] = (*iter)[2].str(); } } } public: AscxHandler(const std::string& fp) : filepath(fp) { read(); } void printProperties() { if (properties.empty()) { std::cout << "No properties found." << std::endl; return; } std::cout << "ASCX Properties:" << std::endl; for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& newFilepath = "", const std::map& updatedProperties = {}) { for (const auto& pair : updatedProperties) { properties[pair.first] = pair.second; } std::string directive = "<%@ Control "; for (const auto& pair : properties) { directive += pair.first + "=\"" + pair.second + "\" "; } directive += "%>"; std::regex directiveRegex(R"(<\%\@\s*Control\s+[^\%>]+\%\>)", std::regex::icase); std::string newContent = std::regex_replace(content, directiveRegex, directive); std::string writePath = newFilepath.empty() ? filepath : newFilepath; std::ofstream outFile(writePath); if (!outFile.is_open()) { std::cerr << "Error writing file." << std::endl; return; } outFile << newContent; outFile.close(); std::cout << "File written to " << writePath << std::endl; } }; // Example usage: // int main() { // AscxHandler handler("example.ascx"); // handler.printProperties(); // std::map updates = {{"Language", "C#"}}; // handler.write("", updates); // return 0; // } // ===== end task-038 .ASCX ===== // ===== task-039 .ASF [C++] ===== #include #include #include #include #include #include // Assume uuid library or implement class ASFParser { private: std::string filename; std::map properties; public: ASFParser(const std::string& fn) : filename(fn) { read(); } void read() { std::ifstream file(filename, std::ios::binary); if (!file) return; char buffer[1024 * 1024]; // Assume sufficient file.read(buffer, sizeof(buffer)); size_t offset = 0; auto readGUID = [&](std::string& guid_str) { uuid_t guid; memcpy(guid, buffer + offset, 16); offset += 16; char guid_buf[37]; uuid_unparse_lower(guid, guid_buf); guid_str = guid_buf; }; auto readQWORD = [&]() -> uint64_t { uint64_t val; memcpy(&val, buffer + offset, 8); offset += 8; return val; }; auto readDWORD = [&]() -> uint32_t { uint32_t val; memcpy(&val, buffer + offset, 4); offset += 4; return val; }; auto readBYTE = [&]() -> uint8_t { uint8_t val = static_cast(buffer[offset]); offset += 1; return val; }; std::string guid; readGUID(guid); if (guid != "75b22630-668e-11cf-a6d9-00aa0062ce6c") { std::cerr << "Invalid ASF Header" << std::endl; return; } properties["Header GUID"] = guid; uint64_t objSize = readQWORD(); properties["Header Size"] = std::to_string(objSize); uint32_t numHeaders = readDWORD(); properties["Num Header Objects"] = std::to_string(numHeaders); properties["Reserved1"] = std::to_string(readBYTE()); properties["Reserved2"] = std::to_string(readBYTE()); // Parse sub-objects (example) while (offset < objSize) { readGUID(guid); uint64_t subSize = readQWORD(); properties["Sub-Object GUID " + guid] = guid; properties["Sub-Object Size " + guid] = std::to_string(subSize); if (guid == "8cabdca1-a947-11cf-8ee4-00c00c205365") { // File Properties std::string fileId; readGUID(fileId); properties["File ID"] = fileId; properties["File Size"] = std::to_string(readQWORD()); properties["Creation Date"] = std::to_string(readQWORD()); properties["Data Packets Count"] = std::to_string(readQWORD()); properties["Play Duration"] = std::to_string(readQWORD()); properties["Send Duration"] = std::to_string(readQWORD()); properties["Preroll"] = std::to_string(readQWORD()); properties["Flags"] = std::to_string(readDWORD()); properties["Min Packet Size"] = std::to_string(readDWORD()); properties["Max Packet Size"] = std::to_string(readDWORD()); properties["Max Bitrate"] = std::to_string(readDWORD()); } else { offset += subSize - 24; } } } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& outputFilename) { std::ofstream file(outputFilename, std::ios::binary); if (!file) return; uint8_t header[30] = {0x30,0x26,0xB2,0x75,0x8E,0x66,0xCF,0x11,0xA6,0xD9,0x00,0xAA,0x00,0x62,0xCE,0x6C, 0x1E,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // Size 30 0x00,0x00,0x00,0x00, // Num headers 0x01,0x02}; file.write(reinterpret_cast(header), 30); std::cout << "Minimal ASF file written." << std::endl; } }; // Example usage // int main() { // ASFParser parser("sample.asf"); // parser.printProperties(); // parser.write("output.asf"); // return 0; // } // ===== end task-039 .ASF ===== // ===== task-040 .ASHX [C++] ===== #include #include #include #include #include #include #include #include class AshxHandler { private: std::string filepath; std::string content; std::map properties; // Using string for simplicity; lists as comma-separated public: AshxHandler(const std::string& fp) : filepath(fp) {} std::map readAndDecode() { std::ifstream file(filepath); if (file) { content.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); parseProperties(); } return properties; } void parseProperties() { std::regex directiveRegex(R"(<%@\s*WebHandler\s*Language="([^"]+)"\s*Class="([^"]+)"\s*%>)", std::regex::icase); std::smatch directiveMatch; std::string directive = std::regex_search(content, directiveMatch, directiveRegex) ? directiveMatch[0] : "Not found"; std::string language = directiveMatch.size() > 1 ? directiveMatch[1] : "Not found"; std::string className = directiveMatch.size() > 2 ? directiveMatch[2] : "Not found"; std::regex namespaceRegex(R"(using\s+([^;]+);)"); std::sregex_iterator nsIter(content.begin(), content.end(), namespaceRegex); std::vector namespaces; for (std::sregex_iterator end; nsIter != end; ++nsIter) { namespaces.push_back((*nsIter)[1]); } std::string nsList; for (const auto& ns : namespaces) { if (!nsList.empty()) nsList += ", "; nsList += ns; } std::regex processRequestRegex(R"(public\s+void\s+ProcessRequest\s*\(HttpContext\s+context\)\s*\{([\s\S]*?)\})", std::regex::icase); std::smatch processRequestMatch; std::string processRequest = std::regex_search(content, processRequestMatch, processRequestRegex) ? processRequestMatch[1] : "Not found"; std::regex isReusableRegex(R"(public\s+bool\s+IsReusable\s*\{\s*get\s*\{\s*return\s+(true|false);\s*\}\s*\})", std::regex::icase); std::smatch isReusableMatch; std::string isReusable = std::regex_search(content, isReusableMatch, isReusableRegex) ? isReusableMatch[1] : "Not found"; struct stat statbuf; stat(filepath.c_str(), &statbuf); char ctimeBuf[64], mtimeBuf[64]; std::strftime(ctimeBuf, sizeof(ctimeBuf), "%Y-%m-%d %H:%M:%S", std::localtime(&statbuf.st_ctime)); std::strftime(mtimeBuf, sizeof(mtimeBuf), "%Y-%m-%d %H:%M:%S", std::localtime(&statbuf.st_mtime)); properties["File Extension"] = ".ashx"; properties["MIME Type"] = "Dynamic (e.g., text/plain)"; properties["Directive Line"] = directive; properties["Language"] = language; properties["Class Name"] = className; properties["Imported Namespaces"] = nsList; properties["ProcessRequest Method"] = processRequest; properties["IsReusable Property"] = isReusable; properties["Content Encoding"] = "UTF-8"; properties["File Size"] = std::to_string(statbuf.st_size) + " bytes"; properties["Creation/Modification Dates"] = std::string("Created: ") + ctimeBuf + ", Modified: " + mtimeBuf; } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void writeNewFile(const std::string& newFilepath, const std::string& language = "C#", const std::string& className = "Handler", const std::vector& namespaces = {"System", "System.Web"}, const std::string& processRequest = "// Add logic here", bool isReusable = false) { std::ofstream out(newFilepath); if (out) { out << "<%@ WebHandler Language=\"" << language << "\" Class=\"" << className << "\" %>\n"; for (const auto& ns : namespaces) { out << "using " << ns << ";\n"; } out << "public class " << className << " : IHttpHandler {\n"; out << " public void ProcessRequest(HttpContext context) {\n" << processRequest << "\n }\n"; out << " public bool IsReusable { get { return " << (isReusable ? "true" : "false") << "; } }\n"; out << "}\n"; } } }; // Example usage: // int main() { // AshxHandler handler("example.ashx"); // handler.readAndDecode(); // handler.printProperties(); // std::vector ns = {"System", "System.Web"}; // handler.writeNewFile("new.ashx"); // return 0; // } // ===== end task-040 .ASHX ===== // ===== task-042 .ASPX [C++] ===== #include #include #include #include #include class ASPXHandler { private: std::string filename; std::map properties; std::string original_content; public: ASPXHandler(const std::string& fn) : filename(fn) {} void read() { std::ifstream file(filename); if (!file.is_open()) { std::cout << "File " << filename << " does not exist." << std::endl; return; } std::string line; while (std::getline(file, line)) { original_content += line + "\n"; } file.close(); // Parse <%@ Page ... %> std::regex directive_regex(R"(<\%\@\s*Page\s*(.*?)\%\>)", std::regex::icase); std::smatch directive_match; if (std::regex_search(original_content, directive_match, directive_regex)) { std::string attrs = directive_match[1].str(); // Parse key="value" or key=value std::regex prop_regex(R"((\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+)))"); std::sregex_iterator iter(attrs.begin(), attrs.end(), prop_regex); std::sregex_iterator end; for (; iter != end; ++iter) { std::string key = (*iter)[1].str(); std::string value = (*iter)[2].str().empty() ? ((*iter)[3].str().empty() ? (*iter)[4].str() : (*iter)[3].str()) : (*iter)[2].str(); properties[key] = value; } } else { std::cout << "No Page directive found." << std::endl; } } void print_properties() { if (properties.empty()) { std::cout << "No properties extracted." << std::endl; return; } std::cout << "Extracted Properties:" << std::endl; for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& new_filename) { if (properties.empty()) { std::cout << "No properties to write." << std::endl; return; } std::string directive = "<%@ Page "; for (const auto& pair : properties) { directive += pair.first + "=\"" + pair.second + "\" "; } directive += "%>\n"; std::string content = directive + "\n\n\n

Modified ASPX

\n\n"; std::ofstream out_file(new_filename); if (out_file.is_open()) { out_file << content; out_file.close(); std::cout << "Written to " << new_filename << std::endl; } else { std::cout << "Failed to write file." << std::endl; } } }; // Example usage: // int main() { // ASPXHandler handler("sample.aspx"); // handler.read(); // handler.print_properties(); // handler.write("modified.aspx"); // return 0; // } // ===== end task-042 .ASPX ===== // ===== task-043 .ASX [C++] ===== #include #include #include #include #include "tinyxml2.h" // Assume TinyXML-2 library is included using namespace tinyxml2; using namespace std; class ASXHandler { private: string filepath; XMLDocument doc; map>> properties; public: ASXHandler(const string& fp) : filepath(fp) {} void readAndDecode() { doc.LoadFile(filepath.c_str()); extractProperties(); } void extractProperties() { XMLElement* root = doc.FirstChildElement("ASX"); if (root) { map rootAttrs; rootAttrs["VERSION"] = root->Attribute("VERSION") ? root->Attribute("VERSION") : ""; rootAttrs["PREVIEWMODE"] = root->Attribute("PREVIEWMODE") ? root->Attribute("PREVIEWMODE") : ""; rootAttrs["BANNERBAR"] = root->Attribute("BANNERBAR") ? root->Attribute("BANNERBAR") : ""; properties["ASX"] = {rootAttrs}; } vector elements = {"ABSTRACT", "AUTHOR", "BANNER", "BASE", "COPYRIGHT", "DURATION", "ENDMARKER", "ENTRY", "ENTRYREF", "EVENT", "LOGO", "MOREINFO", "PARAM", "PREVIEWDURATION", "REF", "REPEAT", "STARTMARKER", "STARTTIME", "TITLE"}; for (const auto& el : elements) { vector> list; XMLElement* tag = doc.FirstChildElement(el.c_str()); while (tag) { map map; map["text"] = tag->GetText() ? tag->GetText() : ""; const XMLAttribute* attr = tag->FirstAttribute(); while (attr) { map[attr->Name()] = attr->Value(); attr = attr->Next(); } list.push_back(map); tag = tag->NextSiblingElement(el.c_str()); } if (!list.empty()) { properties[el] = list; } } } void printProperties() { for (const auto& prop : properties) { cout << prop.first << ": " << endl; for (const auto& item : prop.second) { for (const auto& kv : item) { cout << " " << kv.first << ": " << kv.second << endl; } cout << "---" << endl; } } } void write(const string& outputFilepath) { doc.SaveFile(outputFilepath.c_str()); } }; // Usage example: // int main() { // ASXHandler handler("sample.asx"); // handler.readAndDecode(); // handler.printProperties(); // handler.write("output.asx"); // return 0; // } // ===== end task-043 .ASX ===== // ===== task-044 .AT3 [C] ===== #include #include #include #include typedef struct { uint16_t audio_format; uint16_t channels; uint32_t sample_rate; uint32_t byte_rate; uint16_t block_align; uint16_t bits_per_sample; uint16_t extra_size; uint8_t *extra_params; uint32_t num_samples; uint32_t data_size; uint8_t *data; uint8_t *header_data; size_t header_size; } AT3File; AT3File* at3_create(const char* filename) { AT3File* at3 = malloc(sizeof(AT3File)); memset(at3, 0, sizeof(AT3File)); // Initialization if needed return at3; } void at3_read(AT3File* at3, const char* filename) { FILE* fp = fopen(filename, "rb"); if (!fp) { perror("Failed to open file"); exit(1); } fseek(fp, 0, SEEK_END); size_t file_size = ftell(fp); fseek(fp, 0, SEEK_SET); uint8_t* buffer = malloc(file_size); fread(buffer, 1, file_size, fp); fclose(fp); size_t offset = 0; // RIFF header if (memcmp(buffer + offset, "RIFF", 4) != 0) { fprintf(stderr, "Invalid RIFF header\n"); exit(1); } offset += 4; uint32_t riff_size = *(uint32_t*)(buffer + offset) + 8; offset += 4; if (memcmp(buffer + offset, "WAVE", 4) != 0) { fprintf(stderr, "Invalid WAVE format\n"); exit(1); } offset += 4; // fmt chunk if (memcmp(buffer + offset, "fmt ", 4) != 0) { fprintf(stderr, "Invalid fmt chunk\n"); exit(1); } offset += 4; uint32_t fmt_size = *(uint32_t*)(buffer + offset); offset += 4; at3->audio_format = *(uint16_t*)(buffer + offset); if (at3->audio_format != 0x0270) { fprintf(stderr, "Not ATRAC3 format\n"); exit(1); } offset += 2; at3->channels = *(uint16_t*)(buffer + offset); offset += 2; at3->sample_rate = *(uint32_t*)(buffer + offset); offset += 4; at3->byte_rate = *(uint32_t*)(buffer + offset); offset += 4; at3->block_align = *(uint16_t*)(buffer + offset); offset += 2; at3->bits_per_sample = *(uint16_t*)(buffer + offset); offset += 2; at3->extra_size = *(uint16_t*)(buffer + offset); offset += 2; at3->extra_params = malloc(at3->extra_size); memcpy(at3->extra_params, buffer + offset, at3->extra_size); offset += at3->extra_size; // fact chunk if (memcmp(buffer + offset, "fact", 4) != 0) { fprintf(stderr, "Invalid fact chunk\n"); exit(1); } offset += 4; uint32_t fact_size = *(uint32_t*)(buffer + offset); offset += 4; at3->num_samples = *(uint32_t*)(buffer + offset); offset += 4; // Skip extra // data chunk if (memcmp(buffer + offset, "data", 4) != 0) { fprintf(stderr, "Invalid data chunk\n"); exit(1); } offset += 4; at3->data_size = *(uint32_t*)(buffer + offset); offset += 4; at3->data = malloc(at3->data_size); memcpy(at3->data, buffer + offset, at3->data_size); at3->header_size = offset - at3->data_size; at3->header_data = malloc(at3->header_size); memcpy(at3->header_data, buffer, at3->header_size); free(buffer); } void at3_print_properties(AT3File* at3) { printf("Audio Format Code: %u (0x%04X)\n", at3->audio_format, at3->audio_format); printf("Number of Channels: %u\n", at3->channels); printf("Sample Rate: %u Hz\n", at3->sample_rate); printf("Average Bytes per Second: %u\n", at3->byte_rate); printf("Block Align: %u\n", at3->block_align); printf("Bits per Sample: %u\n", at3->bits_per_sample); printf("Extra Param Size: %u\n", at3->extra_size); printf("Extra Params (hex): "); for (int i = 0; i < at3->extra_size; i++) { printf("%02x ", at3->extra_params[i]); } printf("\n"); printf("Number of Samples: %u\n", at3->num_samples); printf("Data Size: %u bytes\n", at3->data_size); } void at3_write(AT3File* at3, const char* output_filename) { if (!at3->data) { fprintf(stderr, "No data to write\n"); exit(1); } FILE* fp = fopen(output_filename, "wb"); if (!fp) { perror("Failed to open output file"); exit(1); } fwrite(at3->header_data, 1, at3->header_size, fp); uint32_t data_size_le = at3->data_size; fwrite(&data_size_le, sizeof(uint32_t), 1, fp); fwrite(at3->data, 1, at3->data_size, fp); fclose(fp); } void at3_destroy(AT3File* at3) { free(at3->extra_params); free(at3->data); free(at3->header_data); free(at3); } // Example usage: ./program input.at3 output.at3 int main(int argc, char** argv) { if (argc < 3) { printf("Usage: %s input.at3 output.at3\n", argv[0]); return 1; } AT3File* at3 = at3_create(argv[1]); at3_read(at3, argv[1]); at3_print_properties(at3); at3_write(at3, argv[2]); at3_destroy(at3); return 0; } // ===== end task-044 .AT3 ===== // ===== task-045 .ATG [C++] ===== #include #include #include #include #include #include #include class ATGFile { private: std::vector imports; std::string compilerName; std::string globalFieldsAndMethods; bool ignoreCase; std::map characterSets; std::map tokens; std::vector pragmas; std::vector comments; std::string ignore; std::map productions; std::string endName; public: ATGFile(const std::string& filepath = "") { ignoreCase = false; if (!filepath.empty()) { read(filepath); } } void read(const std::string& filepath) { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Failed to open file." << std::endl; return; } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); std::istringstream iss(content); std::string line; std::string state = "imports"; while (std::getline(iss, line)) { line = std::regex_replace(line, std::regex("^\\s+|\\s+$"), ""); if (line.empty()) continue; std::smatch match; if (state == "imports" && (std::regex_search(line, std::regex("^using ")) || std::regex_search(line, std::regex("^import ")))) { imports.push_back(line); } else if (std::regex_match(line, match, std::regex("^COMPILER\\s*(.*)"))) { compilerName = match[1]; state = "global"; } else if (state == "global" && !std::regex_search(line, std::regex("^(IGNORECASE|CHARACTERS|TOKENS|PRAGMAS|COMMENTS|IGNORE|PRODUCTIONS|END)"))) { globalFieldsAndMethods += line + "\n"; } else if (line == "IGNORECASE") { ignoreCase = true; state = "scanner"; } else if (std::regex_search(line, std::regex("^CHARACTERS"))) { state = "characters"; } else if (state == "characters" && line.find('=') != std::string::npos) { size_t pos = line.find('='); std::string name = line.substr(0, pos); std::string defn = line.substr(pos + 1); name = std::regex_replace(name, std::regex("^\\s+|\\s+$"), ""); defn = std::regex_replace(defn, std::regex("^\\s+|\\s+$|\\.$"), ""); characterSets[name] = defn; } else if (std::regex_search(line, std::regex("^TOKENS"))) { state = "tokens"; } else if (state == "tokens" && line.find('=') != std::string::npos) { size_t pos = line.find('='); std::string name = line.substr(0, pos); std::string defn = line.substr(pos + 1); name = std::regex_replace(name, std::regex("^\\s+|\\s+$"), ""); defn = std::regex_replace(defn, std::regex("^\\s+|\\s+$|\\.$"), ""); tokens[name] = defn; } else if (std::regex_search(line, std::regex("^PRAGMAS"))) { state = "pragmas"; } else if (state == "pragmas" && line.find('=') != std::string::npos) { pragmas.push_back(std::regex_replace(line, std::regex("\\.$"), "")); } else if (std::regex_search(line, std::regex("^COMMENTS FROM"))) { comments.push_back(line); } else if (std::regex_match(line, match, std::regex("^IGNORE\\s*(.*)"))) { ignore = match[1]; } else if (std::regex_search(line, std::regex("^PRODUCTIONS"))) { state = "productions"; } else if (state == "productions" && line.find('=') != std::string::npos) { size_t pos = line.find('='); std::string name = line.substr(0, pos); std::string defn = line.substr(pos + 1); name = std::regex_replace(name, std::regex("^\\s+|\\s+$"), ""); defn = std::regex_replace(defn, std::regex("^\\s+|\\s+$|\\.$"), ""); productions[name] = defn; } else if (std::regex_match(line, match, std::regex("^END\\s*(.*)\\.$"))) { endName = match[1]; state = "end"; } } } void printProperties() { std::cout << "{\n"; std::cout << " \"imports\": ["; for (size_t i = 0; i < imports.size(); ++i) { std::cout << "\"" << imports[i] << "\"" << (i < imports.size() - 1 ? ", " : ""); } std::cout << "],\n"; std::cout << " \"compilerName\": \"" << compilerName << "\",\n"; std::cout << " \"globalFieldsAndMethods\": \"" << globalFieldsAndMethods << "\",\n"; std::cout << " \"ignoreCase\": " << (ignoreCase ? "true" : "false") << ",\n"; std::cout << " \"characterSets\": {"; for (auto it = characterSets.begin(); it != characterSets.end(); ) { std::cout << "\"" << it->first << "\": \"" << it->second << "\""; if (++it != characterSets.end()) std::cout << ", "; } std::cout << "},\n"; std::cout << " \"tokens\": {"; for (auto it = tokens.begin(); it != tokens.end(); ) { std::cout << "\"" << it->first << "\": \"" << it->second << "\""; if (++it != tokens.end()) std::cout << ", "; } std::cout << "},\n"; std::cout << " \"pragmas\": ["; for (size_t i = 0; i < pragmas.size(); ++i) { std::cout << "\"" << pragmas[i] << "\"" << (i < pragmas.size() - 1 ? ", " : ""); } std::cout << "],\n"; std::cout << " \"comments\": ["; for (size_t i = 0; i < comments.size(); ++i) { std::cout << "\"" << comments[i] << "\"" << (i < comments.size() - 1 ? ", " : ""); } std::cout << "],\n"; std::cout << " \"ignore\": \"" << ignore << "\",\n"; std::cout << " \"productions\": {"; for (auto it = productions.begin(); it != productions.end(); ) { std::cout << "\"" << it->first << "\": \"" << it->second << "\""; if (++it != productions.end()) std::cout << ", "; } std::cout << "},\n"; std::cout << " \"endName\": \"" << endName << "\"\n"; std::cout << "}\n"; } void write(const std::string& filepath) { std::ofstream file(filepath); if (!file.is_open()) { std::cerr << "Failed to open file for writing." << std::endl; return; } for (const auto& imp : imports) { file << imp << "\n"; } file << "COMPILER " << compilerName << "\n"; file << globalFieldsAndMethods; if (ignoreCase) file << "IGNORECASE\n"; file << "CHARACTERS\n"; for (const auto& entry : characterSets) { file << " " << entry.first << " = " << entry.second << ".\n"; } file << "TOKENS\n"; for (const auto& entry : tokens) { file << " " << entry.first << " = " << entry.second << ".\n"; } if (!pragmas.empty()) { file << "PRAGMAS\n"; for (const auto& pragma : pragmas) { file << " " << pragma << ".\n"; } } for (const auto& comment : comments) { file << comment << "\n"; } if (!ignore.empty()) file << "IGNORE " << ignore << "\n"; file << "PRODUCTIONS\n"; for (const auto& entry : productions) { file << " " << entry.first << " = " << entry.second << ".\n"; } file << "END " << endName << ".\n"; file.close(); } }; // Example usage: // int main() { // ATGFile atg("example.ATG"); // atg.printProperties(); // atg.write("output.ATG"); // return 0; // } // ===== end task-045 .ATG ===== // ===== task-046 .AU [C++] ===== #include #include #include #include #include #include class AUFileHandler { private: std::string filename; std::string magic; uint32_t dataOffset; uint32_t dataSize; uint32_t encoding; uint32_t sampleRate; uint32_t channels; std::string info; uint32_t readBigEndianUInt32(std::ifstream& file) { uint32_t value; file.read(reinterpret_cast(&value), sizeof(value)); return __builtin_bswap32(value); // Assuming little-endian host } public: AUFileHandler(const std::string& fname = "") : filename(fname), dataOffset(0), dataSize(0), encoding(0), sampleRate(0), channels(0) { if (!fname.empty()) { read(); } } void read() { std::ifstream file(filename, std::ios::binary); if (!file) { std::cerr << "Error opening file: " << filename << std::endl; return; } char magicBytes[4]; file.read(magicBytes, 4); magic = std::string(magicBytes, 4); if (magic != ".snd") { throw std::runtime_error("Invalid .AU file: Magic number mismatch"); } dataOffset = readBigEndianUInt32(file); dataSize = readBigEndianUInt32(file); encoding = readBigEndianUInt32(file); sampleRate = readBigEndianUInt32(file); channels = readBigEndianUInt32(file); uint32_t infoLength = dataOffset - 24; std::vector infoBytes(infoLength); file.read(infoBytes.data(), infoLength); auto nullIt = std::find(infoBytes.begin(), infoBytes.end(), '\0'); info = std::string(infoBytes.begin(), nullIt); } void printProperties() const { std::cout << "Magic Number: " << magic << std::endl; std::cout << "Data Offset: " << dataOffset << std::endl; std::cout << "Data Size: " << (dataSize == 0xFFFFFFFF ? "Unknown (0xFFFFFFFF)" : std::to_string(dataSize)) << std::endl; std::cout << "Encoding: " << encoding << std::endl; std::cout << "Sample Rate: " << sampleRate << " Hz" << std::endl; std::cout << "Channels: " << channels << std::endl; std::cout << "Information Chunk: " << (info.empty() ? "None" : info) << std::endl; } void write(const std::string& outputFilename, const std::vector& audioData, const std::string& infoStr, uint32_t dataSizeParam = 0xFFFFFFFF) { std::string infoWithNull = infoStr + '\0'; uint32_t infoLength = infoWithNull.size(); dataOffset = 24 + infoLength; dataSize = (dataSizeParam == 0xFFFFFFFF) ? audioData.size() : dataSizeParam; std::ofstream file(outputFilename, std::ios::binary); if (!file) { std::cerr << "Error opening output file: " << outputFilename << std::endl; return; } file.write(".snd", 4); uint32_t beDataOffset = __builtin_bswap32(dataOffset); file.write(reinterpret_cast(&beDataOffset), sizeof(beDataOffset)); uint32_t beDataSize = __builtin_bswap32(dataSize); file.write(reinterpret_cast(&beDataSize), sizeof(beDataSize)); uint32_t beEncoding = __builtin_bswap32(encoding); file.write(reinterpret_cast(&beEncoding), sizeof(beEncoding)); uint32_t beSampleRate = __builtin_bswap32(sampleRate); file.write(reinterpret_cast(&beSampleRate), sizeof(beSampleRate)); uint32_t beChannels = __builtin_bswap32(channels); file.write(reinterpret_cast(&beChannels), sizeof(beChannels)); file.write(infoWithNull.c_str(), infoLength); file.write(reinterpret_cast(audioData.data()), audioData.size()); } }; // Example usage: // int main() { // AUFileHandler handler("sample.au"); // handler.printProperties(); // std::vector dummyData(1024, 0); // handler.write("output.au", dummyData, "Sample AU File"); // return 0; // } // ===== end task-046 .AU ===== // ===== task-047 .AVI [C] ===== #include #include #include #include // Structure to hold AVI properties typedef struct { char riff_id[5]; uint32_t file_size; char file_type[5]; uint32_t microsec_per_frame; uint32_t max_bytes_per_sec; uint32_t padding_granularity; uint32_t flags; uint32_t total_frames; uint32_t initial_frames; uint32_t streams; uint32_t suggested_buffer_size; uint32_t width; uint32_t height; struct StreamHeader { char stream_type[5]; char codec[5]; uint32_t flags; uint16_t priority; uint16_t language; uint32_t initial_frames; uint32_t scale; uint32_t rate; uint32_t start; uint32_t length; uint32_t suggested_buffer_size; uint32_t quality; uint32_t sample_size; uint16_t frame_left, frame_top, frame_right, frame_bottom; } *stream_headers; struct StreamFormat { // Video uint32_t size; uint32_t width; uint32_t height; uint16_t planes; uint16_t bit_count; char compression[5]; uint32_t image_size; uint32_t xpels_per_meter; uint32_t ypels_per_meter; uint32_t colors_used; uint32_t colors_important; // Audio uint16_t format_tag; uint16_t channels; uint32_t samples_per_sec; uint32_t avg_bytes_per_sec; uint16_t block_align; uint16_t bits_per_sample; } *stream_formats; char **stream_names; struct IndexEntry { char chunk_id[5]; uint32_t flags; uint32_t offset; uint32_t size; } *index_entries; uint32_t stream_count; uint32_t index_count; uint8_t *data; size_t data_size; } AVIFile; // Initialize AVIFile AVIFile* avi_init(const char* filename) { AVIFile* avi = (AVIFile*)malloc(sizeof(AVIFile)); memset(avi, 0, sizeof(AVIFile)); strncpy(avi->riff_id, "", 5); strncpy(avi->file_type, "", 5); avi->stream_count = 0; avi->index_count = 0; avi->data = NULL; FILE* file = fopen(filename, "rb"); if (!file) { fprintf(stderr, "Error: Cannot open file %s\n", filename); free(avi); return NULL; } fseek(file, 0, SEEK_END); avi->data_size = ftell(file); fseek(file, 0, SEEK_SET); avi->data = (uint8_t*)malloc(avi->data_size); fread(avi->data, 1, avi->data_size, file); fclose(file); return avi; } // Read AVI properties int avi_read(AVIFile* avi) { size_t offset = 0; // RIFF Header if (strncmp((char*)avi->data, "RIFF", 4) != 0) { fprintf(stderr, "Error: Not a valid AVI file\n"); return -1; } strncpy(avi->riff_id, (char*)avi->data, 4); avi->riff_id[4] = '\0'; avi->file_size = *(uint32_t*)(avi->data + 4); strncpy(avi->file_type, (char*)(avi->data + 8), 4); avi->file_type[4] = '\0'; offset = 12; while (offset < avi->data_size) { char chunk_id[5]; strncpy(chunk_id, (char*)(avi->data + offset), 4); chunk_id[4] = '\0'; uint32_t chunk_size = *(uint32_t*)(avi->data + offset + 4); if (strcmp(chunk_id, "LIST") == 0 && strncmp((char*)(avi->data + offset + 8), "hdrl", 4) == 0) { offset += 12; if (strncmp((char*)(avi->data + offset), "avih", 4) == 0) { offset += 4; uint32_t avih_size = *(uint32_t*)(avi->data + offset); offset += 4; avi->microsec_per_frame = *(uint32_t*)(avi->data + offset); avi->max_bytes_per_sec = *(uint32_t*)(avi->data + offset + 4); avi->padding_granularity = *(uint32_t*)(avi->data + offset + 8); avi->flags = *(uint32_t*)(avi->data + offset + 12); avi->total_frames = *(uint32_t*)(avi->data + offset + 16); avi->initial_frames = *(uint32_t*)(avi->data + offset + 20); avi->streams = *(uint32_t*)(avi->data + offset + 24); avi->suggested_buffer_size = *(uint32_t*)(avi->data + offset + 28); avi->width = *(uint32_t*)(avi->data + offset + 32); avi->height = *(uint32_t*)(avi->data + offset + 36); offset += avih_size; } } else if (strcmp(chunk_id, "LIST") == 0 && strncmp((char*)(avi->data + offset + 8), "strl", 4) == 0) { offset += 12; avi->stream_count++; avi->stream_headers = (struct StreamHeader*)realloc(avi->stream_headers, avi->stream_count * sizeof(struct StreamHeader)); avi->stream_formats = (struct StreamFormat*)realloc(avi->stream_formats, avi->stream_count * sizeof(struct StreamFormat)); avi->stream_names = (char**)realloc(avi->stream_names, avi->stream_count * sizeof(char*)); avi->stream_names[avi->stream_count - 1] = (char*)malloc(256); avi->stream_names[avi->stream_count - 1][0] = '\0'; if (strncmp((char*)(avi->data + offset), "strh", 4) == 0) { offset += 4; uint32_t strh_size = *(uint32_t*)(avi->data + offset); offset += 4; strncpy(avi->stream_headers[avi->stream_count - 1].stream_type, (char*)(avi->data + offset), 4); avi->stream_headers[avi->stream_count - 1].stream_type[4] = '\0'; strncpy(avi->stream_headers[avi->stream_count - 1].codec, (char*)(avi->data + offset + 4), 4); avi->stream_headers[avi->stream_count - 1].codec[4] = '\0'; avi->stream_headers[avi->stream_count - 1].flags = *(uint32_t*)(avi->data + offset + 8); avi->stream_headers[avi->stream_count - 1].priority = *(uint16_t*)(avi->data + offset + 12); avi->stream_headers[avi->stream_count - 1].language = *(uint16_t*)(avi->data + offset + 14); avi->stream_headers[avi->stream_count - 1].initial_frames = *(uint32_t*)(avi->data + offset + 16); avi->stream_headers[avi->stream_count - 1].scale = *(uint32_t*)(avi->data + offset + 20); avi->stream_headers[avi->stream_count - 1].rate = *(uint32_t*)(avi->data + offset + 24); avi->stream_headers[avi->stream_count - 1].start = *(uint32_t*)(avi->data + offset + 28); avi->stream_headers[avi->stream_count - 1].length = *(uint32_t*)(avi->data + offset + 32); avi->stream_headers[avi->stream_count - 1].suggested_buffer_size = *(uint32_t*)(avi->data + offset + 36); avi->stream_headers[avi->stream_count - 1].quality = *(uint32_t*)(avi->data + offset + 40); avi->stream_headers[avi->stream_count - 1].sample_size = *(uint32_t*)(avi->data + offset + 44); avi->stream_headers[avi->stream_count - 1].frame_left = *(uint16_t*)(avi->data + offset + 48); avi->stream_headers[avi->stream_count - 1].frame_top = *(uint16_t*)(avi->data + offset + 50); avi->stream_headers[avi->stream_count - 1].frame_right = *(uint16_t*)(avi->data + offset + 52); avi->stream_headers[avi->stream_count - 1].frame_bottom = *(uint16_t*)(avi->data + offset + 54); offset += strh_size; } if (strncmp((char*)(avi->data + offset), "strf", 4) == 0) { offset += 4; uint32_t strf_size = *(uint32_t*)(avi->data + offset); offset += 4; if (strcmp(avi->stream_headers[avi->stream_count - 1].stream_type, "vids") == 0) { avi->stream_formats[avi->stream_count - 1].size = *(uint32_t*)(avi->data + offset); avi->stream_formats[avi->stream_count - 1].width = *(uint32_t*)(avi->data + offset + 4); avi->stream_formats[avi->stream_count - 1].height = *(uint32_t*)(avi->data + offset + 8); avi->stream_formats[avi->stream_count - 1].planes = *(uint16_t*)(avi->data + offset + 12); avi->stream_formats[avi->stream_count - 1].bit_count = *(uint16_t*)(avi->data + offset + 14); strncpy(avi->stream_formats[avi->stream_count - 1].compression, (char*)(avi->data + offset + 16), 4); avi->stream_formats[avi->stream_count - 1].compression[4] = '\0'; avi->stream_formats[avi->stream_count - 1].image_size = *(uint32_t*)(avi->data + offset + 20); avi->stream_formats[avi->stream_count - 1].xpels_per_meter = *(uint32_t*)(avi->data + offset + 24); avi->stream_formats[avi->stream_count - 1].ypels_per_meter = *(uint32_t*)(avi->data + offset + 28); avi->stream_formats[avi->stream_count - 1].colors_used = *(uint32_t*)(avi->data + offset + 32); avi->stream_formats[avi->stream_count - 1].colors_important = *(uint32_t*)(avi->data + offset + 36); } else if (strcmp(avi->stream_headers[avi->stream_count - 1].stream_type, "auds") == 0) { avi->stream_formats[avi->stream_count - 1].format_tag = *(uint16_t*)(avi->data + offset); avi->stream_formats[avi->stream_count - 1].channels = *(uint16_t*)(avi->data + offset + 2); avi->stream_formats[avi->stream_count - 1].samples_per_sec = *(uint32_t*)(avi->data + offset + 4); avi->stream_formats[avi->stream_count - 1].avg_bytes_per_sec = *(uint32_t*)(avi->data + offset + 8); avi->stream_formats[avi->stream_count - 1].block_align = *(uint16_t*)(avi->data + offset + 12); avi->stream_formats[avi->stream_count - 1].bits_per_sample = *(uint16_t*)(avi->data + offset + 14); } offset += strf_size; } if (strncmp((char*)(avi->data + offset), "strn", 4) == 0) { offset += 4; uint32_t strn_size = *(uint32_t*)(avi->data + offset); offset += 4; strncpy(avi->stream_names[avi->stream_count - 1], (char*)(avi->data + offset), strn_size); avi->stream_names[avi->stream_count - 1][strn_size] = '\0'; offset += strn_size; } } else if (strcmp(chunk_id, "idx1") == 0) { offset += 4; uint32_t idx_size = *(uint32_t*)(avi->data + offset); offset += 4; avi->index_count = idx_size / 16; avi->index_entries = (struct IndexEntry*)malloc(avi->index_count * sizeof(struct IndexEntry)); for (uint32_t i = 0; i < avi->index_count; i++) { strncpy(avi->index_entries[i].chunk_id, (char*)(avi->data + offset + i * 16), 4); avi->index_entries[i].chunk_id[4] = '\0'; avi->index_entries[i].flags = *(uint32_t*)(avi->data + offset + i * 16 + 4); avi->index_entries[i].offset = *(uint32_t*)(avi->data + offset + i * 16 + 8); avi->index_entries[i].size = *(uint32_t*)(avi->data + offset + i * 16 + 12); } offset += idx_size; } else { offset += chunk_size + 8; if (chunk_size % 2) offset++; // Padding } } return 0; } // Print AVI properties void avi_print_properties(AVIFile* avi) { printf("AVI File Properties:\n"); printf("RIFF ID: %s\n", avi->riff_id); printf("File Size: %u bytes\n", avi->file_size); printf("File Type: %s\n", avi->file_type); printf("\nMain AVI Header:\n"); printf(" Microseconds Per Frame: %u\n", avi->microsec_per_frame); printf(" Max Bytes Per Second: %u\n", avi->max_bytes_per_sec); printf(" Padding Granularity: %u\n", avi->padding_granularity); printf(" Flags: %08x\n", avi->flags); printf(" Total Frames: %u\n", avi->total_frames); printf(" Initial Frames: %u\n", avi->initial_frames); printf(" Number of Streams: %u\n", avi->streams); printf(" Suggested Buffer Size: %u\n", avi->suggested_buffer_size); printf(" Width: %u pixels\n", avi->width); printf(" Height: %u pixels\n"); for (uint32_t i = 0; i < avi->stream_count; i++) { printf("\nStream %u Header:\n", i); printf(" Stream Type: %s\n", avi->stream_headers[i].stream_type); printf(" Codec: %s\n", avi->stream_headers[i].codec); printf(" Flags: %08x\n", avi->stream_headers[i].flags); printf(" Priority: %u\n", avi->stream_headers[i].priority); printf(" Language: %u\n", avi->stream_headers[i].language); printf(" Initial Frames: %u\n", avi->stream_headers[i].initial_frames); printf(" Scale: %u\n", avi->stream_headers[i].scale); printf(" Rate: %u\n", avi->stream_headers[i].rate); printf(" Start: %u\n", avi->stream_headers[i].start); printf(" Length: %u\n", avi->stream_headers[i].length); printf(" Suggested Buffer Size: %u\n", avi->stream_headers[i].suggested_buffer_size); printf(" Quality: %u\n", avi->stream_headers[i].quality); printf(" Sample Size: %u\n", avi->stream_headers[i].sample_size); printf(" Frame Left: %u\n", avi->stream_headers[i].frame_left); printf(" Frame Top: %u\n", avi->stream_headers[i].frame_top); printf(" Frame Right: %u\n", avi->stream_headers[i].frame_right); printf(" Frame Bottom: %u\n", avi->stream_headers[i].frame_bottom); printf("Stream %u Format:\n", i); if (strcmp(avi->stream_headers[i].stream_type, "vids") == 0) { printf(" Size: %u\n", avi->stream_formats[i].size); printf(" Width: %u\n", avi->stream_formats[i].width); printf(" Height: %u\n", avi->stream_formats[i].height); printf(" Planes: %u\n", avi->stream_formats[i].planes); printf(" Bit Count: %u\n", avi->stream_formats[i].bit_count); printf(" Compression: %s\n", avi->stream_formats[i].compression); printf(" Image Size: %u\n", avi->stream_formats[i].image_size); printf(" XPels Per Meter: %u\n", avi->stream_formats[i].xpels_per_meter); printf(" YPels Per Meter: %u\n", avi->stream_formats[i].ypels_per_meter); printf(" Colors Used: %u\n", avi->stream_formats[i].colors_used); printf(" Colors Important: %u\n", avi->stream_formats[i].colors_important); } else if (strcmp(avi->stream_headers[i].stream_type, "auds") == 0) { printf(" Format Tag: %u\n", avi->stream_formats[i].format_tag); printf(" Channels: %u\n", avi->stream_formats[i].channels); printf(" Samples Per Second: %u\n", avi->stream_formats[i].samples_per_sec); printf(" Avg Bytes Per Second: %u\n", avi->stream_formats[i].avg_bytes_per_sec); printf(" Block Align: %u\n", avi->stream_formats[i].block_align); printf(" Bits Per Sample: %u\n", avi->stream_formats[i].bits_per_sample); } if (avi->stream_names[i][0]) { printf("Stream %u Name: %s\n", i, avi->stream_names[i]); } } if (avi->index_count > 0) { printf("\nIndex Entries:\n"); for (uint32_t i = 0; i < avi->index_count; i++) { printf(" Entry %u: Chunk ID: %s, Flags: %08x, Offset: %u, Size: %u\n", i, avi->index_entries[i].chunk_id, avi->index_entries[i].flags, avi->index_entries[i].offset, avi->index_entries[i].size); } } } // Write AVI file int avi_write(AVIFile* avi, const char* output_filename) { FILE* file = fopen(output_filename, "wb"); if (!file) { fprintf(stderr, "Error: Cannot open output file %s\n", output_filename); return -1; } fwrite(avi->data, 1, avi->data_size, file); fclose(file); return 0; } // Free AVI resources void avi_free(AVIFile* avi) { if (avi->stream_headers) free(avi->stream_headers); if (avi->stream_formats) free(avi->stream_formats); if (avi->stream_names) { for (uint32_t i = 0; i < avi->stream_count; i++) { if (avi->stream_names[i]) free(avi->stream_names[i]); } free(avi->stream_names); } if (avi->index_entries) free(avi->index_entries); if (avi->data) free(avi->data); free(avi); } int main() { AVIFile* avi = avi_init("sample.avi"); if (!avi) return 1; if (avi_read(avi) != 0) { avi_free(avi); return 1; } avi_print_properties(avi); avi_write(avi, "output.avi"); avi_free(avi); return 0; } #include #include #include #include typedef struct { char *filename; // Use a struct for properties, e.g. struct Properties { uint32_t file_size; char file_type[5]; /* etc */ }; // void *properties; // Use map-like or struct } AVIParser; void init_avi_parser(AVIParser *parser, char *filename) { parser->filename = strdup(filename); FILE *f = fopen(filename, "rb"); fseek(f, 0, SEEK_END); long len = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(len); fread(data, 1, len, f); fclose(f); // Parse similar to Python, using memcpy for fields // Stubbed full parse } uint32_t read_property(AVIParser *parser, char *key) { // Return based on key return 0; // Stub } void write_property(AVIParser *parser, char *key, uint32_t value) { // Set } void save_avi_parser(AVIParser *parser, char *filename) { // Write } void free_avi_parser(AVIParser *parser) { free(parser->filename); } // ===== end task-047 .AVI ===== // ===== task-048 .AVIF [C++] ===== #include #include #include #include #include class AVIFParser { private: std::string filename; std::map> boxes; std::map properties; // Use variant for different types public: AVIFParser(const std::string& fn) : filename(fn) { parse(); } void parse() { std::ifstream file(filename, std::ios::binary); std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); size_t pos = 0; while (pos < data.size()) { uint32_t size = (data[pos] << 24) | (data[pos+1] << 16) | (data[pos+2] << 8) | data[pos+3]; std::string boxType(data.begin() + pos + 4, data.begin() + pos + 8); size_t headerSize = 8; if (size == 1) { uint64_t largeSize = ((uint64_t)data[pos+8] << 56) | ((uint64_t)data[pos+9] << 48) | // etc size = static_cast(largeSize); headerSize = 16; } std::vector boxData(data.begin() + pos + headerSize, data.begin() + pos + size); boxes[boxType] = boxData; pos += size; if (boxType == "ftyp") { // Parse similar } // etc. } } void write(const std::string& newFilename) { // Similar } }; // ===== end task-048 .AVIF ===== // ===== task-048 .AVIF [C] ===== #include #include #include #include typedef struct { char* filepath; avifImage* image; avifDecoder* decoder; struct { char* file_extension; char* mime_type; char* container_format; char* compression_codec; uint32_t width; uint32_t height; uint8_t bit_depth; int has_alpha; char* color_space; long file_size; char* major_brand; char* compatible_brands[8]; int is_animated; char* compression_mode; } properties; } AVIFHandler; void avif_handler_init(AVIFHandler* handler, const char* filepath) { handler->filepath = strdup(filepath); handler->image = NULL; handler->decoder = NULL; handler->properties.file_extension = ".avif"; handler->properties.mime_type = "image/avif"; handler->properties.container_format = "HEIF/ISOBMFF"; handler->properties.compression_codec = "AV1"; handler->properties.color_space = "sRGB/BT.709"; handler->properties.compression_mode = "Lossy"; } void avif_handler_read_properties(AVIFHandler* handler) { FILE* file = fopen(handler->filepath, "rb"); if (!file || strstr(handler->filepath, ".avif") == NULL) { printf("Error: Invalid AVIF file\n"); return; } // Decode AVIF handler->decoder = avifDecoderCreate(); avifResult result = avifDecoderReadFile(handler->decoder, handler->filepath, &handler->image); if (result != AVIF_RESULT_OK) { printf("Error decoding AVIF: %s\n", avifResultToString(result)); fclose(file); return; } // Extract properties handler->properties.width = handler->image->width; handler->properties.height = handler->image->height; handler->properties.bit_depth = handler->image->depth; handler->properties.has_alpha = handler->image->alphaPlane != NULL; fseek(file, 0, SEEK_END); handler->properties.file_size = ftell(file); // Read ftyp box (simplified) fseek(file, 8, SEEK_SET); char ftyp[5] = {0}; fread(ftyp, 1, 4, file); handler->properties.major_brand = strdup(ftyp); char brands[9] = {0}; fread(brands, 1, 8, file); for (int i = 0; i < 2; i++) { handler->properties.compatible_brands[i] = strndup(brands + i*4, 4); } handler->properties.is_animated = handler->decoder->imageCount > 1; fclose(file); } void avif_handler_print_properties(AVIFHandler* handler) { printf("file_extension: %s\n", handler->properties.file_extension); printf("mime_type: %s\n", handler->properties.mime_type); printf("container_format: %s\n", handler->properties.container_format); printf("compression_codec: %s\n", handler->properties.compression_codec); printf("width: %u\n", handler->properties.width); printf("height: %u\n", handler->properties.height); printf("bit_depth: %u\n", handler->properties.bit_depth); printf("has_alpha: %d\n", handler->properties.has_alpha); printf("color_space: %s\n", handler->properties.color_space); printf("file_size: %ld\n", handler->properties.file_size); printf("major_brand: %s\n", handler->properties.major_brand); printf("compatible_brands: %s %s\n", handler->properties.compatible_brands[0], handler->properties.compatible_brands[1]); printf("is_animated: %d\n", handler->properties.is_animated); printf("compression_mode: %s\n", handler->properties.compression_mode); } void avif_handler_write_avif(AVIFHandler* handler, const char* output_path, int quality) { if (!handler->image) { printf("No image loaded to write\n"); return; } avifEncoder* encoder = avifEncoderCreate(); encoder->quality = quality; avifRWData output = AVIF_DATA_EMPTY; avifResult result = avifEncoderWrite(encoder, handler->image, &output); if (result == AVIF_RESULT_OK) { FILE* out = fopen(output_path, "wb"); fwrite(output.data, 1, output.size, out); fclose(out); printf("AVIF file written to %s\n", output_path); } else { printf("Error writing AVIF: %s\n", avifResultToString(result)); } avifRWDataFree(&output); avifEncoderDestroy(encoder); } void avif_handler_destroy(AVIFHandler* handler) { if (handler->image) avifImageDestroy(handler->image); if (handler->decoder) avifDecoderDestroy(handler->decoder); free(handler->filepath); free(handler->properties.major_brand); for (int i = 0; i < 2; i++) free(handler->properties.compatible_brands[i]); } int main() { AVIFHandler handler; avif_handler_init(&handler, "sample.avif"); avif_handler_read_properties(&handler); avif_handler_print_properties(&handler); avif_handler_write_avif(&handler, "output.avif", 50); avif_handler_destroy(&handler); return 0; } // ===== end task-048 .AVIF ===== // ===== task-049 .AWK [C] ===== fseek(file, 0, SEEK_END); long size = ftell(file); fseek(file, 0, SEEK_SET); char* content = (char*)malloc(size + 1); fread(content, 1, size, file); content[size] = '\0'; fclose(file); handler->file_extension = strdup(strrchr(handler->filepath, '.') ? strrchr(handler->filepath, '.') : ".awk"); handler->content_type = strdup("text/plain"); handler->shebang = content[0] == '#' && content[1] == '!' ? strdup(strtok(strdup(content), "\n")) : strdup("No shebang"); handler->encoding = strdup("utf-8"); struct stat st; stat(handler->filepath, &st); char perm[10]; snprintf(perm, sizeof(perm), "%o", st.st_mode & 0777); handler->permissions = strdup(perm); handler->structure = strstr(content, "{") ? strdup("Contains AWK patterns and actions") : strdup("Empty or invalid AWK script"); handler->os_compatibility = strdup("Unix/Linux"); handler->file_size = size; handler->purpose = strdup("Text manipulation and report generation"); return content; // ===== end task-049 .AWK ===== // ===== task-050 .AX [C] ===== #include #include #include typedef struct { const char* filepath; char* properties[12][2]; // Key-value pairs for properties } AXFileHandler; void init_ax_file_handler(AXFileHandler* handler, const char* filepath) { handler->filepath = filepath; } void read_properties(AXFileHandler* handler) { WIN32_FILE_ATTRIBUTE_DATA fileInfo; if (!GetFileAttributesEx(handler->filepath, GetFileExInfoStandard, &fileInfo)) { printf("Error reading file attributes: %lu\n", GetLastError()); return; } // File system properties sprintf(handler->properties[0][0], "File Extension"); sprintf(handler->properties[0][1], ".ax"); sprintf(handler->properties[1][0], "File Type"); sprintf(handler->properties[1][1], "DirectShow Filter (DLL)"); sprintf(handler->properties[2][0], "MIME Type"); sprintf(handler->properties[2][1], "application/octet-stream"); sprintf(handler->properties[3][0], "File Size"); sprintf(handler->properties[3][1], "%llu", ((unsigned long long)fileInfo.nFileSizeHigh << 32) | fileInfo.nFileSizeLow); sprintf(handler->properties[4][0], "File Path"); sprintf(handler->properties[4][1], "%s", handler->filepath); char timeStr[32]; FILETIME ft = fileInfo.ftCreationTime; struct tm* timeinfo; time_t rawtime = FileTimeToUnixTime(&ft); timeinfo = gmtime(&rawtime); strftime(timeStr, sizeof(timeStr), "%Y-%m-%dT%H:%M:%SZ", timeinfo); sprintf(handler->properties[5][0], "Creation Date"); sprintf(handler->properties[5][1], "%s", timeStr); ft = fileInfo.ftLastWriteTime; rawtime = FileTimeToUnixTime(&ft); timeinfo = gmtime(&rawtime); strftime(timeStr, sizeof(timeStr), "%Y-%m-%dT%H:%M:%SZ", timeinfo); sprintf(handler->properties[6][0], "Modification Date"); sprintf(handler->properties[6][1], "%s", timeStr); ft = fileInfo.ftLastAccessTime; rawtime = FileTimeToUnixTime(&ft); timeinfo = gmtime(&rawtime); strftime(timeStr, sizeof(timeStr), "%Y-%m-%dT%H:%M:%SZ", timeinfo); sprintf(handler->properties[7][0], "Access Date"); sprintf(handler->properties[7][1], "%s", timeStr); sprintf(handler->properties[8][0], "File Attributes"); char attrs[64] = ""; if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_READONLY) strcat(attrs, "Read-Only, "); if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) strcat(attrs, "Hidden, "); if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) strcat(attrs, "System, "); sprintf(handler->properties[8][1], "%s", attrs[0] ? attrs : "None"); sprintf(handler->properties[9][0], "DLL Version"); sprintf(handler->properties[9][1], "Unknown"); // Requires PE parsing sprintf(handler->properties[10][0], "Digital Signature"); sprintf(handler->properties[10][1], "Unknown"); sprintf(handler->properties[11][0], "Filter Type"); sprintf(handler->properties[11][1], guess_filter_type(handler->filepath)); } void write_properties(AXFileHandler* handler, const char* output_filepath) { if (CopyFile(handler->filepath, output_filepath, FALSE)) { printf("Properties written to %s\n", output_filepath); } else { printf("Error writing file: %lu\n", GetLastError()); } } void print_properties(AXFileHandler* handler) { for (int i = 0; i < 12; i++) { printf("%s: %s\n", handler->properties[i][0], handler->properties[i][1]); } } const char* guess_filter_type(const char* filepath) { if (strstr(filepath, "mpeg") || strstr(filepath, "MPEG")) { return "Parsing Filter (likely MPEG-related)"; } else if (strstr(filepath, "render") || strstr(filepath, "RENDER")) { return "Rendering Filter"; } return "Unknown Filter Type"; } time_t FileTimeToUnixTime(FILETIME* ft) { ULARGE_INTEGER ull; ull.LowPart = ft->dwLowDateTime; ull.HighPart = ft->dwHighDateTime; return ull.QuadPart / 10000000ULL - 11644473600ULL; } int main() { AXFileHandler handler; init_ax_file_handler(&handler, "example.ax"); read_properties(&handler); print_properties(&handler); write_properties(&handler, "output.ax"); return 0; } // ===== end task-050 .AX ===== // ===== task-051 .AXF [C] ===== #include #include #include #include typedef struct { char* filename; char* file_container; char** lightweight_filesystem; int file_count; int self_describing; char** metadata; int metadata_count; int immutable; char* storage_media; char* filesystem_abstraction; char* checksum; unsigned int version; char* media_footer; int interoperability; int preservation; } AXFHandler; AXFHandler* create_axf_handler(const char* filename) { AXFHandler* handler = (AXFHandler*)malloc(sizeof(AXFHandler)); handler->filename = strdup(filename); handler->file_container = NULL; handler->lightweight_filesystem = NULL; handler->file_count = 0; handler->self_describing = 0; handler->metadata = NULL; handler->metadata_count = 0; handler->immutable = 1; handler->storage_media = NULL; handler->filesystem_abstraction = NULL; handler->checksum = NULL; handler->version = 1; handler->media_footer = NULL; handler->interoperability = 1; handler->preservation = 1; return handler; } void free_axf_handler(AXFHandler* handler) { free(handler->filename); free(handler->file_container); if (handler->lightweight_filesystem) { for (int i = 0; i < handler->file_count; i++) free(handler->lightweight_filesystem[i]); free(handler->lightweight_filesystem); } if (handler->metadata) { for (int i = 0; i < handler->metadata_count; i++) free(handler->metadata[i]); free(handler->metadata); } free(handler->storage_media); free(handler->filesystem_abstraction); free(handler->checksum); free(handler->media_footer); free(handler); } int open_axf(AXFHandler* handler) { FILE* file = fopen(handler->filename, "rb"); if (!file) { printf("Error opening AXF file: %s\n", handler->filename); return 1; } // Read header unsigned char header[12]; if (fread(header, 1, 12, file) != 12) { printf("Invalid AXF file: too short\n"); fclose(file); return 1; } if (strncmp((char*)header, "AXF\0", 4) != 0) { printf("Invalid AXF file: wrong magic number\n"); fclose(file); return 1; } handler->version = (header[4] << 24) | (header[5] << 16) | (header[6] << 8) | header[7]; handler->file_count = (header[8] << 24) | (header[9] << 16) | (header[10] << 8) | header[11]; handler->file_container = (char*)malloc(50); snprintf(handler->file_container, 50, "Container with %d files", handler->file_count); handler->self_describing = 1; // Read metadata unsigned int metadata_len; fread(&metadata_len, 4, 1, file); char* metadata_str = (char*)malloc(metadata_len + 1); fread(metadata_str, 1, metadata_len, file); metadata_str[metadata_len] = '\0'; // Parse metadata (split by ';') handler->metadata_count = 1; for (char* p = metadata_str; *p; p++) if (*p == ';') handler->metadata_count++; handler->metadata = (char**)malloc(handler->metadata_count * sizeof(char*)); char* token = strtok(metadata_str, ";"); for (int i = 0; token; i++) { handler->metadata[i] = strdup(token); token = strtok(NULL, ";"); } free(metadata_str); // Read file list handler->lightweight_filesystem = (char**)malloc(handler->file_count * sizeof(char*)); for (int i = 0; i < handler->file_count; i++) { unsigned int name_len; fread(&name_len, 4, 1, file); handler->lightweight_filesystem[i] = (char*)malloc(name_len + 1); fread(handler->lightweight_filesystem[i], 1, name_len, file); handler->lightweight_filesystem[i][name_len] = '\0'; } // Read checksum fseek(file, -32, SEEK_END); unsigned char checksum[32]; fread(checksum, 1, 32, file); handler->checksum = (char*)malloc(65); for (int i = 0; i < 32; i++) sprintf(handler->checksum + 2*i, "%02x", checksum[i]); // Set other properties handler->storage_media = strdup("Detected from file system"); handler->filesystem_abstraction = strdup("Universal view"); handler->media_footer = strdup("Present"); fclose(file); return 0; } int write_axf(AXFHandler* handler, const char** files, int file_count, const char** metadata, int metadata_count) { FILE* file = fopen(handler->filename, "wb"); if (!file) { printf("Error writing AXF file: %s\n", handler->filename); return 1; } // Write header fwrite("AXF\0", 1, 4, file); fwrite(&handler->version, 4, 1, file); fwrite(&file_count, 4, 1, file); // Write metadata char* metadata_str = (char*)malloc(1024); metadata_str[0] = '\0'; for (int i = 0; i < metadata_count; i++) { strcat(metadata_str, metadata[i]); if (i < metadata_count - 1) strcat(metadata_str, ";"); } unsigned int metadata_len = strlen(metadata_str); fwrite(&metadata_len, 4, 1, file); fwrite(metadata_str, 1, metadata_len, file); free(metadata_str); // Write file list for (int i = 0; i < file_count; i++) { unsigned int name_len = strlen(files[i]); fwrite(&name_len, 4, 1, file); fwrite(files[i], 1, name_len, file); } // Write file contents for (int i = 0; i < file_count; i++) { FILE* src = fopen(files[i], "rb"); if (!src) continue; char buffer[1024]; size_t bytes; while ((bytes = fread(buffer, 1, 1024, src)) > 0) { fwrite(buffer, 1, bytes, file); } fclose(src); } // Write checksum fseek(file, 0, SEEK_SET); unsigned char buffer[1024]; SHA256_CTX sha256; SHA256_Init(&sha256); size_t bytes; while ((bytes = fread(buffer, 1, 1024, file)) > 0) { SHA256_Update(&sha256, buffer, bytes); } unsigned char checksum[32]; SHA256_Final(checksum, &sha256); fwrite(checksum, 1, 32, file); handler->file_count = file_count; handler->lightweight_filesystem = (char**)malloc(file_count * sizeof(char*)); for (int i = 0; i < file_count; i++) handler->lightweight_filesystem[i] = strdup(files[i]); handler->metadata_count = metadata_count; handler->metadata = (char**)malloc(metadata_count * sizeof(char*)); for (int i = 0; i < metadata_count; i++) handler->metadata[i] = strdup(metadata[i]); handler->checksum = (char*)malloc(65); for (int i = 0; i < 32; i++) sprintf(handler->checksum + 2*i, "%02x", checksum[i]); fclose(file); return 0; } void print_properties(AXFHandler* handler) { printf("file_container: %s\n", handler->file_container ? handler->file_container : "null"); printf("lightweight_filesystem: "); if (handler->lightweight_filesystem) { for (int i = 0; i < handler->file_count; i++) { printf("%s%s", handler->lightweight_filesystem[i], i < handler->file_count - 1 ? ", " : ""); } } else { printf("null"); } printf("\n"); printf("self_describing: %d\n", handler->self_describing); printf("metadata: "); if (handler->metadata) { for (int i = 0; i < handler->metadata_count; i++) { printf("%s%s", handler->metadata[i], i < handler->metadata_count - 1 ? ", " : ""); } } else { printf("null"); } printf("\n"); printf("immutable: %d\n", handler->immutable); printf("storage_media: %s\n", handler->storage_media ? handler->storage_media : "null"); printf("filesystem_abstraction: %s\n", handler->filesystem_abstraction ? handler->filesystem_abstraction : "null"); printf("checksum: %s\n", handler->checksum ? handler->checksum : "null"); printf("version: %u\n", handler->version); printf("media_footer: %s\n", handler->media_footer ? handler->media_footer : "null"); printf("interoperability: %d\n", handler->interoperability); printf("preservation: %d\n", handler->preservation); } int main() { AXFHandler* axf = create_axf_handler("example.axf"); const char* files[] = {"file1.txt", "file2.jpg"}; const char* metadata[] = {"creator=John", "date=2025-09-09"}; write_axf(axf, files, 2, metadata, 2); open_axf(axf); print_properties(axf); free_axf_handler(axf); return 0; } // ===== end task-051 .AXF ===== // ===== task-052 .B [C] ===== #include #include #include #include #define AUTHOR_NAME_SIZE 32 typedef struct { char* filename; char magic[4]; unsigned int version; unsigned int file_size; unsigned long long creation_timestamp; char author_name[AUTHOR_NAME_SIZE]; unsigned int data_length; unsigned char* data_payload; } BFile; void bfile_init(BFile* bfile, const char* filename) { bfile->filename = strdup(filename); memcpy(bfile->magic, "BFRM", 4); bfile->version = 1; bfile->file_size = 0; bfile->creation_timestamp = 0; memset(bfile->author_name, 0, AUTHOR_NAME_SIZE); bfile->data_length = 0; bfile->data_payload = NULL; } void bfile_free(BFile* bfile) { free(bfile->filename); free(bfile->data_payload); } int bfile_read(BFile* bfile) { FILE* fp = fopen(bfile->filename, "rb"); if (!fp) { printf("Error opening file: %s\n", bfile->filename); return 1; } // Read header char magic[4]; if (fread(magic, 1, 4, fp) != 4 || memcmp(magic, bfile->magic, 4) != 0) { printf("Invalid .B file: incorrect magic number\n"); fclose(fp); return 1; } if (fread(&bfile->version, sizeof(unsigned int), 1, fp) != 1) { printf("Error reading version\n"); fclose(fp); return 1; } // Read metadata if (fread(&bfile->file_size, sizeof(unsigned int), 1, fp) != 1 || fread(&bfile->creation_timestamp, sizeof(unsigned long long), 1, fp) != 1 || fread(bfile->author_name, 1, AUTHOR_NAME_SIZE, fp) != AUTHOR_NAME_SIZE) { printf("Error reading metadata\n"); fclose(fp); return 1; } bfile->author_name[AUTHOR_NAME_SIZE - 1] = '\0'; // Read data section if (fread(&bfile->data_length, sizeof(unsigned int), 1, fp) != 1) { printf("Error reading data length\n"); fclose(fp); return 1; } bfile->data_payload = malloc(bfile->data_length); if (!bfile->data_payload || fread(bfile->data_payload, 1, bfile->data_length, fp) != bfile->data_length) { printf("Error reading data payload\n"); free(bfile->data_payload); fclose(fp); return 1; } fclose(fp); return 0; } int bfile_write(BFile* bfile, const char* author_name, const unsigned char* data_payload, unsigned int data_length) { FILE* fp = fopen(bfile->filename, "wb"); if (!fp) { printf("Error opening file: %s\n", bfile->filename); return 1; } // Write header fwrite(bfile->magic, 1, 4, fp); fwrite(&bfile->version, sizeof(unsigned int), 1, fp); // Write metadata bfile->creation_timestamp = (unsigned long long)time(NULL); bfile->data_length = data_length; bfile->file_size = 8 + 44 + 4 + data_length; strncpy(bfile->author_name, author_name, AUTHOR_NAME_SIZE); bfile->author_name[AUTHOR_NAME_SIZE - 1] = '\0'; fwrite(&bfile->file_size, sizeof(unsigned int), 1, fp); fwrite(&bfile->creation_timestamp, sizeof(unsigned long long), 1, fp); fwrite(bfile->author_name, 1, AUTHOR_NAME_SIZE, fp); // Write data section fwrite(&bfile->data_length, sizeof(unsigned int), 1, fp); bfile->data_payload = malloc(data_length); memcpy(bfile->data_payload, data_payload, data_length); fwrite(bfile->data_payload, 1, data_length, fp); fclose(fp); return 0; } void bfile_print_properties(BFile* bfile) { printf("File Extension: .B\n"); printf("File Size: %u bytes\n", bfile->file_size); printf("Creation Timestamp: %llu\n", bfile->creation_timestamp); printf("Author Name: %s\n", bfile->author_name); printf("Data Length: %u bytes\n", bfile->data_length); printf("Data Payload: %.*s\n", bfile->data_length, bfile->data_payload); } int main() { BFile bfile; bfile_init(&bfile, "example.b"); const char* data = "Sample data for .B file"; bfile_write(&bfile, "John Doe", (unsigned char*)data, strlen(data)); bfile_read(&bfile); bfile_print_properties(&bfile); bfile_free(&bfile); return 0; } // ===== end task-052 .B ===== // ===== task-054 .B64 [C] ===== #include #include #include // Base64 encoding/decoding table static const char b64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static const char *properties[] = { "File Extension: .b64", "Format Type: Binary-to-text encoding scheme using Base64", "Encoding Characters: A-Z, a-z, 0-9, +, /", "Padding Character: =", "MIME Type: application/base64", "Line Length: 76 characters per line (MIME), no limit (RFC 4648)", "Size Increase: Approximately 33%", "Character Encoding: ASCII text", "File Content: Represents binary data in text format" }; typedef struct { const char *filename; } B64FileHandler; // Base64 decode function unsigned char *b64_decode(const char *input, size_t *out_len) { size_t len = strlen(input), i, j; if (len % 4 != 0) return NULL; // Invalid length *out_len = len / 4 * 3; if (input[len - 1] == '=') (*out_len)--; if (input[len - 2] == '=') (*out_len)--; unsigned char *output = malloc(*out_len); if (!output) return NULL; for (i = 0, j = 0; i < len; i += 4, j += 3) { unsigned int val = 0; for (int k = 0; k < 4; k++) { char c = input[i + k]; if (c >= 'A' && c <= 'Z') val = (val << 6) | (c - 'A'); else if (c >= 'a' && c <= 'z') val = (val << 6) | (c - 'a' + 26); else if (c >= '0' && c <= '9') val = (val << 6) | (c - '0' + 52); else if (c == '+') val = (val << 6) | 62; else if (c == '/') val = (val << 6) | 63; else if (c == '=') val = val << 6; } output[j] = (val >> 16) & 0xFF; if (j + 1 < *out_len) output[j + 1] = (val >> 8) & 0xFF; if (j + 2 < *out_len) output[j + 2] = val & 0xFF; } return output; } // Base64 encode function char *b64_encode(const unsigned char *input, size_t len) { size_t out_len = ((len + 2) / 3) * 4; char *output = malloc(out_len + 1); if (!output) return NULL; size_t i, j; for (i = 0, j = 0; i < len; i += 3, j += 4) { unsigned int val = (input[i] << 16) | (i + 1 < len ? input[i + 1] << 8 : 0) | (i + 2 < len ? input[i + 2] : 0); output[j] = b64_table[(val >> 18) & 0x3F]; output[j + 1] = b64_table[(val >> 12) & 0x3F]; output[j + 2] = i + 1 < len ? b64_table[(val >> 6) & 0x3F] : '='; output[j + 3] = i + 2 < len ? b64_table[val & 0x3F] : '='; } output[out_len] = '\0'; return output; } B64FileHandler *b64_file_handler_new(const char *filename) { B64FileHandler *handler = malloc(sizeof(B64FileHandler)); if (handler) handler->filename = filename; return handler; } void b64_file_handler_free(B64FileHandler *handler) { free(handler); } unsigned char *b64_file_handler_read_and_decode(B64FileHandler *handler, size_t *out_len) { FILE *file = fopen(handler->filename, "r"); if (!file) { fprintf(stderr, "Error: File %s not found.\n", handler->filename); return NULL; } fseek(file, 0, SEEK_END); long len = ftell(file); fseek(file, 0, SEEK_SET); char *encoded_data = malloc(len + 1); if (!encoded_data) { fclose(file); return NULL; } fread(encoded_data, 1, len, file); encoded_data[len] = '\0'; fclose(file); unsigned char *decoded = b64_decode(encoded_data, out_len); free(encoded_data); return decoded; } void b64_file_handler_write(B64FileHandler *handler, const unsigned char *data, size_t len, const char *output_filename) { char *encoded_data = b64_encode(data, len); if (!encoded_data) { fprintf(stderr, "Error: Encoding failed.\n"); return; } FILE *file = fopen(output_filename, "w"); if (!file) { fprintf(stderr, "Error: Could not write to %s.\n", output_filename); free(encoded_data); return; } fprintf(file, "%s", encoded_data); fclose(file); free(encoded_data); printf("Successfully wrote to %s\n", output_filename); } void b64_file_handler_print_properties(B64FileHandler *handler) { printf("Properties of .B64 File Format:\n"); for (int i = 0; i < 9; i++) { printf("%s\n", properties[i]); } } int main() { B64FileHandler *handler = b64_file_handler_new("sample.b64"); const char *sample_data = "Hello, World!"; b64_file_handler_write(handler, (const unsigned char *)sample_data, strlen(sample_data), "sample.b64"); size_t decoded_len; unsigned char *decoded = b64_file_handler_read_and_decode(handler, &decoded_len); if (decoded) { printf("Decoded data: %.*s\n", (int)decoded_len, decoded); free(decoded); } b64_file_handler_print_properties(handler); b64_file_handler_free(handler); return 0; } // ===== end task-054 .B64 ===== // ===== task-055 .BAK [C] ===== #include #include #include #include #include #include typedef struct { char* file_extension; char* file_format; long long file_size; char* database_name; char* backup_timestamp; int sql_server_version; char* backup_type; int media_family_count; int compression_status; int encryption_status; int checksum; } BakProperties; void init_properties(BakProperties* props) { props->file_extension = NULL; props->file_format = "Microsoft Tape Format (MTF)"; props->file_size = 0; props->database_name = NULL; props->backup_timestamp = NULL; props->sql_server_version = 0; props->backup_type = NULL; props->media_family_count = 0; props->compression_status = 0; props->encryption_status = 0; props->checksum = 0; } void free_properties(BakProperties* props) { free(props->file_extension); free(props->database_name); free(props->backup_timestamp); free(props->backup_type); } SQLHDBC connect_to_sql_server(const char* server, const char* database) { SQLHENV env; SQLHDBC conn; SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env); SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); SQLAllocHandle(SQL_HANDLE_DBC, env, &conn); char conn_str[256]; snprintf(conn_str, sizeof(conn_str), "DRIVER={SQL Server};SERVER=%s;DATABASE=%s;Trusted_Connection=yes", server, database); SQLRETURN ret = SQLDriverConnect(conn, NULL, (SQLCHAR*)conn_str, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT); if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) { printf("Error connecting to SQL Server\n"); SQLFreeHandle(SQL_HANDLE_DBC, conn); SQLFreeHandle(SQL_HANDLE_ENV, env); return NULL; } return conn; } void read_properties(const char* file_path, BakProperties* props) { struct stat st; if (stat(file_path, &st) == 0) { props->file_size = st.st_size; } char* ext = strrchr(file_path, '.'); if (ext) { props->file_extension = strdup(ext); } SQLHDBC conn = connect_to_sql_server("localhost", "master"); if (conn) { SQLHSTMT stmt; SQLAllocHandle(SQL_HANDLE_STMT, conn, &stmt); char query[512]; snprintf(query, sizeof(query), "RESTORE HEADERONLY FROM DISK = '%s'", file_path); if (SQLExecDirect(stmt, (SQLCHAR*)query, SQL_NTS) == SQL_SUCCESS) { char db_name[256], backup_type[50], timestamp[50]; SQLBindCol(stmt, 1, SQL_C_CHAR, db_name, sizeof(db_name), NULL); SQLBindCol(stmt, 15, SQL_C_TYPE_TIMESTAMP, timestamp, sizeof(timestamp), NULL); SQLBindCol(stmt, 17, SQL_C_LONG, &props->sql_server_version, 0, NULL); SQLBindCol(stmt, 3, SQL_C_CHAR, backup_type, sizeof(backup_type), NULL); SQLBindCol(stmt, 10, SQL_C_LONG, &props->media_family_count, 0, NULL); SQLBindCol(stmt, 44, SQL_C_BIT, &props->compression_status, 0, NULL); SQLBindCol(stmt, 45, SQL_C_BIT, &props->encryption_status, 0, NULL); SQLBindCol(stmt, 13, SQL_C_BIT, &props->checksum, 0, NULL); if (SQLFetch(stmt) == SQL_SUCCESS) { props->database_name = strdup(db_name); props->backup_type = strdup(backup_type); props->backup_timestamp = strdup(timestamp); } } SQLFreeHandle(SQL_HANDLE_STMT, stmt); SQLDisconnect(conn); SQLFreeHandle(SQL_HANDLE_DBC, conn); } } void write_properties(const char* file_path, BakProperties* props) { SQLHDBC conn = connect_to_sql_server("localhost", "master"); if (conn) { SQLHSTMT stmt; SQLAllocHandle(SQL_HANDLE_STMT, conn, &stmt); char backup_file[512]; snprintf(backup_file, sizeof(backup_file), "%s_new.bak", file_path); char query[512]; snprintf(query, sizeof(query), "BACKUP DATABASE %s TO DISK = '%s'", props->database_name ? props->database_name : "master", backup_file); if (SQLExecDirect(stmt, (SQLCHAR*)query, SQL_NTS) == SQL_SUCCESS) { printf("New backup created at: %s\n", backup_file); } else { printf("Error creating backup\n"); } SQLFreeHandle(SQL_HANDLE_STMT, stmt); SQLDisconnect(conn); SQLFreeHandle(SQL_HANDLE_DBC, conn); } } void print_properties(BakProperties* props) { printf("file_extension: %s\n", props->file_extension ? props->file_extension : "N/A"); printf("file_format: %s\n", props->file_format); printf("file_size: %lld\n", props->file_size); printf("database_name: %s\n", props->database_name ? props->database_name : "N/A"); printf("backup_timestamp: %s\n", props->backup_timestamp ? props->backup_timestamp : "N/A"); printf("sql_server_version: %d\n", props->sql_server_version); printf("backup_type: %s\n", props->backup_type ? props->backup_type : "N/A"); printf("media_family_count: %d\n", props->media_family_count); printf("compression_status: %d\n", props->compression_status); printf("encryption_status: %d\n", props->encryption_status); printf("checksum: %d\n", props->checksum); } int main() { BakProperties props; init_properties(&props); read_properties("C:\\Path\\To\\Your\\BackupFile.bak", &props); print_properties(&props); write_properties("C:\\Path\\To\\Your\\BackupFile.bak", &props); free_properties(&props); return 0; } // ===== end task-055 .BAK ===== // ===== task-056 .BAS [C] ===== #include #include #include typedef struct { char* filepath; char* content_type; char* encoding; // Properties as key-value, but for simplicity, print directly } BASHandler; BASHandler* bas_handler_create(const char* filepath) { BASHandler* h = malloc(sizeof(BASHandler)); h->filepath = strdup(filepath); h->content_type = NULL; h->encoding = NULL; return h; } void bas_handler_destroy(BASHandler* h) { free(h->filepath); free(h->content_type); free(h->encoding); free(h); } char* bytes_to_hex(const unsigned char* bytes, int len) { char* hex = malloc(2 * len + 1); for (int i = 0; i < len; i++) { sprintf(hex + 2*i, "%02x", bytes[i]); } hex[2*len] = '\0'; return hex; } unsigned char* bas_open_and_decode(BASHandler* h) { FILE* f = fopen(h->filepath, "rb"); if (!f) { perror("File not found"); return NULL; } fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); unsigned char* raw_data = malloc(size); fread(raw_data, 1, size, f); fclose(f); // Heuristic for text int is_text = 1; for (int i = 0; i < (size < 100 ? size : 100); i++) { unsigned char b = raw_data[i]; if (!((b >= 32 && b <= 126) || b == 10 || b == 13)) { is_text = 0; break; } } if (is_text) { h->content_type = strdup("text"); h->encoding = strdup("UTF-8"); // Assume; check could be added char header[51]; strncpy(header, (char*)raw_data, 50); header[50] = '\0'; // Simplified; assume ASCII for print printf("File Extension: .bas\n"); printf("Content Type: %s\n", h->content_type); printf("MIME Type: text/plain\n"); printf("Character Encoding: %s\n", h->encoding); printf("File Structure: Line-oriented text with optional line numbers\n"); printf("Header/Signature: %s...\n", header); // Line delim: simplified printf("Line Delimitation: LF\n"); printf("Data Elements: BASIC code lines\n"); printf("Keyword Handling: Plain text keywords\n"); printf("Size: %ld bytes\n", size); return raw_data; // As text bytes } else { h->content_type = strdup("binary"); h->encoding = strdup("N/A (tokenized)"); char* hex_header = bytes_to_hex(raw_data, 4); int first_line = (raw_data[3] << 8) | raw_data[2]; // Little-endian int line_count = 0; for (int i = 0; i < size - 1; i += 2) { if (raw_data[i] == 0 && raw_data[i+1] == 0) line_count++; } printf("File Extension: .bas\n"); printf("Content Type: %s\n", h->content_type); printf("MIME Type: application/octet-stream\n"); printf("Character Encoding: %s\n", h->encoding); printf("File Structure: Tokenized binary with %d lines\n", line_count); printf("Header/Signature: Binary: %s\n", hex_header); printf("Line Delimitation: N/A\n"); printf("Data Elements: First line number: %d\n", first_line); printf("Keyword Handling: Single-byte tokens\n"); printf("Size: %ld bytes\n", size); free(hex_header); return raw_data; } } void bas_write(BASHandler* h, const char* output_path, unsigned char* data, long size) { FILE* f = fopen(output_path, "wb"); if (f) { fwrite(data, 1, size, f); fclose(f); printf("Written to %s\n", output_path); } else { perror("Write failed"); } } int main(int argc, char* argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } BASHandler* h = bas_handler_create(argv[1]); unsigned char* data = bas_open_and_decode(h); if (data) { // bas_write(h, "output.bas", data, /*size*/ 0); // Uncomment with size free(data); } bas_handler_destroy(h); return 0; } // ===== end task-056 .BAS ===== // ===== task-057 .BAT [C] ===== #include #include #include #include #define MAX_CONTENT_SIZE 1024 * 1024 // 1MB max content size typedef struct { char* fileExtension; char* fileType; char* mimeType; char* encoding; char* lineEndings; char* executionEnvironment; char* fileContent; char** specialVariables; int varCount; } BatFileProperties; typedef struct { char* filepath; BatFileProperties properties; } BatFileHandler; void initBatFileHandler(BatFileHandler* handler, const char* filepath) { handler->filepath = strdup(filepath); handler->properties.fileType = "Plain text (Batch Script)"; handler->properties.encoding = "ANSI"; // Simplified assumption handler->properties.fileContent = NULL; handler->properties.specialVariables = NULL; handler->properties.varCount = 0; } void detectLineEndings(BatFileHandler* handler) { if (strstr(handler->properties.fileContent, "\r\n")) { handler->properties.lineEndings = "CRLF (Windows)"; } else if (strstr(handler->properties.fileContent, "\n")) { handler->properties.lineEndings = "LF (Unix)"; } else { handler->properties.lineEndings = "Unknown"; } } void detectSpecialVariables(BatFileHandler* handler) { char* content = handler->properties.fileContent; handler->properties.specialVariables = (char**)malloc(10 * sizeof(char*)); handler->properties.varCount = 0; char* line = strtok(content, "\n"); while (line) { if (strstr(line, "%0")) { handler->properties.specialVariables[handler->properties.varCount++] = "%0 (batch file name)"; } for (int i = 1; i <= 9; i++) { char var[4]; snprintf(var, sizeof(var), "%%%d", i); if (strstr(line, var)) { char* varDesc = (char*)malloc(50); snprintf(varDesc, 50, "%%%d (command-line argument)", i); handler->properties.specialVariables[handler->properties.varCount++] = varDesc; } } line = strtok(NULL, "\n"); } if (handler->properties.varCount == 0) { handler->properties.specialVariables[handler->properties.varCount++] = "None detected"; } } void readFile(BatFileHandler* handler) { FILE* file = fopen(handler->filepath, "r"); if (!file) { printf("Error reading file\n"); return; } handler->properties.fileContent = (char*)malloc(MAX_CONTENT_SIZE); size_t len = fread(handler->properties.fileContent, 1, MAX_CONTENT_SIZE - 1, file); handler->properties.fileContent[len] = '\0'; fclose(file); char* ext = strrchr(handler->filepath, '.'); handler->properties.fileExtension = ext ? strdup(ext) : ".bat"; handler->properties.mimeType = (strcmp(handler->properties.fileExtension, ".bat") == 0 || strcmp(handler->properties.fileExtension, ".cmd") == 0) ? "application/bat" : "text/plain"; handler->properties.executionEnvironment = (strcmp(handler->properties.fileExtension, ".bat") == 0 || strcmp(handler->properties.fileExtension, ".cmd") == 0) ? "cmd.exe" : "Unknown"; detectLineEndings(handler); detectSpecialVariables(handler); } void writeFile(BatFileHandler* handler, const char* content) { FILE* file = fopen(handler->filepath, "w"); if (!file) { printf("Error writing file\n"); return; } fprintf(file, "%s", content); fclose(file); free(handler->properties.fileContent); handler->properties.fileContent = strdup(content); printf("File written successfully.\n"); } void printProperties(BatFileHandler* handler) { printf("BAT File Properties:\n"); printf("File Extension: %s\n", handler->properties.fileExtension); printf("File Type: %s\n", handler->properties.fileType); printf("MIME Type: %s\n", handler->properties.mimeType); printf("Encoding: %s\n", handler->properties.encoding); printf("Line Endings: %s\n", handler->properties.lineEndings); printf("Execution Environment: %s\n", handler->properties.executionEnvironment); printf("File Content: %s\n", handler->properties.fileContent); printf("Special Variables: "); for (int i = 0; i < handler->properties.varCount; i++) { printf("%s%s", handler->properties.specialVariables[i], i < handler->properties.varCount - 1 ? ", " : "\n"); } } void freeBatFileHandler(BatFileHandler* handler) { free(handler->filepath); free(handler->properties.fileExtension); free(handler->properties.fileContent); for (int i = 0; i < handler->properties.varCount; i++) { if (strcmp(handler->properties.specialVariables[i], "None detected") != 0) { free(handler->properties.specialVariables[i]); } } free(handler->properties.specialVariables); } int main() { BatFileHandler handler; initBatFileHandler(&handler, "example.bat"); readFile(&handler); printProperties(&handler); const char* sampleContent = "@ECHO OFF\nECHO Hello, World!\nPAUSE"; writeFile(&handler, sampleContent); freeBatFileHandler(&handler); return 0; } // ===== end task-057 .BAT ===== // ===== task-058 .BDF [C] ===== #include #include #include #define MAX_LINE 256 #define MAX_GLYPHS 1000 #define MAX_BITMAP_ROWS 100 #define MAX_PROPERTIES 50 typedef struct { int x, y; } Point; typedef struct { int width, height, x_offset, y_offset; } BoundingBox; typedef struct { char* name; int encoding; Point swidth; Point dwidth; BoundingBox bbx; char** bitmap; int bitmap_rows; } Glyph; typedef struct { char* filename; char* version; char* font_name; struct { int point_size, x_resolution, y_resolution; } size; BoundingBox font_bounding_box; struct { char* key; char* value; } font_properties[MAX_PROPERTIES]; int num_font_properties; int num_glyphs; Glyph glyphs[MAX_GLYPHS]; int glyph_count; } BDFHandler; BDFHandler* create_bdf_handler(const char* filename) { BDFHandler* handler = (BDFHandler*)malloc(sizeof(BDFHandler)); handler->filename = strdup(filename); handler->version = NULL; handler->font_name = NULL; handler->size.point_size = 0; handler->size.x_resolution = 0; handler->size.y_resolution = 0; handler->font_bounding_box.width = 0; handler->font_bounding_box.height = 0; handler->font_bounding_box.x_offset = 0; handler->font_bounding_box.y_offset = 0; handler->num_font_properties = 0; handler->num_glyphs = 0; handler->glyph_count = 0; return handler; } void free_bdf_handler(BDFHandler* handler) { if (handler->version) free(handler->version); if (handler->font_name) free(handler->font_name); for (int i = 0; i < handler->num_font_properties; i++) { free(handler->font_properties[i].key); free(handler->font_properties[i].value); } for (int i = 0; i < handler->glyph_count; i++) { free(handler->glyphs[i].name); for (int j = 0; j < handler->glyphs[i].bitmap_rows; j++) { free(handler->glyphs[i].bitmap[j]); } free(handler->glyphs[i].bitmap); } free(handler->filename); free(handler); } void read_bdf(BDFHandler* handler) { FILE* file = fopen(handler->filename, "r"); if (!file) { printf("Error opening file %s\n", handler->filename); return; } char line[MAX_LINE]; Glyph* current_glyph = NULL; char** bitmap_data = NULL; int bitmap_rows = 0; int in_bitmap = 0; int in_properties = 0; while (fgets(line, MAX_LINE, file)) { line[strcspn(line, "\n")] = 0; if (!line[0]) continue; char* keyword = strtok(line, " "); char* rest = strtok(NULL, ""); if (strcmp(keyword, "STARTFONT") == 0) { handler->version = strdup(rest); } else if (strcmp(keyword, "FONT") == 0) { handler->font_name = strdup(rest); } else if (strcmp(keyword, "SIZE") == 0) { sscanf(rest, "%d %d %d", &handler->size.point_size, &handler->size.x_resolution, &handler->size.y_resolution); } else if (strcmp(keyword, "FONTBOUNDINGBOX") == 0) { sscanf(rest, "%d %d %d %d", &handler->font_bounding_box.width, &handler->font_bounding_box.height, &handler->font_bounding_box.x_offset, &handler->font_bounding_box.y_offset); } else if (strcmp(keyword, "STARTPROPERTIES") == 0) { in_properties = 1; } else if (strcmp(keyword, "ENDPROPERTIES") == 0) { in_properties = 0; } else if (in_properties) { char* key = strtok(line, " "); char* value = strtok(NULL, ""); handler->font_properties[handler->num_font_properties].key = strdup(key); handler->font_properties[handler->num_font_properties].value = strdup(value ? value : ""); handler->num_font_properties++; } else if (strcmp(keyword, "CHARS") == 0) { sscanf(rest, "%d", &handler->num_glyphs); } else if (strcmp(keyword, "STARTCHAR") == 0) { current_glyph = &handler->glyphs[handler->glyph_count]; current_glyph->name = strdup(rest); current_glyph->bitmap_rows = 0; current_glyph->bitmap = NULL; } else if (strcmp(keyword, "ENCODING") == 0) { sscanf(rest, "%d", ¤t_glyph->encoding); } else if (strcmp(keyword, "SWIDTH") == 0) { sscanf(rest, "%d %d", ¤t_glyph->swidth.x, ¤t_glyph->swidth.y); } else if (strcmp(keyword, "DWIDTH") == 0) { sscanf(rest, "%d %d", ¤t_glyph->dwidth.x, ¤t_glyph->dwidth.y); } else if (strcmp(keyword, "BBX") == 0) { sscanf(rest, "%d %d %d %d", ¤t_glyph->bbx.width, ¤t_glyph->bbx.height, ¤t_glyph->bbx.x_offset, ¤t_glyph->bbx.y_offset); } else if (strcmp(keyword, "BITMAP") == 0) { in_bitmap = 1; bitmap_rows = 0; bitmap_data = (char**)malloc(MAX_BITMAP_ROWS * sizeof(char*)); } else if (strcmp(keyword, "ENDCHAR") == 0) { current_glyph->bitmap = bitmap_data; current_glyph->bitmap_rows = bitmap_rows; handler->glyph_count++; bitmap_data = NULL; in_bitmap = 0; } else if (in_bitmap) { bitmap_data[bitmap_rows] = strdup(keyword); bitmap_rows++; } else if (strcmp(keyword, "ENDFONT") == 0) { break; } } fclose(file); } void print_properties(BDFHandler* handler) { printf("BDF File Properties:\n"); printf(" Version: %s\n", handler->version ? handler->version : "N/A"); printf(" Font Name: %s\n", handler->font_name ? handler->font_name : "N/A"); printf(" Size: { point_size: %d, x_resolution: %d, y_resolution: %d }\n", handler->size.point_size, handler->size.x_resolution, handler->size.y_resolution); printf(" Font Bounding Box: { width: %d, height: %d, x_offset: %d, y_offset: %d }\n", handler->font_bounding_box.width, handler->font_bounding_box.height, handler->font_bounding_box.x_offset, handler->font_bounding_box.y_offset); printf(" Font Properties:\n"); for (int i = 0; i < handler->num_font_properties; i++) { printf(" %s: %s\n", handler->font_properties[i].key, handler->font_properties[i].value); } printf(" Number of Glyphs: %d\n", handler->num_glyphs); printf("\nGlyphs:\n"); for (int i = 0; i < handler->glyph_count; i++) { Glyph* glyph = &handler->glyphs[i]; printf(" Glyph Name: %s\n", glyph->name ? glyph->name : "N/A"); printf(" Encoding: %d\n", glyph->encoding); printf(" SWIDTH: { x: %d, y: %d }\n", glyph->swidth.x, glyph->swidth.y); printf(" DWIDTH: { x: %d, y: %d }\n", glyph->dwidth.x, glyph->dwidth.y); printf(" BBX: { width: %d, height: %d, x_offset: %d, y_offset: %d }\n", glyph->bbx.width, glyph->bbx.height, glyph->bbx.x_offset, glyph->bbx.y_offset); printf(" Bitmap:\n"); for (int j = 0; j < glyph->bitmap_rows; j++) { printf(" %s\n", glyph->bitmap[j]); } } } void write_bdf(BDFHandler* handler, const char* output_filename) { FILE* file = fopen(output_filename, "w"); if (!file) { printf("Error opening file %s\n", output_filename); return; } fprintf(file, "STARTFONT %s\n", handler->version ? handler->version : "2.1"); fprintf(file, "FONT %s\n", handler->font_name ? handler->font_name : "Unknown"); fprintf(file, "SIZE %d %d %d\n", handler->size.point_size ? handler->size.point_size : 16, handler->size.x_resolution ? handler->size.x_resolution : 75, handler->size.y_resolution ? handler->size.y_resolution : 75); fprintf(file, "FONTBOUNDINGBOX %d %d %d %d\n", handler->font_bounding_box.width ? handler->font_bounding_box.width : 16, handler->font_bounding_box.height ? handler->font_bounding_box.height : 16, handler->font_bounding_box.x_offset, handler->font_bounding_box.y_offset ? handler->font_bounding_box.y_offset : -2); fprintf(file, "STARTPROPERTIES %d\n", handler->num_font_properties); for (int i = 0; i < handler->num_font_properties; i++) { fprintf(file, "%s %s\n", handler->font_properties[i].key, handler->font_properties[i].value); } fprintf(file, "ENDPROPERTIES\n"); fprintf(file, "CHARS %d\n", handler->num_glyphs ? handler->num_glyphs : handler->glyph_count); for (int i = 0; i < handler->glyph_count; i++) { Glyph* glyph = &handler->glyphs[i]; fprintf(file, "STARTCHAR %s\n", glyph->name ? glyph->name : "Unknown"); fprintf(file, "ENCODING %d\n", glyph->encoding); fprintf(file, "SWIDTH %d %d\n", glyph->swidth.x, glyph->swidth.y); fprintf(file, "DWIDTH %d %d\n", glyph->dwidth.x, glyph->dwidth.y); fprintf(file, "BBX %d %d %d %d\n", glyph->bbx.width, glyph->bbx.height, glyph->bbx.x_offset, glyph->bbx.y_offset); fprintf(file, "BITMAP\n"); for (int j = 0; j < glyph->bitmap_rows; j++) { fprintf(file, "%s\n", glyph->bitmap[j]); } fprintf(file, "ENDCHAR\n"); } fprintf(file, "ENDFONT\n"); fclose(file); } int main() { BDFHandler* bdf = create_bdf_handler("input.bdf"); read_bdf(bdf); print_properties(bdf); write_bdf(bdf, "output.bdf"); free_bdf_handler(bdf); return 0; } // ===== end task-058 .BDF ===== // ===== task-059 .BDT [C] ===== #include #include #include #include typedef struct { int64_t hash; int32_t padded_size; int32_t size; int64_t offset; } FileEntry; typedef struct { int32_t file_count; int32_t file_header_offset; FileEntry* files; } Bucket; typedef struct { char magic[5]; uint8_t unk04; uint8_t unk05; uint8_t unk06; uint8_t unk07; int32_t unk08; int32_t bucket_count; int32_t bucket_offset; Bucket* buckets; } Properties; Properties* decode(const char* bhd_path) { FILE* f = fopen(bhd_path, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); Properties* props = malloc(sizeof(Properties)); memcpy(props->magic, data, 4); props->magic[4] = '\0'; int offset = 4; props->unk04 = data[offset++]; props->unk05 = data[offset++]; props->unk06 = data[offset++]; props->unk07 = data[offset++]; memcpy(&props->unk08, data + offset, 4); offset += 4; memcpy(&props->bucket_count, data + offset, 4); offset += 4; memcpy(&props->bucket_offset, data + offset, 4); offset += 4; props->buckets = malloc(props->bucket_count * sizeof(Bucket)); offset = props->bucket_offset; for (int i = 0; i < props->bucket_count; i++) { memcpy(&props->buckets[i].file_count, data + offset, 4); offset += 4; memcpy(&props->buckets[i].file_header_offset, data + offset, 4); offset += 4; } for (int i = 0; i < props->bucket_count; i++) { offset = props->buckets[i].file_header_offset; props->buckets[i].files = malloc(props->buckets[i].file_count * sizeof(FileEntry)); for (int j = 0; j < props->buckets[i].file_count; j++) { memcpy(&props->buckets[i].files[j].hash, data + offset, 8); offset += 8; memcpy(&props->buckets[i].files[j].padded_size, data + offset, 4); offset += 4; memcpy(&props->buckets[i].files[j].size, data + offset, 4); offset += 4; memcpy(&props->buckets[i].files[j].offset, data + offset, 8); offset += 8; } } free(data); return props; } void print_properties(Properties* p) { printf("Magic: %s\n", p->magic); printf("Unknown 04: %u\n", p->unk04); printf("Unknown 05: %u\n", p->unk05); printf("Unknown 06: %u\n", p->unk06); printf("Unknown 07: %u\n", p->unk07); printf("Unknown 08: %d\n", p->unk08); printf("Bucket Count: %d\n", p->bucket_count); printf("Bucket Offset: %d\n", p->bucket_offset); for (int i = 0; i < p->bucket_count; i++) { printf("Bucket %d: File Count = %d, Header Offset = %d\n", i, p->buckets[i].file_count, p->buckets[i].file_header_offset); for (int j = 0; j < p->buckets[i].file_count; j++) { printf(" File %d: Hash = %ld, Padded Size = %d, Size = %d, Offset = %ld\n", j, p->buckets[i].files[j].hash, p->buckets[i].files[j].padded_size, p->buckets[i].files[j].size, p->buckets[i].files[j].offset); } } } uint8_t* read_file_data(const char* bdt_path, Properties* p, int bucket_index, int file_index, int* out_size) { FileEntry file = p->buckets[bucket_index].files[file_index]; *out_size = file.size; uint8_t* buffer = malloc(file.size); FILE* f = fopen(bdt_path, "rb"); fseek(f, file.offset, SEEK_SET); fread(buffer, 1, file.size, f); fclose(f); return buffer; } void write(Properties* p, const char* output_bdt_path, const char* output_bhd_path, const char* original_bdt_path) { FILE* f = fopen(output_bhd_path, "wb"); fwrite(p->magic, 1, 4, f); fwrite(&p->unk04, 1, 1, f); fwrite(&p->unk05, 1, 1, f); fwrite(&p->unk06, 1, 1, f); fwrite(&p->unk07, 1, 1, f); fwrite(&p->unk08, 4, 1, f); fwrite(&p->bucket_count, 4, 1, f); fwrite(&p->bucket_offset, 4, 1, f); for (int i = 0; i < p->bucket_count; i++) { fwrite(&p->buckets[i].file_count, 4, 1, f); fwrite(&p->buckets[i].file_header_offset, 4, 1, f); } for (int i = 0; i < p->bucket_count; i++) { for (int j = 0; j < p->buckets[i].file_count; j++) { fwrite(&p->buckets[i].files[j].hash, 8, 1, f); fwrite(&p->buckets[i].files[j].padded_size, 4, 1, f); fwrite(&p->buckets[i].files[j].size, 4, 1, f); fwrite(&p->buckets[i].files[j].offset, 8, 1, f); } } fclose(f); // Copy original BDT FILE* src = fopen(original_bdt_path, "rb"); FILE* dst = fopen(output_bdt_path, "wb"); uint8_t buf[4096]; size_t n; while ((n = fread(buf, 1, sizeof(buf), src)) > 0) { fwrite(buf, 1, n, dst); } fclose(src); fclose(dst); } // Example usage: // Properties* props = decode("example.bhd"); // print_properties(props); // int size; // uint8_t* data = read_file_data("example.bdt", props, 0, 0, &size); // write(props, "output.bdt", "output.bhd", "example.bdt"); // ===== end task-059 .BDT ===== // ===== task-060 .BEAM [C] ===== #include #include #include #include #include typedef struct { char id[5]; unsigned char* data; size_t size; void* decoded; } Chunk; typedef struct { char magic[5]; uint32_t size; char beam_id[5]; Chunk* chunks; size_t num_chunks; } BeamFile; void free_beam(BeamFile* beam) { for (size_t i = 0; i < beam->num_chunks; i++) { free(beam->chunks[i].data); // Free decoded if needed } free(beam->chunks); } int read_beam(BeamFile* beam, const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) return 1; fseek(f, 0, SEEK_END); size_t file_size = ftell(f); fseek(f, 0, SEEK_SET); unsigned char* data = malloc(file_size); fread(data, 1, file_size, f); fclose(f); size_t pos = 0; memcpy(beam->magic, data + pos, 4); beam->magic[4] = '\0'; pos += 4; beam->size = be32toh(*(uint32_t*)(data + pos)); pos += 4; memcpy(beam->beam_id, data + pos, 4); beam->beam_id[4] = '\0'; pos += 4; if (strcmp(beam->magic, "FOR1") != 0 || strcmp(beam->beam_id, "BEAM") != 0) { free(data); return 1; } beam->chunks = NULL; beam->num_chunks = 0; while (pos < file_size) { beam->chunks = realloc(beam->chunks, (beam->num_chunks + 1) * sizeof(Chunk)); Chunk* chunk = &beam->chunks[beam->num_chunks]; memcpy(chunk->id, data + pos, 4); chunk->id[4] = '\0'; pos += 4; uint32_t chunk_size = be32toh(*(uint32_t*)(data + pos)); pos += 4; chunk->data = malloc(chunk_size); memcpy(chunk->data, data + pos, chunk_size); chunk->size = chunk_size; pos += chunk_size; uint32_t pad = (4 - (chunk_size % 4)) % 4; pos += pad; chunk->decoded = NULL; // Decode here if needed // Add decoding similar to above, but omit for brevity; use printf in print beam->num_chunks++; } free(data); return 0; } void print_beam(const BeamFile* beam) { printf("Header: %s, Size: %u, %s\n", beam->magic, beam->size, beam->beam_id); for (size_t i = 0; i < beam->num_chunks; i++) { const Chunk* chunk = &beam->chunks[i]; printf("Chunk ID: %s\n", chunk->id); // Add decoding print, similar to above classes printf("Data (hex): "); for (size_t j = 0; j < chunk->size; j++) { printf("%02x ", chunk->data[j]); } printf("\n\n"); } } int write_beam(const BeamFile* beam, const char* filename) { FILE* f = fopen(filename, "wb"); if (!f) return 1; fwrite("FOR1", 1, 4, f); uint32_t temp_size = 0; fwrite(&temp_size, sizeof(uint32_t), 1, f); fwrite("BEAM", 1, 4, f); size_t body_start = ftell(f); for (size_t i = 0; i < beam->num_chunks; i++) { const Chunk* chunk = &beam->chunks[i]; fwrite(chunk->id, 1, 4, f); uint32_t size_be = htobe32((uint32_t)chunk->size); fwrite(&size_be, sizeof(uint32_t), 1, f); fwrite(chunk->data, 1, chunk->size, f); uint32_t pad = (4 - (chunk->size % 4)) % 4; for (uint32_t p = 0; p < pad; p++) fputc(0, f); } size_t end = ftell(f); uint32_t body_size = (end - body_start) + 4; // 'BEAM' uint32_t size_be = htobe32(body_size); fseek(f, 4, SEEK_SET); fwrite(&size_be, sizeof(uint32_t), 1, f); fclose(f); return 0; } // Example usage: // int main() { // BeamFile beam = {0}; // if (read_beam(&beam, "example.beam") != 0) return 1; // print_beam(&beam); // write_beam(&beam, "output.beam"); // free_beam(&beam); // return 0; // } // ===== end task-060 .BEAM ===== // ===== task-061 .BIB [C++] ===== #include #include #include #include #include #include class BibHandler { private: struct Entry { std::string entry_type; std::string citekey; std::map fields; }; std::vector entries; public: void read(const std::string& filepath) { std::ifstream file(filepath); if (!file) { std::cerr << "Error opening file: " << filepath << std::endl; return; } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); parse(content); } void parse(const std::string& content) { entries.clear(); std::regex entry_regex(R"(@(\w+)\s*\{\s*([^,]+)\s*,([^@]*)\})", std::regex::icase | std::regex::ECMAScript); auto entries_begin = std::sregex_iterator(content.begin(), content.end(), entry_regex); auto entries_end = std::sregex_iterator(); for (std::sregex_iterator i = entries_begin; i != entries_end; ++i) { std::smatch match = *i; std::string entry_type = match[1].str(); std::transform(entry_type.begin(), entry_type.end(), entry_type.begin(), ::tolower); std::string citekey = match[2].str(); citekey.erase(std::remove_if(citekey.begin(), citekey.end(), ::isspace), citekey.end()); std::string fields_str = match[3].str(); Entry entry; entry.entry_type = entry_type; entry.citekey = citekey; std::regex field_regex(R"((\w+)\s*=\s*(?:"([^"]*)"|\{([^}]*)\}))", std::regex::icase | std::regex::ECMAScript); auto fields_begin = std::sregex_iterator(fields_str.begin(), fields_str.end(), field_regex); auto fields_end = std::sregex_iterator(); for (std::sregex_iterator f = fields_begin; f != fields_end; ++f) { std::smatch fmatch = *f; std::string key = fmatch[1].str(); std::transform(key.begin(), key.end(), key.begin(), ::tolower); std::string value = fmatch[2].matched ? fmatch[2].str() : fmatch[3].str(); value.erase(std::remove_if(value.begin(), value.end(), ::isspace), value.end()); entry.fields[key] = value; } entries.push_back(entry); } } void print_properties() { std::vector props = {"address", "annote", "author", "booktitle", "chapter", "edition", "editor", "howpublished", "institution", "journal", "month", "note", "number", "organization", "pages", "publisher", "school", "series", "title", "type", "volume", "year"}; for (const auto& entry : entries) { std::cout << "Entry: @" << entry.entry_type << "{" << entry.citekey << "}" << std::endl; for (const auto& prop : props) { auto it = entry.fields.find(prop); if (it != entry.fields.end()) { std::cout << " " << prop << ": " << it->second << std::endl; } } std::cout << std::endl; } } void write(const std::string& filepath) { std::ofstream file(filepath); if (!file) { std::cerr << "Error writing file: " << filepath << std::endl; return; } for (const auto& entry : entries) { file << "@" << entry.entry_type << "{" << entry.citekey << ",\n"; for (const auto& field : entry.fields) { file << " " << field.first << " = {" << field.second << "},\n"; } file << "}\n\n"; } } }; // Example usage: // int main() { // BibHandler handler; // handler.read("sample.bib"); // handler.print_properties(); // handler.write("output.bib"); // return 0; // } // ===== end task-061 .BIB ===== // ===== task-062 .BIN [C++] ===== #include #include #include #include #include #include #include class BinFileHandler { private: std::string filename; std::vector> records; // Use double for simplicity, cast as needed public: BinFileHandler(const std::string& fn) : filename(fn) {} void read() { std::ifstream file(filename, std::ios::binary); if (!file) return; while (file) { // BinObjectHeader (little-endian, 24 bytes) uint16_t mask; uint32_t reserved; double timestamp; double latency; uint32_t dataSize; file.read(reinterpret_cast(&mask), sizeof(mask)); file.read(reinterpret_cast(&reserved), sizeof(reserved)); file.read(reinterpret_cast(×tamp), sizeof(timestamp)); file.read(reinterpret_cast(&latency), sizeof(latency)); file.read(reinterpret_cast(&dataSize), sizeof(dataSize)); if (file.gcount() < sizeof(dataSize)) break; // WaterColumnHeader (big-endian, 58 bytes) char headerStr[9] = {0}; file.read(headerStr, 8); uint32_t pingNumber = 0; file.read(reinterpret_cast(&pingNumber), 4); std::reverse(reinterpret_cast(&pingNumber), reinterpret_cast(&pingNumber) + 4); uint16_t reserved1 = 0; file.read(reinterpret_cast(&reserved1), 2); std::reverse(reinterpret_cast(&reserved1), reinterpret_cast(&reserved1) + 2); uint32_t reserved2 = 0; file.read(reinterpret_cast(&reserved2), 4); std::reverse(reinterpret_cast(&reserved2), reinterpret_cast(&reserved2) + 4); uint32_t depth = 0; file.read(reinterpret_cast(&depth), 4); std::reverse(reinterpret_cast(&depth), reinterpret_cast(&depth) + 4); uint16_t draft = 0; file.read(reinterpret_cast(&draft), 2); std::reverse(reinterpret_cast(&draft), reinterpret_cast(&draft) + 2); uint16_t indexOffset = 0; file.read(reinterpret_cast(&indexOffset), 2); std::reverse(reinterpret_cast(&indexOffset), reinterpret_cast(&indexOffset) + 2); uint32_t gateHi = 0; file.read(reinterpret_cast(&gateHi), 4); std::reverse(reinterpret_cast(&gateHi), reinterpret_cast(&gateHi) + 4); uint32_t gateLo = 0; file.read(reinterpret_cast(&gateLo), 4); std::reverse(reinterpret_cast(&gateLo), reinterpret_cast(&gateLo) + 4); uint16_t scaleWidth = 0; file.read(reinterpret_cast(&scaleWidth), 2); std::reverse(reinterpret_cast(&scaleWidth), reinterpret_cast(&scaleWidth) + 2); uint16_t endOfScale = 0; file.read(reinterpret_cast(&endOfScale), 2); std::reverse(reinterpret_cast(&endOfScale), reinterpret_cast(&endOfScale) + 2); int16_t motionStatus = 0; file.read(reinterpret_cast(&motionStatus), 2); std::reverse(reinterpret_cast(&motionStatus), reinterpret_cast(&motionStatus) + 2); int16_t motionHeave = 0; file.read(reinterpret_cast(&motionHeave), 2); std::reverse(reinterpret_cast(&motionHeave), reinterpret_cast(&motionHeave) + 2); int16_t motionRoll = 0; file.read(reinterpret_cast(&motionRoll), 2); std::reverse(reinterpret_cast(&motionRoll), reinterpret_cast(&motionRoll) + 2); int16_t motionPitch = 0; file.read(reinterpret_cast(&motionPitch), 2); std::reverse(reinterpret_cast(&motionPitch), reinterpret_cast(&motionPitch) + 2); uint32_t tideCorrection = 0; file.read(reinterpret_cast(&tideCorrection), 4); std::reverse(reinterpret_cast(&tideCorrection), reinterpret_cast(&tideCorrection) + 4); uint16_t sampleCount = 0; file.read(reinterpret_cast(&sampleCount), 2); std::reverse(reinterpret_cast(&sampleCount), reinterpret_cast(&sampleCount) + 2); uint16_t sampleResolution = 0; file.read(reinterpret_cast(&sampleResolution), 2); std::reverse(reinterpret_cast(&sampleResolution), reinterpret_cast(&sampleResolution) + 2); uint32_t sampleFrequency = 0; file.read(reinterpret_cast(&sampleFrequency), 4); std::reverse(reinterpret_cast(&sampleFrequency), reinterpret_cast(&sampleFrequency) + 4); if (file.gcount() < 4) break; std::map record; record["Mask"] = mask; record["Reserved (BinObject)"] = reserved; record["Timestamp"] = timestamp; record["Latency"] = latency; record["DataSize"] = dataSize; record["Header (WaterColumn)"] = 0; // String not stored as double; handle separately if needed record["PingNumber"] = pingNumber; record["Reserved1"] = reserved1; record["Reserved2"] = reserved2; record["Depth"] = depth; record["Draft"] = draft; record["IndexOffset"] = indexOffset; record["GateHi"] = gateHi; record["GateLo"] = gateLo; record["ScaleWidth"] = scaleWidth; record["EndOfScale"] = endOfScale; record["MotionStatus"] = motionStatus; record["MotionHeave"] = motionHeave; record["MotionRoll"] = motionRoll; record["MotionPitch"] = motionPitch; record["TideCorrection"] = tideCorrection; record["SampleCount"] = sampleCount; record["SampleResolution"] = sampleResolution; record["SampleFrequency"] = sampleFrequency; records.push_back(record); // Skip sample data uint32_t sampleBytes = sampleCount * sampleResolution; file.seekg(sampleBytes, std::ios::cur); } } void printProperties() { for (size_t i = 0; i < records.size(); ++i) { std::cout << "Record " << (i + 1) << ":" << std::endl; for (const auto& entry : records[i]) { std::cout << " " << entry.first << ": " << entry.second << std::endl; } std::cout << std::endl; } } void write(const std::string& outputFilename) { std::ofstream file(outputFilename, std::ios::binary); if (!file) return; for (const auto& record : records) { // Write BinObjectHeader (little-endian) uint16_t mask = static_cast(record.at("Mask")); uint32_t reserved = static_cast(record.at("Reserved (BinObject)")); double timestamp = record.at("Timestamp"); double latency = record.at("Latency"); uint32_t dataSize = static_cast(record.at("DataSize")); file.write(reinterpret_cast(&mask), sizeof(mask)); file.write(reinterpret_cast(&reserved), sizeof(reserved)); file.write(reinterpret_cast(×tamp), sizeof(timestamp)); file.write(reinterpret_cast(&latency), sizeof(latency)); file.write(reinterpret_cast(&dataSize), sizeof(dataSize)); // Write WaterColumnHeader (big-endian) char headerStr[8] = {0}; // Placeholder, extend for string file.write(headerStr, 8); uint32_t pingNumber = static_cast(record.at("PingNumber")); std::reverse(reinterpret_cast(&pingNumber), reinterpret_cast(&pingNumber) + 4); file.write(reinterpret_cast(&pingNumber), 4); uint16_t reserved1 = static_cast(record.at("Reserved1")); std::reverse(reinterpret_cast(&reserved1), reinterpret_cast(&reserved1) + 2); file.write(reinterpret_cast(&reserved1), 2); uint32_t reserved2 = static_cast(record.at("Reserved2")); std::reverse(reinterpret_cast(&reserved2), reinterpret_cast(&reserved2) + 4); file.write(reinterpret_cast(&reserved2), 4); uint32_t depth = static_cast(record.at("Depth")); std::reverse(reinterpret_cast(&depth), reinterpret_cast(&depth) + 4); file.write(reinterpret_cast(&depth), 4); uint16_t draft = static_cast(record.at("Draft")); std::reverse(reinterpret_cast(&draft), reinterpret_cast(&draft) + 2); file.write(reinterpret_cast(&draft), 2); uint16_t indexOffset = static_cast(record.at("IndexOffset")); std::reverse(reinterpret_cast(&indexOffset), reinterpret_cast(&indexOffset) + 2); file.write(reinterpret_cast(&indexOffset), 2); uint32_t gateHi = static_cast(record.at("GateHi")); std::reverse(reinterpret_cast(&gateHi), reinterpret_cast(&gateHi) + 4); file.write(reinterpret_cast(&gateHi), 4); uint32_t gateLo = static_cast(record.at("GateLo")); std::reverse(reinterpret_cast(&gateLo), reinterpret_cast(&gateLo) + 4); file.write(reinterpret_cast(&gateLo), 4); uint16_t scaleWidth = static_cast(record.at("ScaleWidth")); std::reverse(reinterpret_cast(&scaleWidth), reinterpret_cast(&scaleWidth) + 2); file.write(reinterpret_cast(&scaleWidth), 2); uint16_t endOfScale = static_cast(record.at("EndOfScale")); std::reverse(reinterpret_cast(&endOfScale), reinterpret_cast(&endOfScale) + 2); file.write(reinterpret_cast(&endOfScale), 2); int16_t motionStatus = static_cast(record.at("MotionStatus")); std::reverse(reinterpret_cast(&motionStatus), reinterpret_cast(&motionStatus) + 2); file.write(reinterpret_cast(&motionStatus), 2); int16_t motionHeave = static_cast(record.at("MotionHeave")); std::reverse(reinterpret_cast(&motionHeave), reinterpret_cast(&motionHeave) + 2); file.write(reinterpret_cast(&motionHeave), 2); int16_t motionRoll = static_cast(record.at("MotionRoll")); std::reverse(reinterpret_cast(&motionRoll), reinterpret_cast(&motionRoll) + 2); file.write(reinterpret_cast(&motionRoll), 2); int16_t motionPitch = static_cast(record.at("MotionPitch")); std::reverse(reinterpret_cast(&motionPitch), reinterpret_cast(&motionPitch) + 2); file.write(reinterpret_cast(&motionPitch), 2); uint32_t tideCorrection = static_cast(record.at("TideCorrection")); std::reverse(reinterpret_cast(&tideCorrection), reinterpret_cast(&tideCorrection) + 4); file.write(reinterpret_cast(&tideCorrection), 4); uint16_t sampleCount = static_cast(record.at("SampleCount")); std::reverse(reinterpret_cast(&sampleCount), reinterpret_cast(&sampleCount) + 2); file.write(reinterpret_cast(&sampleCount), 2); uint16_t sampleResolution = static_cast(record.at("SampleResolution")); std::reverse(reinterpret_cast(&sampleResolution), reinterpret_cast(&sampleResolution) + 2); file.write(reinterpret_cast(&sampleResolution), 2); uint32_t sampleFrequency = static_cast(record.at("SampleFrequency")); std::reverse(reinterpret_cast(&sampleFrequency), reinterpret_cast(&sampleFrequency) + 4); file.write(reinterpret_cast(&sampleFrequency), 4); // Note: Sample data not written } } }; // Example usage: // int main() { // BinFileHandler handler("input.bin"); // handler.read(); // handler.printProperties(); // handler.write("output.bin"); // return 0; // } // ===== end task-062 .BIN ===== // ===== task-063 .BLEND [C++] ===== #include #include #include #include // For gzip check, but full decompress requires gzopen class BlendFileHandler { private: std::string filepath; std::string magic; char ptr_size_id; int ptr_size; char endian_id; std::string endian; std::string version; bool is_compressed; public: BlendFileHandler(const std::string& fp) : filepath(fp), is_compressed(false) { read_and_decode(); } void read_and_decode() { std::ifstream file(filepath, std::ios::binary); if (!file) return; char header[12]; file.read(header, 12); if (header[0] == 0x1F && static_cast(header[1]) == 0x8B) { is_compressed = true; // For full decompress, use gzFile; assume uncompressed for parsing here. } magic = std::string(header, 7); ptr_size_id = header[7]; ptr_size = (ptr_size_id == '_') ? 4 : 8; endian_id = header[8]; endian = (endian_id == 'v') ? "little-endian" : "big-endian"; version = std::string(header + 9, 3); } void print_properties() { std::cout << "Compression: " << (is_compressed ? "Gzip compressed" : "Uncompressed") << std::endl; std::cout << "Magic String: " << magic << std::endl; std::cout << "Pointer Size Indicator: " << ptr_size_id << " (" << ptr_size << " bytes)" << std::endl; std::cout << "Endianness Indicator: " << endian_id << " (" << endian << ")" << std::endl; std::cout << "Version Number: " << version << std::endl; } void write_new_file(const std::string& new_filepath, const std::string& ver = "300", int ps = 8, const std::string& end = "little", bool comp = false) { char ps_id = (ps == 8) ? '-' : '_'; char end_id = (end == "little") ? 'v' : 'V'; std::string header = "BLENDER"; header += ps_id; header += end_id; header += ver; if (comp) { // Use gzFile for compression; skipped for simplicity. std::ofstream out(new_filepath, std::ios::binary); out.write(header.c_str(), header.size()); } else { std::ofstream out(new_filepath, std::ios::binary); out.write(header.c_str(), header.size()); } } }; // Example usage: // int main() { // BlendFileHandler handler("example.blend"); // handler.print_properties(); // handler.write_new_file("new.blend"); // return 0; // } // ===== end task-063 .BLEND ===== // ===== task-064 .BM3 [C] ===== #include #include #include #include typedef struct { char* filename; char** properties; int prop_count; } BM3Handler; BM3Handler* new_BM3Handler(const char* filename) { BM3Handler* handler = malloc(sizeof(BM3Handler)); handler->filename = strdup(filename); handler->properties = NULL; handler->prop_count = 0; return handler; } void add_property(BM3Handler* handler, const char* prop) { handler->properties = realloc(handler->properties, (handler->prop_count + 1) * sizeof(char*)); handler->properties[handler->prop_count++] = strdup(prop); } void read_BM3(BM3Handler* handler) { // Assume ZIP open with minizip, parse fullbackupdata // For simplicity, placeholder parse add_property(handler, "Contacts"); add_property(handler, "Messages"); print_properties(handler); } void parse_ab(unsigned char* ab_data, size_t size, BM3Handler* handler) { if (strncmp((char*)ab_data, "ANDROID BACKUP", 15) != 0) return; // Skip lines, assume no encryption, decompress if needed // Add properties based on content } void print_properties(BM3Handler* handler) { printf("BM3 Properties:\n"); for (int i = 0; i < handler->prop_count; i++) { printf("%s\n", handler->properties[i]); } } void write_BM3(BM3Handler* handler, const char* output_filename, const char** new_properties, int count) { // Placeholder: create ZIP with dummy AB FILE* fp = fopen(output_filename, "wb"); if (fp) { // Write dummy ZIP content fclose(fp); } printf("Written to %s\n", output_filename); } void free_BM3Handler(BM3Handler* handler) { for (int i = 0; i < handler->prop_count; i++) free(handler->properties[i]); free(handler->properties); free(handler->filename); free(handler); } // Usage int main() { BM3Handler* handler = new_BM3Handler("example.bm3"); read_BM3(handler); const char* new_props[] = {"Contacts", "Messages"}; write_BM3(handler, "new.bm3", new_props, 2); free_BM3Handler(handler); return 0; } // ===== end task-064 .BM3 ===== // ===== task-065 .BMP [C++] ===== #include #include #include #include #include #include class BMPHandler { private: std::vector data; std::map properties; // Using int64_t for generality void decodeProperties() { // Helper to read little-endian values auto readUint16 = [&](size_t offset) { return static_cast(data[offset] | (data[offset + 1] << 8)); }; auto readInt32 = [&](size_t offset) { return static_cast(data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)); }; auto readUint32 = [&](size_t offset) { return static_cast(readInt32(offset)); }; // Bitmap File Header char sig[3] = {static_cast(data[0]), static_cast(data[1]), '\0'}; properties["Signature"] = *reinterpret_cast(sig); // For display, but treat as string later properties["File Size"] = readUint32(2); properties["Reserved 1"] = readUint16(6); properties["Reserved 2"] = readUint16(8); properties["Pixel Array Offset"] = readUint32(10); // DIB Header uint32_t dibSize = readUint32(14); properties["DIB Header Size"] = dibSize; properties["Width"] = readInt32(18); properties["Height"] = readInt32(22); properties["Color Planes"] = readUint16(26); properties["Bits Per Pixel"] = readUint16(28); properties["Compression Method"] = readUint32(30); properties["Raw Image Size"] = readUint32(34); properties["Horizontal Resolution"] = readInt32(38); properties["Vertical Resolution"] = readInt32(42); properties["Palette Colors"] = readUint32(46); properties["Important Colors"] = readUint32(50); if (dibSize >= 108) { // Version 4+ properties["Red Mask"] = readUint32(54); properties["Green Mask"] = readUint32(58); properties["Blue Mask"] = readUint32(62); properties["Alpha Mask"] = readUint32(66); properties["Color Space Type"] = readUint32(70); // Additional fields can be added } if (dibSize >= 124) { // Version 5+ properties["Intent"] = readUint32(122); properties["Profile Data Offset"] = readUint32(126); properties["Profile Size"] = readUint32(130); } } public: BMPHandler(const std::string& filepath) { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { throw std::runtime_error("Failed to open file"); } size_t size = file.tellg(); file.seekg(0); data.resize(size); file.read(reinterpret_cast(data.data()), size); decodeProperties(); } void printProperties() { for (const auto& pair : properties) { if (pair.first == "Signature") { char sig[3]; memcpy(sig, &pair.second, 2); sig[2] = '\0'; std::cout << pair.first << ": " << sig << std::endl; } else { std::cout << pair.first << ": " << pair.second << std::endl; } } } void write(const std::string& outputPath) { std::ofstream file(outputPath, std::ios::binary); if (!file) { throw std::runtime_error("Failed to write file"); } file.write(reinterpret_cast(data.data()), data.size()); } }; // ===== end task-065 .BMP ===== // ===== task-066 .BPS [C++] ===== #include #include #include #include #include #include class BPSFile { private: std::vector data; std::map properties; // Simplified to strings for printing std::vector> actions; std::pair decodeVLI(size_t pos) { long long value = 0; long long shift = 1; while (true) { unsigned char x = data[pos++]; value += (x & 0x7f) * shift; if (x & 0x80) break; shift <<= 7; value += shift; } return {value, pos}; } std::pair decodeSignedVLI(size_t pos) { auto res = decodeVLI(pos); long long value = res.first; int sign = value & 1; value = (value >> 1) * (sign ? -1 : 1); return {value, res.second}; } void readProperties() { size_t pos = 0; // Magic std::string magic(data.begin() + pos, data.begin() + pos + 4); properties["magic"] = magic; pos += 4; if (magic != "BPS1") { throw std::runtime_error("Invalid BPS file"); } // Source size auto res = decodeVLI(pos); properties["source_size"] = std::to_string(res.first); pos = res.second; // Target size res = decodeVLI(pos); properties["target_size"] = std::to_string(res.first); pos = res.second; // Metadata size res = decodeVLI(pos); long long metadataSize = res.first; properties["metadata_size"] = std::to_string(metadataSize); pos = res.second; // Metadata std::string metadata; if (metadataSize > 0) { metadata = std::string(data.begin() + pos, data.begin() + pos + metadataSize); pos += metadataSize; } properties["metadata"] = metadata; // Actions size_t endActions = data.size() - 12; while (pos < endActions) { res = decodeVLI(pos); long long dataVal = res.first; pos = res.second; int command = dataVal & 3; long long length = (dataVal >> 2) + 1; std::map action; action["type"] = std::to_string(command); action["length"] = std::to_string(length); if (command == 1) { // TargetRead std::stringstream ss; for (long long i = 0; i < length; ++i) { ss << std::hex << std::setw(2) << std::setfill('0') << (int)data[pos + i]; } action["data"] = ss.str(); pos += length; } else if (command == 2 || command == 3) { // SourceCopy or TargetCopy res = decodeSignedVLI(pos); action["relative_offset"] = std::to_string(res.first); pos = res.second; } actions.push_back(action); } // Checksums std::stringstream ss; for (int i = 0; i < 4; ++i) ss << std::hex << std::setw(2) << std::setfill('0') << (int)data[pos + i]; properties["source_checksum"] = ss.str(); pos += 4; ss.str(""); for (int i = 0; i < 4; ++i) ss << std::hex << std::setw(2) << std::setfill('0') << (int)data[pos + i]; properties["target_checksum"] = ss.str(); pos += 4; ss.str(""); for (int i = 0; i < 4; ++i) ss << std::hex << std::setw(2) << std::setfill('0') << (int)data[pos + i]; properties["patch_checksum"] = ss.str(); } public: BPSFile(const std::string& filename) { std::ifstream file(filename, std::ios::binary); if (!file) throw std::runtime_error("Cannot open file"); data = std::vector((std::istreambuf_iterator(file)), std::istreambuf_iterator()); readProperties(); } void printProperties() const { std::cout << "Magic: " << properties.at("magic") << std::endl; std::cout << "Source Size: " << properties.at("source_size") << std::endl; std::cout << "Target Size: " << properties.at("target_size") << std::endl; std::cout << "Metadata Size: " << properties.at("metadata_size") << std::endl; std::cout << "Metadata: " << properties.at("metadata") << std::endl; std::cout << "Actions:" << std::endl; const std::string types[] = {"SourceRead", "TargetRead", "SourceCopy", "TargetCopy"}; for (size_t i = 0; i < actions.size(); ++i) { const auto& action = actions[i]; int type = std::stoi(action.at("type")); std::cout << " Action " << (i + 1) << ":" << std::endl; std::cout << " Type: " << type << " (" << types[type] << ")" << std::endl; std::cout << " Length: " << action.at("length") << std::endl; if (action.count("data")) std::cout << " Data: " << action.at("data") << std::endl; if (action.count("relative_offset")) std::cout << " Relative Offset: " << action.at("relative_offset") << std::endl; } std::cout << "Source Checksum: " << properties.at("source_checksum") << std::endl; std::cout << "Target Checksum: " << properties.at("target_checksum") << std::endl; std::cout << "Patch Checksum: " << properties.at("patch_checksum") << std::endl; } void write(const std::string& filename) const { std::ofstream file(filename, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); } }; // Example usage: // int main() { // try { // BPSFile bps("example.bps"); // bps.printProperties(); // bps.write("output.bps"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-066 .BPS ===== // ===== task-067 .BR7 [C] ===== #include #include #include #include typedef struct { char *filepath; char magic[17]; u_int32_t field1, field2, field3, field4, field5, field6; u_int16_t field7; u_char *compressed_data; size_t compressed_size; u_char *decompressed_data; size_t decompressed_size; } BR7File; BR7File* br7_create(const char *filepath) { BR7File *br7 = malloc(sizeof(BR7File)); br7->filepath = strdup(filepath); br7->compressed_data = NULL; br7->decompressed_data = NULL; return br7; } void br7_read(BR7File *br7) { FILE *f = fopen(br7->filepath, "rb"); fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); u_char *data = malloc(size); fread(data, 1, size, f); fclose(f); memcpy(br7->magic, data, 16); br7->magic[16] = '\0'; memcpy(&br7->field1, data + 16, 4); memcpy(&br7->field2, data + 20, 4); memcpy(&br7->field3, data + 24, 4); memcpy(&br7->field4, data + 28, 4); memcpy(&br7->field5, data + 32, 4); memcpy(&br7->field6, data + 36, 4); memcpy(&br7->field7, data + 40, 2); br7->compressed_size = size - 42; br7->compressed_data = malloc(br7->compressed_size); memcpy(br7->compressed_data, data + 42, br7->compressed_size); free(data); br7->decompressed_size = br7->compressed_size * 10; // Estimate br7->decompressed_data = malloc(br7->decompressed_size); int ret = uncompress(br7->decompressed_data, &br7->decompressed_size, br7->compressed_data, br7->compressed_size); if (ret != Z_OK) { free(br7->decompressed_data); br7->decompressed_data = (u_char*)"Decompression failed"; br7->decompressed_size = strlen((char*)br7->decompressed_data); } } void br7_print_properties(BR7File *br7) { printf("Magic String: %s\n", br7->magic); printf("Field 1: %u\n", br7->field1); printf("Field 2: %u\n", br7->field2); printf("Field 3: %u\n", br7->field3); printf("Field 4: %u\n", br7->field4); printf("Field 5: %u\n", br7->field5); printf("Field 6: %u\n", br7->field6); printf("Field 7: %u\n", br7->field7); printf("Compressed Data Size: %zu bytes\n", br7->compressed_size); printf("Decompressed Data Size: %zu bytes\n", br7->decompressed_size); } void br7_write(BR7File *br7, const char *new_filepath) { uLongf comp_size = compressBound(br7->decompressed_size); u_char *comp = malloc(comp_size); int ret = compress(comp, &comp_size, br7->decompressed_data, br7->decompressed_size); if (ret != Z_OK) { free(comp); return; } FILE *f = fopen(new_filepath ? new_filepath : strcat(strdup(br7->filepath), ".new"), "wb"); fwrite(br7->magic, 1, 16, f); fwrite(&br7->field1, 4, 1, f); fwrite(&br7->field2, 4, 1, f); fwrite(&br7->field3, 4, 1, f); fwrite(&br7->field4, 4, 1, f); fwrite(&br7->field5, 4, 1, f); fwrite(&br7->field6, 4, 1, f); fwrite(&br7->field7, 2, 1, f); fwrite(comp, 1, comp_size, f); fclose(f); free(comp); } void br7_destroy(BR7File *br7) { free(br7->filepath); free(br7->compressed_data); if (br7->decompressed_data != (u_char*)"Decompression failed") free(br7->decompressed_data); free(br7); } // ===== end task-067 .BR7 ===== // ===== task-068 .BSK [C] ===== #include #include #include typedef struct { char magic[5]; int version; float sunPosition[3]; float sunColor[3]; float cloudDensity; float fogDensity; } BSKData; void readBSK(const char* filepath, BSKData* data) { FILE* file = fopen(filepath, "rb"); if (!file) { printf("Unable to open file.\n"); exit(1); } fread(data->magic, 1, 4, file); data->magic[4] = '\0'; if (strcmp(data->magic, "BSK ") != 0) { printf("Invalid magic signature.\n"); fclose(file); exit(1); } fread(&data->version, sizeof(int), 1, file); fread(data->sunPosition, sizeof(float), 3, file); fread(data->sunColor, sizeof(float), 3, file); fread(&data->cloudDensity, sizeof(float), 1, file); fread(&data->fogDensity, sizeof(float), 1, file); fclose(file); } void printBSKProperties(const BSKData* data) { printf("Magic: %s\n", data->magic); printf("Version: %d\n", data->version); printf("Sun Position: (%.2f, %.2f, %.2f)\n", data->sunPosition[0], data->sunPosition[1], data->sunPosition[2]); printf("Sun Color: (%.2f, %.2f, %.2f)\n", data->sunColor[0], data->sunColor[1], data->sunColor[2]); printf("Cloud Density: %.2f\n", data->cloudDensity); printf("Fog Density: %.2f\n", data->fogDensity); } void writeBSK(const char* filepath, const BSKData* data) { FILE* file = fopen(filepath, "wb"); if (!file) { printf("Unable to open file for writing.\n"); exit(1); } fwrite(data->magic, 1, 4, file); fwrite(&data->version, sizeof(int), 1, file); fwrite(data->sunPosition, sizeof(float), 3, file); fwrite(data->sunColor, sizeof(float), 3, file); fwrite(&data->cloudDensity, sizeof(float), 1, file); fwrite(&data->fogDensity, sizeof(float), 1, file); fclose(file); } // Example usage: // int main() { // BSKData data; // readBSK("example.bsk", &data); // printBSKProperties(&data); // data.sunPosition[0] = 1.0; // writeBSK("modified.bsk", &data); // return 0; // } // ===== end task-068 .BSK ===== // ===== task-069 .BSON [C++] ===== #include #include #include #include #include #include #include class BSONHandler { private: std::string filepath; std::vector data; std::map parsed; // Simplified; use variant for full types public: BSONHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { throw std::runtime_error("Failed to open file"); } size_t size = file.tellg(); data.resize(size); file.seekg(0); file.read(data.data(), size); } void decode() { if (data.empty()) { read(); } parseBSON(); } void parseBSON() { // Simplified parsing; full implementation would use union or variant for values. // For demonstration, print directly during parse. int32_t size; memcpy(&size, data.data(), 4); std::cout << "Document Size: " << size << " bytes" << std::endl; size_t pos = 4; while (pos < static_cast(size) - 1) { uint8_t type; memcpy(&type, &data[pos], 1); pos += 1; std::string key = readCString(pos); pos += key.length() + 1; std::string value = readValue(type, pos); std::cout << "Key: " << key << ", Type: 0x" << std::hex << static_cast(type) << ", Value: " << value << std::endl; } if (data[pos] != 0) { throw std::runtime_error("Invalid terminator"); } // Store in parsed if needed. } std::string readCString(size_t& pos) { size_t start = pos; while (data[pos] != 0) pos++; return std::string(&data[start], pos - start); } std::string readValue(uint8_t type, size_t& pos) { // Simplified; returns string representation. switch (type) { case 0x01: { double val; memcpy(&val, &data[pos], 8); pos += 8; return std::to_string(val); } case 0x02: { int32_t len; memcpy(&len, &data[pos], 4); pos += 4; std::string val(&data[pos], len - 1); pos += len; return val; } // Add cases for other types. default: { pos += 0; // Stub return "Unsupported"; } } } void printProperties() { decode(); // Parses and prints } void write(const std::string& newFilepath) { // Stub for serialization. std::ofstream file(newFilepath.empty() ? filepath : newFilepath, std::ios::binary); if (!file) { throw std::runtime_error("Failed to write file"); } // Write serialized data. } }; // Example usage: // int main() { // BSONHandler handler("sample.bson"); // handler.printProperties(); // handler.write("output.bson"); // return 0; // } // ===== end task-069 .BSON ===== // ===== task-070 .BSP [C++] ===== #include #include #include #include #include struct Lump { int32_t fileofs; int32_t filelen; int32_t lumpVersion; char fourCC[4]; }; class BSPFile { private: std::string ident; int32_t version; std::vector lumps; int32_t mapRevision; std::string filename; public: BSPFile(const std::string& fn = "") : version(0), mapRevision(0), filename(fn) { lumps.resize(64); ident = "VBSP"; if (!fn.empty()) { read(fn); } } void read(const std::string& fn) { std::ifstream file(fn, std::ios::binary); if (!file) { std::cerr << "Failed to open file." << std::endl; return; } char buffer[1036]; file.read(buffer, 1036); // Read ident ident.assign(buffer, 4); // Read version std::memcpy(&version, buffer + 4, sizeof(int32_t)); // Read lumps for (size_t i = 0; i < 64; ++i) { size_t offset = 8 + i * 16; std::memcpy(&lumps[i].fileofs, buffer + offset, sizeof(int32_t)); std::memcpy(&lumps[i].filelen, buffer + offset + 4, sizeof(int32_t)); std::memcpy(&lumps[i].lumpVersion, buffer + offset + 8, sizeof(int32_t)); std::memcpy(lumps[i].fourCC, buffer + offset + 12, 4); } // Read map revision std::memcpy(&mapRevision, buffer + 1032, sizeof(int32_t)); } void write(const std::string& fn) { std::ofstream file(fn, std::ios::binary); if (!file) { std::cerr << "Failed to write file." << std::endl; return; } char buffer[1036] = {0}; // Write ident std::memcpy(buffer, ident.c_str(), 4); // Write version std::memcpy(buffer + 4, &version, sizeof(int32_t)); // Write lumps for (size_t i = 0; i < 64; ++i) { size_t offset = 8 + i * 16; std::memcpy(buffer + offset, &lumps[i].fileofs, sizeof(int32_t)); std::memcpy(buffer + offset + 4, &lumps[i].filelen, sizeof(int32_t)); std::memcpy(buffer + offset + 8, &lumps[i].lumpVersion, sizeof(int32_t)); std::memcpy(buffer + offset + 12, lumps[i].fourCC, 4); } // Write map revision std::memcpy(buffer + 1032, &mapRevision, sizeof(int32_t)); file.write(buffer, 1036); // Note: Header only; lump data not written. } void printProperties() const { std::cout << "Identification: " << ident << std::endl; std::cout << "Version: " << version << std::endl; std::cout << "Lumps:" << std::endl; for (size_t i = 0; i < 64; ++i) { std::cout << "Lump " << i << ": Offset=" << lumps[i].fileofs << ", Length=" << lumps[i].filelen << ", Version=" << lumps[i].lumpVersion << ", FourCC='"; for (int j = 0; j < 4; ++j) { char c = lumps[i].fourCC[j]; if (c >= 32 && c <= 126) { std::cout << c; } else { std::cout << "\\x" << std::hex << std::setw(2) << std::setfill('0') << (int)(unsigned char)c; } } std::cout << "'" << std::endl; } std::cout << "Map Revision: " << mapRevision << std::endl; } }; int main(int argc, char* argv[]) { if (argc > 1) { BSPFile bsp(argv[1]); bsp.printProperties(); } return 0; } // ===== end task-070 .BSP ===== // ===== task-071 .BYU [C] ===== #include #include #include #define MAX_LINE 1024 #define MAX_PARTS 100 #define MAX_POINTS 10000 #define MAX_POLYS 10000 typedef struct { int nparts; int npoints; int npolys; int nconnects; int ntest; int parts[MAX_PARTS][2]; double points[MAX_POINTS][3]; int polygons[MAX_POLYS][20]; // Assume max 20 sides per poly int poly_sizes[MAX_POLYS]; } BYUFile; void read_byu(BYUFile *byu, const char *filename) { FILE *fp = fopen(filename, "r"); if (!fp) { perror("Error opening file"); return; } char line[MAX_LINE]; fgets(line, MAX_LINE, fp); sscanf(line, "%d %d %d %d %d", &byu->nparts, &byu->npoints, &byu->npolys, &byu->nconnects, &byu->ntest); for (int i = 0; i < byu->nparts; i++) { fgets(line, MAX_LINE, fp); sscanf(line, "%d %d", &byu->parts[i][0], &byu->parts[i][1]); } int point_idx = 0; while (point_idx < byu->npoints) { fgets(line, MAX_LINE, fp); char *token = strtok(line, " "); while (token && point_idx < byu->npoints) { sscanf(token, "%lf", &byu->points[point_idx][0]); token = strtok(NULL, " "); sscanf(token, "%lf", &byu->points[point_idx][1]); token = strtok(NULL, " "); sscanf(token, "%lf", &byu->points[point_idx][2]); point_idx++; token = strtok(NULL, " "); } } int poly_idx = 0; while (poly_idx < byu->npolys) { int size = 0; while (1) { if (!fgets(line, MAX_LINE, fp)) break; char *token = strtok(line, " "); while (token) { int conn; sscanf(token, "%d", &conn); if (conn < 0) { byu->polygons[poly_idx][size++] = -conn; break; } byu->polygons[poly_idx][size++] = conn; token = strtok(NULL, " "); } if (size > 0 && byu->polygons[poly_idx][size-1] > 0) continue; break; } byu->poly_sizes[poly_idx] = size; poly_idx++; } fclose(fp); print_properties(byu); } void print_properties(BYUFile *byu) { printf("Header Properties:\n"); printf("- nparts: %d\n", byu->nparts); printf("- npoints: %d\n", byu->npoints); printf("- npolys: %d\n", byu->npolys); printf("- nconnects: %d\n", byu->nconnects); printf("- ntest: %d\n", byu->ntest); printf("\nPart Boundaries:\n"); for (int i = 0; i < byu->nparts; i++) { printf("- Part %d: first=%d, last=%d\n", i+1, byu->parts[i][0], byu->parts[i][1]); } printf("\nVertex Coordinates:\n"); for (int i = 0; i < byu->npoints; i++) { printf("Point %d: [%.5e, %.5e, %.5e]\n", i+1, byu->points[i][0], byu->points[i][1], byu->points[i][2]); } printf("\nPolygons:\n"); for (int i = 0; i < byu->npolys; i++) { printf("Polygon %d: ", i+1); for (int j = 0; j < byu->poly_sizes[i]; j++) { printf("%d ", byu->polygons[i][j]); } printf("\n"); } } void write_byu(BYUFile *byu, const char *filename) { FILE *fp = fopen(filename, "w"); if (!fp) { perror("Error opening file for write"); return; } fprintf(fp, "%8d%8d%8d%8d%8d\n", byu->nparts, byu->npoints, byu->npolys, byu->nconnects, byu->ntest); for (int i = 0; i < byu->nparts; i++) { fprintf(fp, "%8d%8d\n", byu->parts[i][0], byu->parts[i][1]); } for (int i = 0; i < byu->npoints; i++) { fprintf(fp, "%12.5e%12.5e%12.5e", byu->points[i][0], byu->points[i][1], byu->points[i][2]); if ((i + 1) % 2 == 0) fprintf(fp, "\n"); } if (byu->npoints % 2 != 0) fprintf(fp, "\n"); for (int i = 0; i < byu->npolys; i++) { for (int j = 0; j < byu->poly_sizes[i]; j++) { int idx = byu->polygons[i][j]; if (j == byu->poly_sizes[i] - 1) { fprintf(fp, "%6d ", -idx); } else { fprintf(fp, "%6d ", idx); } if ((j + 1) % 16 == 0) fprintf(fp, "\n"); } fprintf(fp, "\n"); } fclose(fp); } // Usage in main: // int main() { // BYUFile byu; // read_byu(&byu, "sample.byu"); // write_byu(&byu, "output.byu"); // return 0; // } // ===== end task-071 .BYU ===== // ===== task-714 .SXW [C++] ===== #include #include #include #include #include class SXWHandler { private: std::string filename; tinyxml2::XMLDocument doc; public: SXWHandler(const std::string& fn) : filename(fn) {} void readProperties() { zip* z = zip_open(filename.c_str(), 0, nullptr); if (z) { zip_file* f = zip_fopen(z, "meta.xml", 0); if (f) { zip_stat_t stat; zip_stat(z, "meta.xml", 0, &stat); std::vector buffer(stat.size); zip_fread(f, buffer.data(), stat.size); zip_fclose(f); doc.Parse(buffer.data(), stat.size); auto meta = doc.FirstChildElement("office:document-meta")->FirstChildElement("office:meta"); if (meta) { std::cout << "Title: " << (meta->FirstChildElement("dc:title") ? meta->FirstChildElement("dc:title")->GetText() : "") << std::endl; std::cout << "Creator: " << (meta->FirstChildElement("dc:creator") ? meta->FirstChildElement("dc:creator")->GetText() : "") << std::endl; std::cout << "Contributor: " << (meta->FirstChildElement("dc:contributor") ? meta->FirstChildElement("dc:contributor")->GetText() : "") << std::endl; std::cout << "Date: " << (meta->FirstChildElement("dc:date") ? meta->FirstChildElement("dc:date")->GetText() : "") << std::endl; std::cout << "Creation Date: " << (meta->FirstChildElement("meta:creation-date") ? meta->FirstChildElement("meta:creation-date")->GetText() : "") << std::endl; std::cout << "Modification Date: " << (meta->FirstChildElement("meta:modification-date") ? meta->FirstChildElement("meta:modification-date")->GetText() : "") << std::endl; std::cout << "Subject: " << (meta->FirstChildElement("dc:subject") ? meta->FirstChildElement("dc:subject")->GetText() : "") << std::endl; std::cout << "Description: " << (meta->FirstChildElement("dc:description") ? meta->FirstChildElement("dc:description")->GetText() : "") << std::endl; std::cout << "Language: " << (meta->FirstChildElement("dc:language") ? meta->FirstChildElement("dc:language")->GetText() : "") << std::endl; std::cout << "Keywords: "; for (auto kw = meta->FirstChildElement("meta:keyword"); kw; kw = kw->NextSiblingElement("meta:keyword")) { std::cout << (kw->GetText() ? kw->GetText() : "") << " "; } std::cout << std::endl; std::cout << "Printed By: " << (meta->FirstChildElement("meta:printed-by") ? meta->FirstChildElement("meta:printed-by")->GetText() : "") << std::endl; std::cout << "Print Date: " << (meta->FirstChildElement("meta:print-date") ? meta->FirstChildElement("meta:print-date")->GetText() : "") << std::endl; for (auto ud = meta->FirstChildElement("meta:user-defined"); ud; ud = ud->NextSiblingElement("meta:user-defined")) { std::cout << "User Defined - " << ud->Attribute("meta:name") << ": " << (ud->GetText() ? ud->GetText() : "") << std::endl; } auto stats = meta->FirstChildElement("meta:document-statistic"); if (stats) { std::cout << "Page Count: " << stats->Attribute("meta:page-count") << std::endl; std::cout << "Table Count: " << stats->Attribute("meta:table-count") << std::endl; std::cout << "Image Count: " << stats->Attribute("meta:image-count") << std::endl; std::cout << "Object Count: " << stats->Attribute("meta:object-count") << std::endl; std::cout << "Paragraph Count: " << stats->Attribute("meta:paragraph-count") << std::endl; std::cout << "Word Count: " << stats->Attribute("meta:word-count") << std::endl; std::cout << "Character Count: " << stats->Attribute("meta:character-count") << std::endl; } auto template = meta->FirstChildElement("meta:template"); if (template) { std::cout << "Template HREF: " << template->Attribute("xlink:href") << std::endl; std::cout << "Template Title: " << template->Attribute("xlink:title") << std::endl; std::cout << "Template Date: " << template->Attribute("meta:date") << std::endl; } auto autoReload = meta->FirstChildElement("meta:auto-reload"); if (autoReload) { std::cout << "Auto Reload HREF: " << autoReload->Attribute("xlink:href") << std::endl; std::cout << "Auto Reload Delay: " << autoReload->Attribute("meta:delay") << std::endl; } } } else { std::cout << "meta.xml not found." << std::endl; } zip_close(z); } } void writeProperties(const std::string& newFilename, const std::string& newTitle) { zip* zIn = zip_open(filename.c_str(), 0, nullptr); zip* zOut = zip_open(newFilename.c_str(), ZIP_CREATE, nullptr); if (zIn && zOut) { int num = zip_get_num_entries(zIn, 0); for (int i = 0; i < num; ++i) { const char* name = zip_get_name(zIn, i, 0); zip_file* f = zip_fopen_index(zIn, i, 0); zip_stat_t stat; zip_stat_index(zIn, i, 0, &stat); std::vector buffer(stat.size); zip_fread(f, buffer.data(), stat.size); zip_fclose(f); zip_source* src = zip_source_buffer(zOut, buffer.data(), stat.size, 0); if (std::string(name) == "meta.xml") { // Update tinyxml2::XMLDocument tempDoc; tempDoc.Parse(buffer.data(), stat.size); auto meta = tempDoc.FirstChildElement("office:document-meta")->FirstChildElement("office:meta"); auto titleElem = meta->FirstChildElement("dc:title"); if (titleElem) titleElem->SetText(newTitle.c_str()); tinyxml2::XMLPrinter printer; tempDoc.Print(&printer); src = zip_source_buffer(zOut, const_cast(printer.CStr()), printer.CStrSize() - 1, 1); } zip_file_add(zOut, name, src, ZIP_FL_OVERWRITE); } zip_close(zOut); zip_close(zIn); } } }; // Example usage: // int main() { // SXWHandler handler("example.sxw"); // handler.readProperties(); // handler.writeProperties("updated.sxw", "New Title"); // return 0; // } // ===== end task-714 .SXW ===== // ===== task-072 .BZ2 [C++] ===== #include #include #include #include #include #include // Link with -lbz2 for writing class Bz2Handler { private: std::string magic; std::string version; int blockMultiplier; std::string streamCrc; public: void openAndDecode(const std::string& filename) { std::ifstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file."); } file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0, std::ios::beg); if (size < 14) { throw std::runtime_error("File too small for .BZ2 format."); } std::vector data(size); file.read(data.data(), size); // Decode header magic = std::string(1, data[0]) + data[1]; version = std::string(1, data[2]); blockMultiplier = data[3] - '0'; // Decode stream CRC from last 10 bytes std::bitset<80> bits; for (int i = 0; i < 10; ++i) { std::bitset<8> byte(static_cast(data[size - 10 + i])); for (int j = 0; j < 8; ++j) { bits[i * 8 + j] = byte[7 - j]; // MSB first } } unsigned long long endMagic = 0x177245385090ULL; for (int shift = 0; shift < 8; ++shift) { unsigned long long magicBits = (bits >> (80 - 48 - shift)).to_ullong() & ((1ULL << 48) - 1); if (magicBits == endMagic) { unsigned long long crcBits = (bits >> (80 - 48 - 32 - shift)).to_ullong() & ((1ULL << 32) - 1); char buf[9]; sprintf(buf, "%08X", static_cast(crcBits)); streamCrc = buf; break; } } if (streamCrc.empty()) { throw std::runtime_error("Stream end marker not found."); } } void printProperties() { std::cout << "Magic: " << magic << std::endl; std::cout << "Version: " << version << std::endl; std::cout << "Block Size Multiplier: " << blockMultiplier << std::endl; std::cout << "Stream CRC: 0x" << streamCrc << std::endl; } void writeNewFile(const std::string& outputFilename, const char* uncompressedData, size_t dataSize, int compressLevel = 9) { FILE* outFile = fopen(outputFilename.c_str(), "wb"); if (!outFile) { throw std::runtime_error("Cannot open output file."); } BZFILE* bzFile = BZ2_bzWriteOpen(nullptr, outFile, compressLevel, 0, 0); if (!bzFile) { fclose(outFile); throw std::runtime_error("Failed to open BZ2 writer."); } BZ2_bzWrite(&bzFile, const_cast(uncompressedData), dataSize); BZ2_bzWriteClose(nullptr, bzFile, 0, nullptr, nullptr); fclose(outFile); } }; // Example usage: // int main() { // Bz2Handler handler; // try { // handler.openAndDecode("example.bz2"); // handler.printProperties(); // const char* data = "Hello, world!"; // handler.writeNewFile("new.bz2", data, strlen(data), 9); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-072 .BZ2 ===== // ===== task-073 .C [C] ===== #include #include #include #include #include #include #include #include typedef struct { char *filepath; } CFileHandler; CFileHandler* createCFileHandler(const char *filepath) { if (strstr(filepath, ".C") == NULL) { fprintf(stderr, "File must have .C extension\n"); exit(1); } CFileHandler *handler = (CFileHandler*)malloc(sizeof(CFileHandler)); handler->filepath = strdup(filepath); return handler; } void destroyCFileHandler(CFileHandler *handler) { free(handler->filepath); free(handler); } struct stat openAndReadProperties(CFileHandler *handler) { struct stat stats; if (stat(handler->filepath, &stats) != 0) { perror("Error reading file stats"); exit(1); } return stats; } void printProperties(CFileHandler *handler) { struct stat stats = openAndReadProperties(handler); char *filename = strrchr(handler->filepath, '/'); filename = filename ? filename + 1 : handler->filepath; printf("File name: %s\n", filename); printf("File size in bytes: %ld\n", (long)stats.st_size); printf("Creation timestamp: %s", ctime(&stats.st_ctime)); printf("Last modification timestamp: %s", ctime(&stats.st_mtime)); printf("Last access timestamp: %s", ctime(&stats.st_atime)); printf("File permissions: %o\n", stats.st_mode & 0777); printf("Owner user identifier: %d (%s)\n", stats.st_uid, getpwuid(stats.st_uid)->pw_name); printf("Group identifier: %d (%s)\n", stats.st_gid, getgrgid(stats.st_gid)->gr_name); printf("Inode number: %ld\n", (long)stats.st_ino); printf("File type indicator: %s\n", S_ISREG(stats.st_mode) ? "Regular file" : "Other"); } void writeToFile(CFileHandler *handler, const char *content) { FILE *f = fopen(handler->filepath, "w"); if (f == NULL) { perror("Error writing to file"); exit(1); } fprintf(f, "%s", content); fclose(f); } // Example usage: // int main() { // CFileHandler *handler = createCFileHandler("example.C"); // printProperties(handler); // writeToFile(handler, "New content"); // destroyCFileHandler(handler); // return 0; // } // ===== end task-073 .C ===== // ===== task-074 .C32 [C] ===== #include #include #include #include typedef struct { char* key; void* value; // Generic pointer; cast based on type int is_hex; // Flag for hex display } Property; typedef struct { uint8_t* data; size_t data_size; Property* properties; int prop_count; } C32File; void free_c32file(C32File* file) { if (file->data) free(file->data); for (int i = 0; i < file->prop_count; i++) { free(file->properties[i].key); free(file->properties[i].value); } free(file->properties); } int load_file(const char* filename, C32File* file) { FILE* fp = fopen(filename, "rb"); if (!fp) return -1; fseek(fp, 0, SEEK_END); file->data_size = ftell(fp); fseek(fp, 0, SEEK_SET); file->data = malloc(file->data_size); if (!file->data || fread(file->data, 1, file->data_size, fp) != file->data_size) { fclose(fp); return -1; } fclose(fp); return 0; } void parse_header(C32File* file) { if (file->data_size < 52) { fprintf(stderr, "Invalid .C32 file: too short.\n"); return; } file->prop_count = 20; // Number of properties file->properties = malloc(sizeof(Property) * file->prop_count); uint8_t* buf = file->data; // EI_MAG char* mag = malloc(32); sprintf(mag, "0x%02x, 0x%02x, 0x%02x, 0x%02x", buf[0], buf[1], buf[2], buf[3]); file->properties[0] = (Property){"EI_MAG", mag, 0}; // EI_CLASS char* cls = malloc(4); sprintf(cls, "%d", buf[4]); file->properties[1] = (Property){"EI_CLASS", cls, 0}; file->properties[2] = (Property){"EI_DATA", malloc(4), 0}; sprintf(*(char**)file->properties[2].value, "%d", buf[5]); file->properties[3] = (Property){"EI_VERSION", malloc(4), 0}; sprintf(*(char**)file->properties[3].value, "%d", buf[6]); file->properties[4] = (Property){"EI_OSABI", malloc(4), 0}; sprintf(*(char**)file->properties[4].value, "%d", buf[7]); file->properties[5] = (Property){"EI_ABIVERSION", malloc(4), 0}; sprintf(*(char**)file->properties[5].value, "%d", buf[8]); // Little-endian reads uint16_t e_type = (buf[17] << 8) | buf[16]; char* type_str = malloc(4); sprintf(type_str, "%d", e_type); file->properties[6] = (Property){"e_type", type_str, 0}; uint16_t e_machine = (buf[19] << 8) | buf[18]; char* mach_str = malloc(4); sprintf(mach_str, "%d", e_machine); file->properties[7] = (Property){"e_machine", mach_str, 0}; uint32_t e_version = (buf[23] << 24) | (buf[22] << 16) | (buf[21] << 8) | buf[20]; char* ver_str = malloc(4); sprintf(ver_str, "%u", e_version); file->properties[8] = (Property){"e_version", ver_str, 0}; uint32_t e_entry = (buf[27] << 24) | (buf[26] << 16) | (buf[25] << 8) | buf[24]; char* entry_str = malloc(12); sprintf(entry_str, "0x%x", e_entry); file->properties[9] = (Property){"e_entry", entry_str, 1}; uint32_t e_phoff = (buf[31] << 24) | (buf[30] << 16) | (buf[29] << 8) | buf[28]; char* phoff_str = malloc(12); sprintf(phoff_str, "%u", e_phoff); file->properties[10] = (Property){"e_phoff", phoff_str, 0}; uint32_t e_shoff = (buf[35] << 24) | (buf[34] << 16) | (buf[33] << 8) | buf[32]; char* shoff_str = malloc(12); sprintf(shoff_str, "%u", e_shoff); file->properties[11] = (Property){"e_shoff", shoff_str, 0}; uint32_t e_flags = (buf[39] << 24) | (buf[38] << 16) | (buf[37] << 8) | buf[36]; char* flags_str = malloc(12); sprintf(flags_str, "0x%x", e_flags); file->properties[12] = (Property){"e_flags", flags_str, 1}; uint16_t e_ehsize = (buf[41] << 8) | buf[40]; char* ehsize_str = malloc(4); sprintf(ehsize_str, "%d", e_ehsize); file->properties[13] = (Property){"e_ehsize", ehsize_str, 0}; uint16_t e_phentsize = (buf[43] << 8) | buf[42]; char* phentsize_str = malloc(4); sprintf(phentsize_str, "%d", e_phentsize); file->properties[14] = (Property){"e_phentsize", phentsize_str, 0}; uint16_t e_phnum = (buf[45] << 8) | buf[44]; char* phnum_str = malloc(4); sprintf(phnum_str, "%d", e_phnum); file->properties[15] = (Property){"e_phnum", phnum_str, 0}; uint16_t e_shentsize = (buf[47] << 8) | buf[46]; char* shentsize_str = malloc(4); sprintf(shentsize_str, "%d", e_shentsize); file->properties[16] = (Property){"e_shentsize", shentsize_str, 0}; uint16_t e_shnum = (buf[49] << 8) | buf[48]; char* shnum_str = malloc(4); sprintf(shnum_str, "%d", e_shnum); file->properties[17] = (Property){"e_shnum", shnum_str, 0}; uint16_t e_shstrndx = (buf[51] << 8) | buf[50]; char* shstrndx_str = malloc(4); sprintf(shstrndx_str, "%d", e_shstrndx); file->properties[18] = (Property){"e_shstrndx", shstrndx_str, 0}; char* size_str = malloc(12); sprintf(size_str, "%zu", file->data_size); file->properties[19] = (Property){"FileSize", size_str, 0}; } void print_properties(C32File* file) { if (!file->properties) { printf("No properties loaded. Call load_file() and parse_header() first.\n"); return; } printf("C32 (.ELF32) Properties:\n"); for (int i = 0; i < file->prop_count; i++) { Property p = file->properties[i]; char* val = *(char**)p.value; if (p.is_hex) { printf("%s: %s\n", p.key, val); } else { printf("%s: %s\n", p.key, val); } } } int write_file(C32File* file, const char* output_filename) { if (!file->data) return -1; FILE* fp = fopen(output_filename, "wb"); if (!fp) return -1; size_t written = fwrite(file->data, 1, file->data_size, fp); fclose(fp); if (written != file->data_size) return -1; printf("Written to %s\n", output_filename); return 0; } // Example usage in main: int main(int argc, char* argv[]) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } C32File file = {0}; if (load_file(argv[1], &file) != 0) { perror("Load failed"); return 1; } parse_header(&file); print_properties(&file); write_file(&file, "output.c32"); free_c32file(&file); return 0; } // ===== end task-074 .C32 ===== // ===== task-075 .CAB [C++] ===== #include #include #include #include #include #include struct CabProperties { std::string signature; uint32_t reserved1; uint32_t cbCabinet; uint32_t reserved2; uint32_t coffFiles; uint8_t versionMinor; uint8_t versionMajor; uint16_t cFolders; uint16_t cFiles; uint16_t flags; uint16_t setID; uint16_t iCabinet; uint16_t cbCFHeader = 0; uint8_t cbCFFolder = 0; uint8_t cbCFData = 0; std::vector abReserve_header; std::string szCabinetPrev; std::string szDiskPrev; std::string szCabinetNext; std::string szDiskNext; }; struct CabFolder { uint32_t coffCabStart; uint16_t cCFData; uint16_t typeCompress; std::vector abReserve_folder; }; struct CabFileEntry { uint32_t cbFile; uint32_t uoffFolderStart; uint16_t iFolder; uint16_t date; uint16_t time; uint16_t attribs; std::string szName; }; struct CabDataBlock { uint32_t csum; uint16_t cbData; uint16_t cbUncomp; std::vector abReserve_data; std::vector ab; }; class CabFile { private: std::string filepath; std::vector data; CabProperties properties; std::vector folders; std::vector files; std::vector data_blocks; public: CabFile(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { std::cerr << "Failed to open file." << std::endl; return; } size_t size = file.tellg(); file.seekg(0); data.resize(size); file.read(reinterpret_cast(data.data()), size); decode(); } void decode() { size_t offset = 0; // CFHEADER properties.signature = std::string(reinterpret_cast(&data[offset]), 4); offset += 4; memcpy(&properties.reserved1, &data[offset], 4); offset += 4; memcpy(&properties.cbCabinet, &data[offset], 4); offset += 4; memcpy(&properties.reserved2, &data[offset], 4); offset += 4; memcpy(&properties.coffFiles, &data[offset], 4); offset += 4; properties.versionMinor = data[offset]; offset += 1; properties.versionMajor = data[offset]; offset += 1; memcpy(&properties.cFolders, &data[offset], 2); uint16_t cFolders = properties.cFolders; offset += 2; memcpy(&properties.cFiles, &data[offset], 2); uint16_t cFiles = properties.cFiles; offset += 2; memcpy(&properties.flags, &data[offset], 2); uint16_t flags = properties.flags; offset += 2; memcpy(&properties.setID, &data[offset], 2); offset += 2; memcpy(&properties.iCabinet, &data[offset], 2); offset += 2; if (flags & 0x0004) { memcpy(&properties.cbCFHeader, &data[offset], 2); offset += 2; properties.cbCFFolder = data[offset]; offset += 1; properties.cbCFData = data[offset]; offset += 1; } if (properties.cbCFHeader > 0) { properties.abReserve_header.assign(&data[offset], &data[offset + properties.cbCFHeader]); offset += properties.cbCFHeader; } if (flags & 0x0001) { properties.szCabinetPrev = read_null_term(offset); offset += properties.szCabinetPrev.length() + 1; properties.szDiskPrev = read_null_term(offset); offset += properties.szDiskPrev.length() + 1; } if (flags & 0x0002) { properties.szCabinetNext = read_null_term(offset); offset += properties.szCabinetNext.length() + 1; properties.szDiskNext = read_null_term(offset); offset += properties.szDiskNext.length() + 1; } // CFFOLDERs for (uint16_t i = 0; i < cFolders; ++i) { CabFolder folder; memcpy(&folder.coffCabStart, &data[offset], 4); offset += 4; memcpy(&folder.cCFData, &data[offset], 2); offset += 2; memcpy(&folder.typeCompress, &data[offset], 2); offset += 2; if (properties.cbCFFolder > 0) { folder.abReserve_folder.assign(&data[offset], &data[offset + properties.cbCFFolder]); offset += properties.cbCFFolder; } folders.push_back(folder); } // CFFILEs offset = properties.coffFiles; for (uint16_t i = 0; i < cFiles; ++i) { CabFileEntry file_entry; memcpy(&file_entry.cbFile, &data[offset], 4); offset += 4; memcpy(&file_entry.uoffFolderStart, &data[offset], 4); offset += 4; memcpy(&file_entry.iFolder, &data[offset], 2); offset += 2; memcpy(&file_entry.date, &data[offset], 2); offset += 2; memcpy(&file_entry.time, &data[offset], 2); offset += 2; memcpy(&file_entry.attribs, &data[offset], 2); offset += 2; file_entry.szName = read_null_term(offset); offset += file_entry.szName.length() + 1; files.push_back(file_entry); } // CFDATA blocks for (const auto& folder : folders) { offset = folder.coffCabStart; for (uint16_t d = 0; d < folder.cCFData; ++d) { CabDataBlock data_block; memcpy(&data_block.csum, &data[offset], 4); offset += 4; memcpy(&data_block.cbData, &data[offset], 2); uint16_t cbData = data_block.cbData; offset += 2; memcpy(&data_block.cbUncomp, &data[offset], 2); offset += 2; if (properties.cbCFData > 0) { data_block.abReserve_data.assign(&data[offset], &data[offset + properties.cbCFData]); offset += properties.cbCFData; } data_block.ab.assign(&data[offset], &data[offset + cbData]); offset += cbData; data_blocks.push_back(data_block); } } } std::string read_null_term(size_t offset) { std::string str; while (data[offset] != 0) { str += static_cast(data[offset]); ++offset; } return str; } void print_properties() { std::cout << "CFHEADER Properties:" << std::endl; std::cout << " signature: " << properties.signature << std::endl; std::cout << " reserved1: " << properties.reserved1 << std::endl; std::cout << " cbCabinet: " << properties.cbCabinet << std::endl; std::cout << " reserved2: " << properties.reserved2 << std::endl; std::cout << " coffFiles: " << properties.coffFiles << std::endl; std::cout << " versionMinor: " << static_cast(properties.versionMinor) << std::endl; std::cout << " versionMajor: " << static_cast(properties.versionMajor) << std::endl; std::cout << " cFolders: " << properties.cFolders << std::endl; std::cout << " cFiles: " << properties.cFiles << std::endl; std::cout << " flags: " << properties.flags << std::endl; std::cout << " setID: " << properties.setID << std::endl; std::cout << " iCabinet: " << properties.iCabinet << std::endl; if (properties.flags & 0x0004) { std::cout << " cbCFHeader: " << properties.cbCFHeader << std::endl; std::cout << " cbCFFolder: " << static_cast(properties.cbCFFolder) << std::endl; std::cout << " cbCFData: " << static_cast(properties.cbCFData) << std::endl; } if (!properties.abReserve_header.empty()) { std::cout << " abReserve_header: [binary data, size " << properties.abReserve_header.size() << "]" << std::endl; } if (properties.flags & 0x0001) { std::cout << " szCabinetPrev: " << properties.szCabinetPrev << std::endl; std::cout << " szDiskPrev: " << properties.szDiskPrev << std::endl; } if (properties.flags & 0x0002) { std::cout << " szCabinetNext: " << properties.szCabinetNext << std::endl; std::cout << " szDiskNext: " << properties.szDiskNext << std::endl; } std::cout << "\nFolders:" << std::endl; for (size_t i = 0; i < folders.size(); ++i) { std::cout << " Folder " << i << ":" << std::endl; std::cout << " coffCabStart: " << folders[i].coffCabStart << std::endl; std::cout << " cCFData: " << folders[i].cCFData << std::endl; std::cout << " typeCompress: " << folders[i].typeCompress << std::endl; if (!folders[i].abReserve_folder.empty()) { std::cout << " abReserve_folder: [binary data, size " << folders[i].abReserve_folder.size() << "]" << std::endl; } } std::cout << "\nFiles:" << std::endl; for (size_t i = 0; i < files.size(); ++i) { std::cout << " File " << i << ":" << std::endl; std::cout << " cbFile: " << files[i].cbFile << std::endl; std::cout << " uoffFolderStart: " << files[i].uoffFolderStart << std::endl; std::cout << " iFolder: " << files[i].iFolder << std::endl; std::cout << " date: " << files[i].date << std::endl; std::cout << " time: " << files[i].time << std::endl; std::cout << " attribs: " << files[i].attribs << std::endl; std::cout << " szName: " << files[i].szName << std::endl; } std::cout << "\nData Blocks:" << std::endl; for (size_t i = 0; i < data_blocks.size(); ++i) { std::cout << " Data Block " << i << ":" << std::endl; std::cout << " csum: " << data_blocks[i].csum << std::endl; std::cout << " cbData: " << data_blocks[i].cbData << std::endl; std::cout << " cbUncomp: " << data_blocks[i].cbUncomp << std::endl; if (!data_blocks[i].abReserve_data.empty()) { std::cout << " abReserve_data: [binary data, size " << data_blocks[i].abReserve_data.size() << "]" << std::endl; } std::cout << " ab: [binary data, size " << data_blocks[i].ab.size() << "]" << std::endl; } } void write(const std::string& output_path) { std::ofstream out(output_path, std::ios::binary); if (!out) { std::cerr << "Failed to write file." << std::endl; return; } out.write(reinterpret_cast(data.data()), data.size()); std::cout << "Written to " << output_path << std::endl; } }; // Example usage: // int main() { // CabFile cab("sample.cab"); // cab.read(); // cab.print_properties(); // cab.write("output.cab"); // return 0; // } // ===== end task-075 .CAB ===== // ===== task-076 .CBL [C] ===== #include #include #include #define MAX_LINE 81 // 80 chars + null #define MAX_LINES 10000 typedef struct { char filename[256]; char lines[MAX_LINES][MAX_LINE]; int total_lines; char encoding[16]; char line_endings[16]; } CBLHandler; void init_handler(CBLHandler *handler, const char *filename) { strcpy(handler->filename, filename); if (strstr(filename, ".cbl") == NULL && strstr(filename, ".CBL") == NULL) { fprintf(stderr, "Error: File must have .CBL extension.\n"); exit(1); } handler->total_lines = 0; strcpy(handler->encoding, "UTF-8"); strcpy(handler->line_endings, "LF/CRLF (auto-detected)"); } void read_decode(CBLHandler *handler) { FILE *file = fopen(handler->filename, "r"); if (!file) { perror("Error opening file"); exit(1); } char buffer[MAX_LINE]; int crlf = 0; while (fgets(buffer, sizeof(buffer), file) && handler->total_lines < MAX_LINES) { // Check for CRLF if (strstr(buffer, "\r\n")) crlf = 1; strcpy(handler->lines[handler->total_lines], buffer); handler->total_lines++; } fclose(file); strcpy(handler->line_endings, crlf ? "CRLF" : "LF"); } void print_properties(const CBLHandler *handler) { printf("CBL File Properties:\n"); printf("====================\n"); printf("Total Lines: %d\n", handler->total_lines); printf("Encoding: %s\n", handler->encoding); printf("Line Endings: %s\n", handler->line_endings); printf("\nLine-by-Line Decode:\n"); printf("Line # | Seq (1-6) | Ind (7) | A (8-11) | B (12-72) | Ident (73-80)\n"); printf("-------|------------|---------|----------|-----------|-------------\n"); for (int i = 0; i < handler->total_lines; i++) { char padded[MAX_LINE]; strncpy(padded, handler->lines[i], MAX_LINE - 1); padded[MAX_LINE - 1] = '\0'; // Remove trailing newline char *nl = strrchr(padded, '\n'); if (nl) *nl = '\0'; // Pad to 80 int len = strlen(padded); if (len < 80) memset(padded + len, ' ', 80 - len); padded[80] = '\0'; char seq[7], ind[2], areaA[5], areaB[62], ident[9]; strncpy(seq, padded, 6); seq[6] = '\0'; strncpy(ind, padded + 6, 1); ind[1] = '\0'; strncpy(areaA, padded + 7, 4); areaA[4] = '\0'; strncpy(areaB, padded + 11, 61); areaB[61] = '\0'; strncpy(ident, padded + 72, 8); ident[8] = '\0'; // Trim spaces for (int j = 5; j >= 0; j--) if (seq[j] != ' ') break; seq[j+1] = '\0'; for (int j = 3; j >= 0; j--) if (areaA[j] != ' ') break; areaA[j+1] = '\0'; for (int j = 60; j >= 0; j--) if (areaB[j] != ' ') break; areaB[j+1] = '\0'; for (int j = 7; j >= 0; j--) if (ident[j] != ' ') break; ident[j+1] = '\0'; printf("%6d | %-10s | %-7s | %-8s | %.20s... | %-13s\n", i + 1, seq, ind, areaA, areaB, ident); } } void write_file(const CBLHandler *handler, const char *output_filename) { char *out_name = (char *)output_filename; if (!out_name) out_name = handler->filename; FILE *out = fopen(out_name, "w"); if (!out) { perror("Error writing file"); return; } int seq_num = 100; for (int i = 0; i < handler->total_lines; i++) { char padded[MAX_LINE]; strncpy(padded, handler->lines[i], MAX_LINE - 1); padded[MAX_LINE - 1] = '\0'; char *nl = strrchr(padded, '\n'); if (nl) *nl = '\0'; int len = strlen(padded); if (len < 80) memset(padded + len, ' ', 80 - len); padded[80] = '\0'; if (padded[0] == ' ' || !isdigit(padded[0])) { // No seq num char new_line[MAX_LINE]; snprintf(new_line, sizeof(new_line), "%06d%s", seq_num, padded + 6); fputs(new_line, out); seq_num += 10; } else { fputs(padded, out); } fputc('\n', out); } fclose(out); printf("Written to %s\n", out_name); } /* Example usage: int main() { CBLHandler handler; init_handler(&handler, "sample.cbl"); read_decode(&handler); print_properties(&handler); write_file(&handler, "output.cbl"); return 0; } */ // ===== end task-076 .CBL ===== // ===== task-077 .CBT [C] ===== #include #include #include #include #include #include #include #define BLOCK_SIZE 512 #define HEADER_SIZE 512 typedef struct { char name[101]; char mode[9]; char uid[9]; char gid[9]; char size[13]; char mtime[13]; char checksum[9]; char type_flag[2]; char link_name[101]; char magic[7]; char version[3]; char uname[33]; char gname[33]; char dev_major[9]; char dev_minor[9]; char prefix[156]; long data_size; } TarEntryProperties; typedef struct { char *filepath; TarEntryProperties *entries; int entry_count; } CBTReader; CBTReader *cbt_reader_new(const char *filepath) { CBTReader *reader = malloc(sizeof(CBTReader)); reader->filepath = strdup(filepath); reader->entries = NULL; reader->entry_count = 0; return reader; } void cbt_reader_free(CBTReader *reader) { if (reader->entries) free(reader->entries); free(reader->filepath); free(reader); } int parse_octal(const char *str) { int val = 0; for (int i = 0; str[i] && str[i] != ' '; i++) { val = val * 8 + (str[i] - '0'); } return val; } char *decode_ascii(const char *bytes, int len) { char *str = malloc(len + 1); memcpy(str, bytes, len); str[len] = '\0'; for (int i = 0; str[i]; i++) { if (str[i] == '\0') str[i] = '\0'; // Null terminate properly } return str; } int is_null_block(unsigned char *block) { for (int i = 0; i < BLOCK_SIZE; i++) { if (block[i] != 0) return 0; } return 1; } int cbt_open(CBTReader *reader) { int fd = open(reader->filepath, O_RDONLY); if (fd < 0) return -1; unsigned char *buffer = malloc(BLOCK_SIZE); reader->entries = malloc(sizeof(TarEntryProperties) * 100); // Assume max 100 int pos = 0; int count = 0; while (read(fd, buffer, BLOCK_SIZE) == BLOCK_SIZE) { if (is_null_block(buffer)) { if (read(fd, buffer, BLOCK_SIZE) == BLOCK_SIZE && is_null_block(buffer)) break; } if (count >= 100) break; // Limit TarEntryProperties *entry = &reader->entries[count]; strncpy(entry->name, (char *)buffer, 100); entry->name[100] = '\0'; strncpy(entry->mode, (char *)buffer + 100, 8); entry->mode[8] = '\0'; strncpy(entry->uid, (char *)buffer + 108, 8); entry->uid[8] = '\0'; strncpy(entry->gid, (char *)buffer + 116, 8); entry->gid[8] = '\0'; strncpy(entry->size, (char *)buffer + 124, 12); entry->size[12] = '\0'; strncpy(entry->mtime, (char *)buffer + 136, 12); entry->mtime[12] = '\0'; strncpy(entry->checksum, (char *)buffer + 148, 8); entry->checksum[8] = '\0'; entry->type_flag[0] = buffer[156]; entry->type_flag[1] = '\0'; strncpy(entry->link_name, (char *)buffer + 157, 100); entry->link_name[100] = '\0'; strncpy(entry->magic, (char *)buffer + 257, 6); entry->magic[6] = '\0'; strncpy(entry->version, (char *)buffer + 263, 2); entry->version[2] = '\0'; strncpy(entry->uname, (char *)buffer + 265, 32); entry->uname[32] = '\0'; strncpy(entry->gname, (char *)buffer + 297, 32); entry->gname[32] = '\0'; strncpy(entry->dev_major, (char *)buffer + 329, 8); entry->dev_major[8] = '\0'; strncpy(entry->dev_minor, (char *)buffer + 337, 8); entry->dev_minor[8] = '\0'; strncpy(entry->prefix, (char *)buffer + 345, 155); entry->prefix[155] = '\0'; entry->data_size = parse_octal(entry->size); long padded = ((entry->data_size + BLOCK_SIZE - 1) / BLOCK_SIZE) * BLOCK_SIZE; lseek(fd, padded, SEEK_CUR); // Skip data count++; pos += BLOCK_SIZE + padded; } reader->entry_count = count; free(buffer); close(fd); return 0; } void cbt_print_properties(CBTReader *reader) { printf("CBT File Properties:\n"); printf("Block Size: 512 bytes\n"); printf("Total Entries: %d\n", reader->entry_count); long total_size = 0; for (int i = 0; i < reader->entry_count; i++) { total_size += reader->entries[i].data_size; } total_size += BLOCK_SIZE * reader->entry_count; printf("Approximate Total Size: %ld bytes\n", total_size); for (int i = 0; i < reader->entry_count; i++) { TarEntryProperties *entry = &reader->entries[i]; char full_name[256]; if (strlen(entry->prefix)) { snprintf(full_name, sizeof(full_name), "%s/%s", entry->prefix, entry->name); } else { strcpy(full_name, entry->name); } printf("\nEntry %d:\n", i + 1); printf(" Name: %s\n", full_name); printf(" Mode: %s\n", entry->mode); printf(" UID: %d\n", parse_octal(entry->uid)); printf(" GID: %d\n", parse_octal(entry->gid)); printf(" Size: %ld bytes\n", entry->data_size); printf(" Modification Time: %ld (Unix timestamp)\n", parse_octal(entry->mtime)); printf(" Checksum: %s\n", entry->checksum); printf(" Type Flag: %s\n", entry->type_flag); if (strlen(entry->link_name)) printf(" Link Name: %s\n", entry->link_name); printf(" USTAR Magic: %s\n", entry->magic); printf(" Version: %s\n", entry->version); if (strlen(entry->uname)) printf(" User Name: %s\n", entry->uname); if (strlen(entry->gname)) printf(" Group Name: %s\n", entry->gname); printf(" Device Major/Minor: %d/%d\n", parse_octal(entry->dev_major), parse_octal(entry->dev_minor)); } printf("\nEnd-of-Archive: Detected (two null blocks).\n"); } int cbt_write(CBTReader *reader, const char *output_path) { int out_fd = open(output_path, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (out_fd < 0) return -1; int in_fd = open(reader->filepath, O_RDONLY); if (in_fd < 0) { close(out_fd); return -1; } char buffer[BLOCK_SIZE]; ssize_t bytes; while ((bytes = read(in_fd, buffer, BLOCK_SIZE)) == BLOCK_SIZE) { write(out_fd, buffer, BLOCK_SIZE); } close(in_fd); close(out_fd); return 0; } // Example usage: // int main() { // CBTReader *reader = cbt_reader_new("sample.cbt"); // if (cbt_open(reader) == 0) { // cbt_print_properties(reader); // cbt_write(reader, "output.cbt"); // } // cbt_reader_free(reader); // return 0; // } // ===== end task-077 .CBT ===== // ===== task-078 .CC [C] ===== #include #include #include typedef struct { uint16_t hash; uint32_t offset; // UINT24 as uint32_t uint32_t comp_size; // UINT24 as uint32_t } CCEntry; typedef struct { uint16_t num_files; CCEntry *entries; } CCFile; void load_cc(const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) { perror("Error opening file"); return; } uint8_t header[2]; fread(header, 1, 2, f); uint16_t num_files = (uint16_t)(header[0] | (header[1] << 8)); // UINT16LE printf("Number of Files: %u\n", num_files); printf("\nFile Entries:\n"); CCFile cc = {num_files, malloc(num_files * sizeof(CCEntry))}; for (uint16_t i = 0; i < num_files; i++) { uint8_t entry[8]; fread(entry, 1, 8, f); uint16_t hash = (uint16_t)(entry[0] | (entry[1] << 8)); // UINT16LE uint32_t file_offset = (uint32_t)(entry[2] | (entry[3] << 8) | (entry[4] << 16)); // UINT24LE uint32_t comp_size = (uint32_t)(entry[5] | (entry[6] << 8) | (entry[7] << 16)); // UINT24LE cc.entries[i].hash = hash; cc.entries[i].offset = file_offset; cc.entries[i].comp_size = comp_size; printf("Entry %u:\n", i + 1); printf(" Hash: 0x%04X\n", hash); printf(" Offset: 0x%06X\n", file_offset); printf(" Compressed Size: %u bytes\n", comp_size); } fclose(f); free(cc.entries); // Clean up } void write_cc_header(const char *output_filename, CCFile *cc) { FILE *f = fopen(output_filename, "wb"); if (!f) { perror("Error writing file"); return; } uint8_t num_buf[2]; num_buf[0] = (uint8_t)(cc->num_files & 0xFF); num_buf[1] = (uint8_t)((cc->num_files >> 8) & 0xFF); fwrite(num_buf, 1, 2, f); // UINT16LE uint32_t current_offset = 2 + 8 * cc->num_files; for (uint16_t i = 0; i < cc->num_files; i++) { uint8_t entry_buf[8]; // Hash UINT16LE entry_buf[0] = (uint8_t)(cc->entries[i].hash & 0xFF); entry_buf[1] = (uint8_t)((cc->entries[i].hash >> 8) & 0xFF); // Offset UINT24LE (use current_offset for sequential) uint32_t off = current_offset; entry_buf[2] = (uint8_t)(off & 0xFF); entry_buf[3] = (uint8_t)((off >> 8) & 0xFF); entry_buf[4] = (uint8_t)((off >> 16) & 0xFF); // Comp size UINT24LE entry_buf[5] = (uint8_t)(cc->entries[i].comp_size & 0xFF); entry_buf[6] = (uint8_t)((cc->entries[i].comp_size >> 8) & 0xFF); entry_buf[7] = (uint8_t)((cc->entries[i].comp_size >> 16) & 0xFF); fwrite(entry_buf, 1, 8, f); current_offset += cc->entries[i].comp_size; } fclose(f); printf("Header written to %s\n", output_filename); } // Example usage in main: // int main() { load_cc("example.cc"); return 0; } // ===== end task-078 .CC ===== // ===== task-079 .CD [C] ===== #include #include #include typedef struct { char filename[256]; unsigned char* buffer; size_t file_size; char properties[10][256]; // Simple key-value array int prop_count; } CDHandler; void init_handler(CDHandler* h, const char* fn) { strcpy(h->filename, fn); h->buffer = NULL; h->file_size = 0; h->prop_count = 0; } void add_property(CDHandler* h, const char* key, const char* value) { snprintf(h->properties[h->prop_count], 256, "%s: %s", key, value); h->prop_count++; } void read_file(CDHandler* h) { FILE* f = fopen(h->filename, "rb"); if (!f) { printf("Error opening file\n"); return; } fseek(f, 0, SEEK_END); h->file_size = ftell(f); fseek(f, 0, SEEK_SET); h->buffer = malloc(h->file_size); fread(h->buffer, 1, h->file_size, f); fclose(f); decode(h); print_properties(h); } void decode(CDHandler* h) { if (!h->buffer) return; int sector_size = 2352; int num_sectors = h->file_size / sector_size; int start_sector = (num_sectors - 1 < 2400) ? num_sectors - 1 : 2400; int pvd_offset = start_sector * sector_size + 16; int sig_offset = pvd_offset + 8; if (sig_offset + 5 <= h->file_size) { char sig[6] = {0}; memcpy(sig, h->buffer + sig_offset, 5); sig[5] = '\0'; add_property(h, "signature", sig); if (strcmp(sig, "CD-I ") == 0) { add_property(h, "fileSystemType", "OS-9 variant (CD-i)"); add_property(h, "sectorFormat", "Mode 2 (2352 bytes)"); add_property(h, "maxFilenameLength", "28"); add_property(h, "caseSensitivity", "Mixed case, no case-insensitive duplicates"); add_property(h, "directoryDepth", "Unlimited"); add_property(h, "permissions", "Unix-like (rwx for owner/group/other)"); // Sample Disc Label int label_offset = 166 * sector_size; if (label_offset < h->file_size) { char title[33] = {0}; memcpy(title, h->buffer + label_offset + 40, 32); title[32] = '\0'; for (int i = 0; i < 32; i++) if (!title[i]) title[i] = '\0'; // Trim nulls char title_prop[256]; snprintf(title_prop, 256, "discTitle: %s", title); strcpy(h->properties[h->prop_count++], title_prop); } add_property(h, "interleavingSupport", "Yes (real-time audio/video)"); char cap[32]; snprintf(cap, 32, "%.0f (approx)", (num_sectors * 2324.0 / 1024 / 1024)); add_property(h, "volumeCapacityMB", cap); } else { add_property(h, "error", "Not a valid CD-i .CD image"); } } else { add_property(h, "error", "File too small"); } } void print_properties(CDHandler* h) { for (int i = 0; i < h->prop_count; i++) { printf("%s\n", h->properties[i]); } } void write_file(CDHandler* h, const char* output_fn, const char* new_title) { if (new_title) { h->buffer = realloc(h->buffer, h->file_size); // Ensure mutable int label_offset = 166 * 2352 + 40; unsigned char title_bytes[32] = {0}; int len = strlen(new_title); if (len > 32) len = 32; memcpy(title_bytes, new_title, len); memcpy(h->buffer + label_offset, title_bytes, 32); } FILE* f = fopen(output_fn, "wb"); if (f) { fwrite(h->buffer, 1, h->file_size, f); fclose(f); printf("Written updated .CD to %s\n", output_fn); } } void free_handler(CDHandler* h) { if (h->buffer) free(h->buffer); } int main() { CDHandler h; init_handler(&h, "example.cd"); read_file(&h); write_file(&h, "updated.cd", "Updated Disc Title"); free_handler(&h); return 0; } // ===== end task-079 .CD ===== // ===== task-080 .CDF [C] ===== #include #include #include typedef unsigned long long uint64_t; typedef unsigned int uint32_t; typedef int int32_t; typedef struct { uint8_t *data; size_t size; size_t offset; } CDFReader; uint32_t read_uint32(CDFReader *r) { uint32_t val = (r->data[r->offset] << 24) | (r->data[r->offset+1] << 16) | (r->data[r->offset+2] << 8) | r->data[r->offset+3]; r->offset += 4; return val; } int32_t read_int32(CDFReader *r) { int32_t val = (r->data[r->offset] << 24) | (r->data[r->offset+1] << 16) | (r->data[r->offset+2] << 8) | r->data[r->offset+3]; if (val & 0x80000000) val |= 0xFFFFFFFF00000000LL; // Sign extend r->offset += 4; return val; } uint64_t read_uint64(CDFReader *r) { uint64_t high = read_uint32(r); uint64_t low = read_uint32(r); return (high << 32) | low; } char* read_string(CDFReader *r, int length) { char *s = malloc(length + 1); memcpy(s, &r->data[r->offset], length); s[length] = '\0'; for (int i = 0; i < length; i++) if (s[i] == '\0') { s[i] = '\0'; break; } r->offset += length; return s; } void decode_properties(CDFReader *r) { uint32_t magic1 = read_uint32(r); uint32_t magic2 = read_uint32(r); printf("magic1: 0x%08X\n", magic1); printf("magic2: 0x%08X\n", magic2); r->offset = 8; r->offset += 8; // RecordSize read_int32(r); // Type uint64_t gdr_offset = read_uint64(r); int32_t version = read_int32(r); int32_t release = read_int32(r); int32_t encoding = read_int32(r); int32_t flags = read_int32(r); r->offset += 8; // rfu int32_t increment = read_int32(r); int32_t identifier = read_int32(r); read_int32(r); // rfuE char *copyright = read_string(r, 256); printf("version: %d\n", version); printf("release: %d\n", release); printf("encoding: %d\n", encoding); printf("flags: 0x%08X\n", flags); printf("increment: %d\n", increment); printf("identifier: %d\n", identifier); printf("copyright: %s\n", copyright); free(copyright); // GDR partial r->offset = gdr_offset; r->offset += 44; // To NrVars int32_t nr_vars = read_int32(r); int32_t num_attr = read_int32(r); r->offset += 4; // rMaxRec int32_t r_num_dims = read_int32(r); int32_t nz_vars = read_int32(r); printf("nr_vars: %d\n", nr_vars); printf("num_attr: %d\n", num_attr); printf("r_num_dims: %d\n", r_num_dims); printf("nz_vars: %d\n", nz_vars); } void write_file(const char *input, const char *output) { FILE *in = fopen(input, "rb"); FILE *out = fopen(output, "wb"); fseek(in, 0, SEEK_END); size_t size = ftell(in); fseek(in, 0, SEEK_SET); char *buf = malloc(size); fread(buf, 1, size, in); fwrite(buf, 1, size, out); fclose(in); fclose(out); free(buf); printf("Written to %s (copy)\n", output); } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: ./cdf_reader \n"); return 1; } FILE *f = fopen(argv[1], "rb"); if (!f) { perror("Error opening file"); return 1; } fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); CDFReader r = {data, size, 0}; decode_properties(&r); write_file(argv[1], "output.cdf"); free(data); return 0; } // ===== end task-080 .CDF ===== // ===== task-081 .CDR [C] ===== #include #include #include #include typedef struct { char structure[32]; uint32_t chunk_size; char version[8]; char magic[8]; char endianness[16]; // Add more as needed } CDRProperties; typedef struct { FILE *file; uint8_t *data; size_t size; CDRProperties props; } CDRDecoder; void read_properties(CDRDecoder *decoder) { uint8_t *data = decoder->data; // ZIP check (simplified; full needs libzip) if (data[0] == 0x50 && data[1] == 0x4B && data[2] == 0x03 && data[3] == 0x04) { strcpy(decoder->props.structure, "ZIP Archive (X4+)"); strcpy(decoder->props.compression, "Deflate"); // Note: compression added strcpy(decoder->props.endianness, "Little-endian"); strcpy(decoder->props.version, "Inferred from ZIP"); // Entries stub printf("ZIP entries: content/riffData.cdr or root.dat + data/*.dat\n"); } else { // RIFF check if (data[0] == 0x52 && data[1] == 0x49 && data[2] == 0x46 && data[3] == 0x46) { strcpy(decoder->props.structure, "RIFF Chunk (pre-X4)"); decoder->props.chunk_size = data[7] | (data[6] << 8) | (data[5] << 16) | (data[4] << 24); memcpy(decoder->props.version, &data[8], 4); decoder->props.version[4] = '\0'; strcpy(decoder->props.magic, "RIFF"); strcpy(decoder->props.endianness, "Little-endian"); printf("Chunks: COLR, PAGE, LAYR, OBJD, STYL\n"); printf("Objects: Paths, rects, ellipses, text, images\n"); printf("Styles: Fills/gradients, outlines, transforms\n"); } else { strcpy(decoder->props.structure, "Invalid CDR"); } } // Print printf("structure: %s\n", decoder->props.structure); printf("chunk_size: %u\n", decoder->props.chunk_size); printf("version: %s\n", decoder->props.version); printf("magic: %s\n", decoder->props.magic); printf("endianness: %s\n", decoder->props.endianness); } void write_properties(CDRDecoder *decoder, const char *output_path) { // Basic RIFF stub uint8_t header[12] = {0x52,0x49,0x46,0x46, 0x0C,0x00,0x00,0x00, 0x43,0x44,0x52,0x35}; uint8_t chunk[12] = {0x4C,0x49,0x53,0x54, 0x04,0x00,0x00,0x00, 0x50,0x41,0x47,0x45}; FILE *out = fopen(output_path, "wb"); if (out) { fwrite(header, 1, 12, out); fwrite(chunk, 1, 12, out); fclose(out); printf("Written basic .CDR stub to %s\n", output_path); } } int main(int argc, char **argv) { if (argc < 2) return 1; CDRDecoder decoder = {0}; decoder.file = fopen(argv[1], "rb"); if (!decoder.file) return 1; fseek(decoder.file, 0, SEEK_END); decoder.size = ftell(decoder.file); fseek(decoder.file, 0, SEEK_SET); decoder.data = malloc(decoder.size); fread(decoder.data, 1, decoder.size, decoder.file); fclose(decoder.file); read_properties(&decoder); write_properties(&decoder, "output.cdr"); free(decoder.data); return 0; } // ===== end task-081 .CDR ===== // ===== task-083 .CDXML [C++] ===== #include #include #include typedef struct { char* content; size_t size; } CDXMLFile; typedef struct { char tag[256]; char attrs[1024]; // Simple key=value pairs as string } Property; typedef struct Node { Property prop; struct Node* children; int childCount; struct Node* next; // For siblings } Node; class CDXMLHandler { // Simulated as functions; C doesn't have classes public: CDXMLFile file; void init(char* filePath) { FILE* f = fopen(filePath, "r"); if (!f) return; fseek(f, 0, SEEK_END); file.size = ftell(f); fseek(f, 0, SEEK_SET); file.content = malloc(file.size + 1); fread(file.content, 1, file.size, f); file.content[file.size] = '\0'; fclose(f); } void read() { // Content loaded in init } void write(char* outputPath) { FILE* out = fopen(outputPath, "w"); if (out) { fwrite(file.content, 1, file.size, out); fclose(out); } } void printProperties() { Node* root = parseXML(file.content); traverseAndPrint(root); freeTree(root); } // Simple parser: scans for and recurses Node* parseXML(char* xml) { Node* node = malloc(sizeof(Node)); node->children = NULL; node->childCount = 0; node->next = NULL; // Basic scan: find , extract tag and attrs char* start = strstr(xml, "<"); if (start) { char* endTag = strchr(start + 1, '>'); if (endTag) { int len = endTag - start - 1; strncpy(node->prop.tag, start + 1, len); node->prop.tag[len] = '\0'; // Extract attrs roughly (space-separated key="val") strncpy(node->prop.attrs, start + strlen(node->prop.tag) + 1, endTag - start - strlen(node->prop.tag) - 2); node->prop.attrs[strlen(node->prop.attrs)] = '\0'; } } // Recurse for children (simplified, skips text/CDATA) char* childStart = strstr(endTag + 1, "<"); while (childStart && strncmp(childStart, "children) parent->children = child; else { Node* last = parent->children; while (last->next) last = last->next; last->next = child; } parent->childCount++; } void traverseAndPrint(Node* node) { if (!node) return; printf("%s: %s\n", node->prop.tag, node->prop.attrs); Node* child = node->children; while (child) { traverseAndPrint(child); child = child->next; } } void freeTree(Node* node) { if (!node) return; Node* child = node->children; while (child) { Node* next = child->next; freeTree(child); free(child); child = next; } free(node); } }; // Usage (compile with gcc -o handler handler.c): // CDXMLHandler h; // h.init("example.cdxml"); // h.printProperties(); // h.write("output.cdxml"); // Note: This is a basic implementation; for production, use libxml2. // ===== end task-083 .CDXML ===== // ===== task-084 .CER [C++] ===== #include #include #include #include #include class CerHandler { private: std::string filePath; X509* cert; public: CerHandler(const std::string& path) : filePath(path), cert(nullptr) {} ~CerHandler() { if (cert) X509_free(cert); } void read() { BIO* bio = BIO_new_file(filePath.c_str(), "rb"); if (!bio) throw std::runtime_error("Failed to open file"); cert = d2i_X509_bio(bio, nullptr); BIO_free(bio); if (!cert) throw std::runtime_error("Failed to load certificate"); } void printProperties() { if (!cert) read(); char buffer[1024]; std::cout << "Version: " << X509_get_version(cert) + 1 << std::endl; const ASN1_INTEGER* serial = X509_get0_serialNumber(cert); std::cout << "Serial Number: " << ASN1_INTEGER_get(serial) << std::endl; X509_signature_print(nullptr, X509_get0_signature_algorithm(cert), nullptr); X509_NAME_oneline(X509_get_issuer_name(cert), buffer, sizeof(buffer)); std::cout << "Issuer: " << buffer << std::endl; ASN1_TIME_print(nullptr, X509_get0_notBefore(cert)); std::cout << std::endl; ASN1_TIME_print(nullptr, X509_get0_notAfter(cert)); std::cout << std::endl; X509_NAME_oneline(X509_get_subject_name(cert), buffer, sizeof(buffer)); std::cout << "Subject: " << buffer << std::endl; std::cout << "Public Key Algorithm: " << OBJ_nid2sn(X509_get0_pubkey_algor(cert)->algorithm->nid) << std::endl; i2d_PUBKEY_bio(nullptr, X509_get_pubkey(cert)); std::cout << "Extensions:" << std::endl; int extCount = X509_get_ext_count(cert); for (int i = 0; i < extCount; ++i) { X509_EXTENSION* ext = X509_get_ext(cert, i); std::cout << " " << OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext))) << " (Critical: " << X509_EXTENSION_get_critical(ext) << ")" << std::endl; } } void write(const std::string& newFilePath) { if (!cert) read(); BIO* bio = BIO_new_file(newFilePath.c_str(), "wb"); if (!bio) throw std::runtime_error("Failed to open output file"); i2d_X509_bio(bio, cert); BIO_free(bio); } }; // Example usage: // int main() { // try { // CerHandler handler("example.cer"); // handler.printProperties(); // handler.write("copy.cer"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-084 .CER ===== // ===== task-085 .CGM [C++] ===== #include #include #include #include #include class CGMParser { private: std::vector data; size_t pos = 0; std::map properties; unsigned short readUint16() { unsigned short val = (data[pos] << 8) | data[pos + 1]; pos += 2; return val; } short readInt16() { unsigned short uval = readUint16(); return static_cast(uval); } std::string readString(size_t len) { std::string s(data.begin() + pos, data.begin() + pos + len); pos += len; return s; } void parse() { while (pos < data.size()) { unsigned short word = readUint16(); int classId = (word >> 12) & 0xF; int elemId = (word >> 5) & 0x7F; int paramLen = word & 0x1F; if (paramLen == 0x1F) { paramLen = readUint16(); } size_t startPos = pos; if (classId == 0 && elemId == 1) { // BEGIN METAFILE // Skip } else if (classId == 1) { if (elemId == 1) { // METAFILE VERSION properties["Metafile Version"] = std::to_string(readInt16()); } else if (elemId == 2) { // METAFILE DESCRIPTION properties["Metafile Description"] = readString(paramLen); } else if (elemId == 3) { // VDC TYPE properties["VDC Type"] = readInt16() == 0 ? "Integer" : "Real"; } else if (elemId == 4) { // INTEGER PRECISION properties["Integer Precision"] = "Min: " + std::to_string(readInt16()) + ", Max: " + std::to_string(readInt16()); } else if (elemId == 5) { // REAL PRECISION properties["Real Precision"] = "Mantissa: " + std::to_string(readInt16()) + ", Exponent: " + std::to_string(readInt16()); } // Extend for others } pos = startPos + paramLen; if (paramLen % 2 == 1) pos += 1; // Padding if (classId == 0 && elemId == 3) break; // BEGIN PICTURE } } public: CGMParser(const std::string& filename) { std::ifstream file(filename, std::ios::binary); data = std::vector(std::istreambuf_iterator(file), {}); parse(); } void printProperties() const { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& outputFilename) const { std::ofstream file(outputFilename, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); } }; // Example: CGMParser parser("sample.cgm"); parser.printProperties(); parser.write("output.cgm"); // ===== end task-085 .CGM ===== // ===== task-086 .CHM [C++] ===== #include #include #include #include #include #include class CHMParser { private: std::string filepath; std::vector data; std::map properties; std::string toHex(uint64_t value) { std::stringstream ss; ss << std::hex << std::setw(16) << std::setfill('0') << value; return ss.str(); } std::string getGUID(size_t offset) { std::stringstream ss; for (size_t i = 0; i < 4; ++i) ss << std::hex << std::setw(2) << std::setfill('0') << (int)data[offset + i]; ss << "-"; for (size_t i = 4; i < 6; ++i) ss << std::hex << std::setw(2) << std::setfill('0') << (int)data[offset + i]; ss << "-"; for (size_t i = 6; i < 8; ++i) ss << std::hex << std::setw(2) << std::setfill('0') << (int)data[offset + i]; ss << "-"; for (size_t i = 8; i < 10; ++i) ss << std::hex << std::setw(2) << std::setfill('0') << (int)data[offset + i]; ss << "-"; for (size_t i = 10; i < 16; ++i) ss << std::hex << std::setw(2) << std::setfill('0') << (int)data[offset + i]; return ss.str(); } public: CHMParser(const std::string& fp) : filepath(fp) { std::ifstream file(filepath, std::ios::binary | std::ios::ate); std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(reinterpret_cast(data.data()), size); readProperties(); } void readProperties() { char sig[5] = {0}; memcpy(sig, data.data(), 4); properties["Signature"] = sig; uint32_t version; memcpy(&version, data.data() + 4, 4); properties["Version"] = std::to_string(version); uint32_t headerLen; memcpy(&headerLen, data.data() + 8, 4); properties["Total Header Length"] = std::to_string(headerLen); uint32_t unknown1; memcpy(&unknown1, data.data() + 12, 4); properties["Unknown1"] = std::to_string(unknown1); uint32_t timestamp; memcpy(×tamp, data.data() + 16, 4); // big-endian, but for string no swap properties["Timestamp"] = std::to_string(__builtin_bswap32(timestamp)); uint32_t langId; memcpy(&langId, data.data() + 20, 4); properties["Language ID"] = std::to_string(langId); properties["GUID1"] = getGUID(24); properties["GUID2"] = getGUID(40); size_t sectionTableOffset = 0x38; uint64_t sec0Off; memcpy(&sec0Off, data.data() + sectionTableOffset, 8); properties["Section 0 Offset"] = std::to_string(sec0Off); uint64_t sec0Len; memcpy(&sec0Len, data.data() + sectionTableOffset + 8, 8); properties["Section 0 Length"] = std::to_string(sec0Len); uint64_t sec1Off; memcpy(&sec1Off, data.data() + sectionTableOffset + 16, 8); properties["Section 1 Offset"] = std::to_string(sec1Off); uint64_t sec1Len; memcpy(&sec1Len, data.data() + sectionTableOffset + 24, 8); properties["Section 1 Length"] = std::to_string(sec1Len); uint64_t contentOff; memcpy(&contentOff, data.data() + sectionTableOffset + 32, 8); properties["Content Section 0 Offset"] = std::to_string(contentOff); size_t s0 = sec0Off; uint32_t s0u1; memcpy(&s0u1, data.data() + s0, 4); properties["Section0 Unknown1"] = std::to_string(s0u1); uint32_t s0u2; memcpy(&s0u2, data.data() + s0 + 4, 4); properties["Section0 Unknown2"] = std::to_string(s0u2); uint64_t fileSize; memcpy(&fileSize, data.data() + s0 + 8, 8); properties["File Size"] = std::to_string(fileSize); uint32_t s0u3; memcpy(&s0u3, data.data() + s0 + 16, 4); properties["Section0 Unknown3"] = std::to_string(s0u3); uint32_t s0u4; memcpy(&s0u4, data.data() + s0 + 20, 4); properties["Section0 Unknown4"] = std::to_string(s0u4); size_t s1 = sec1Off; char dsig[5] = {0}; memcpy(dsig, data.data() + s1, 4); properties["Directory Signature"] = dsig; uint32_t dver; memcpy(&dver, data.data() + s1 + 4, 4); properties["Directory Version"] = std::to_string(dver); uint32_t dhlen; memcpy(&dhlen, data.data() + s1 + 8, 4); properties["Directory Header Length"] = std::to_string(dhlen); uint32_t du1; memcpy(&du1, data.data() + s1 + 12, 4); properties["Directory Unknown1"] = std::to_string(du1); uint32_t chsize; memcpy(&chsize, data.data() + s1 + 16, 4); properties["Directory Chunk Size"] = std::to_string(chsize); uint32_t qdens; memcpy(&qdens, data.data() + s1 + 20, 4); properties["Quickref Density"] = std::to_string(qdens); uint32_t idepth; memcpy(&idepth, data.data() + s1 + 24, 4); properties["Index Tree Depth"] = std::to_string(idepth); int32_t rootidx; memcpy(&rootidx, data.data() + s1 + 28, 4); properties["Root Index Chunk Number"] = std::to_string(rootidx); uint32_t firstlst; memcpy(&firstlst, data.data() + s1 + 32, 4); properties["First Listing Chunk Number"] = std::to_string(firstlst); uint32_t lastlst; memcpy(&lastlst, data.data() + s1 + 36, 4); properties["Last Listing Chunk Number"] = std::to_string(lastlst); int32_t du2; memcpy(&du2, data.data() + s1 + 40, 4); properties["Directory Unknown2"] = std::to_string(du2); uint32_t numchunks; memcpy(&numchunks, data.data() + s1 + 44, 4); properties["Number of Directory Chunks"] = std::to_string(numchunks); uint32_t dlang; memcpy(&dlang, data.data() + s1 + 48, 4); properties["Directory Language ID"] = std::to_string(dlang); properties["Directory GUID"] = getGUID(s1 + 52); } void printProperties() { for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } void writeModified(const std::string& outputPath, const std::map& modifications) { std::vector newData = data; for (const auto& mod : modifications) { // Example: Modify Language ID if (mod.first == "Language ID") { uint32_t value = std::stoul(mod.second); memcpy(newData.data() + 20, &value, 4); } // Implement other modifications } std::ofstream out(outputPath, std::ios::binary); out.write(reinterpret_cast(newData.data()), newData.size()); } }; // Usage example: // int main() { // CHMParser parser("example.chm"); // parser.printProperties(); // std::map mods = {{"Language ID", "1031"}}; // parser.writeModified("modified.chm", mods); // return 0; // } // ===== end task-086 .CHM ===== // ===== task-087 .CHO [C] ===== #include #include #include #define MAX_PROPERTIES 100 #define MAX_PROP_LENGTH 256 #define MAX_CONTENT 10000 typedef struct { char *filename; char content[MAX_CONTENT]; char properties[MAX_PROPERTIES][MAX_PROP_LENGTH]; int prop_count; } ChoFile; void cho_init(ChoFile *cho, const char *filename) { cho->filename = strdup(filename); cho->prop_count = 0; memset(cho->content, 0, MAX_CONTENT); memset(cho->properties, 0, sizeof(cho->properties)); } void cho_read(ChoFile *cho) { FILE *fp = fopen(cho->filename, "r"); if (fp) { fread(cho->content, 1, MAX_CONTENT - 1, fp); fclose(fp); } // Simple parsing for directives (basic, not full regex) char *ptr = cho->content; while ((ptr = strstr(ptr, "{")) != NULL) { char *end = strstr(ptr, "}"); if (end) { int len = end - ptr - 1; if (len > 0 && cho->prop_count < MAX_PROPERTIES) { strncpy(cho->properties[cho->prop_count], ptr + 1, len); cho->properties[cho->prop_count][len] = '\0'; cho->prop_count++; } ptr = end + 1; } else { break; } } } void cho_print_properties(ChoFile *cho) { for (int i = 0; i < cho->prop_count; i++) { printf("%s\n", cho->properties[i]); } } void cho_write(ChoFile *cho) { FILE *fp = fopen(cho->filename, "w"); if (fp) { fwrite(cho->content, 1, strlen(cho->content), fp); fclose(fp); } } void cho_add_property(ChoFile *cho, const char *directive) { strcat(cho->content, "{"); strcat(cho->content, directive); strcat(cho->content, "}\n"); if (cho->prop_count < MAX_PROPERTIES) { strcpy(cho->properties[cho->prop_count++], directive); } } void cho_free(ChoFile *cho) { free(cho->filename); } // Example usage: // int main() { // ChoFile cho; // cho_init(&cho, "example.cho"); // cho_read(&cho); // cho_print_properties(&cho); // cho_add_property(&cho, "new_directive: value"); // cho_write(&cho); // cho_free(&cho); // return 0; // } // ===== end task-087 .CHO ===== // ===== task-088 .CIA [C] ===== #include #include #include #include typedef struct { uint32_t header_size; uint16_t type; uint16_t version; uint32_t cert_size; uint32_t ticket_size; uint32_t tmd_size; uint32_t meta_size; uint64_t content_size; int content_flags_sample[64]; // Sample present indices int num_flags_sample; uint32_t ticket_sig_type; char title_key[33]; // Hex uint64_t ticket_id; uint64_t title_id; uint8_t common_key_index; uint32_t tmd_sig_type; uint64_t tmd_title_id; uint16_t content_count; uint32_t core_version; // If meta present } CIAProperties; typedef struct { FILE *file; uint8_t *data; size_t size; CIAProperties props; } CIAParser; void parse_header(CIAParser *parser) { uint8_t *buf = parser->data; size_t pos = 0; // Little-endian reads parser->props.header_size = *(uint32_t *)&buf[pos]; pos += 4; // LE assumed in unpack parser->props.type = *(uint16_t *)&buf[pos]; pos += 2; parser->props.version = *(uint16_t *)&buf[pos]; pos += 2; parser->props.cert_size = *(uint32_t *)&buf[pos]; pos += 4; parser->props.ticket_size = *(uint32_t *)&buf[pos]; pos += 4; parser->props.tmd_size = *(uint32_t *)&buf[pos]; pos += 4; parser->props.meta_size = *(uint32_t *)&buf[pos]; pos += 4; parser->props.content_size = *(uint64_t *)&buf[pos]; pos += 8; // Content flags sample parser->props.num_flags_sample = 0; for (int i = 0; i < 64; i++) { if (buf[pos + i / 8] & (1 << (i % 8))) { parser->props.content_flags_sample[parser->props.num_flags_sample++] = i; } } pos += 0x2000; // Skip to ticket pos = 0x2020 + parser->props.cert_size; // Ticket (big-endian approx; manual unpack) uint32_t ticket_sig_type = (buf[pos] << 24) | (buf[pos+1] << 16) | (buf[pos+2] << 8) | buf[pos+3]; parser->props.ticket_sig_type = ticket_sig_type; size_t title_key_start = pos + 0x104 + 0x7C; for (int i = 0; i < 16; i++) { sprintf(parser->props.title_key + i*2, "%02x", buf[title_key_start + i]); } size_t ticket_id_start = title_key_start + 0x10 + 0x1F; parser->props.ticket_id = (uint64_t)buf[ticket_id_start] << 56 | (uint64_t)buf[ticket_id_start+1] << 48 | /* ... full BE unpack */; // Simplified; assume LE for id, adjust as needed parser->props.ticket_id = *(uint64_t *)&buf[ticket_id_start]; // Placeholder size_t title_id_start = pos + 0x104 + 0xA4 + 0x44; parser->props.title_id = *(uint64_t *)&buf[title_id_start]; parser->props.common_key_index = buf[pos + 0xB1]; // TMD similar pos += parser->props.ticket_size; uint32_t tmd_sig_type = (buf[pos] << 24) | (buf[pos+1] << 16) | (buf[pos+2] << 8) | buf[pos+3]; parser->props.tmd_sig_type = tmd_sig_type; size_t tmd_title_id_start = pos + 0x104 + 0xC; parser->props.tmd_title_id = *(uint64_t *)&buf[tmd_title_id_start]; size_t content_count_start = tmd_title_id_start + 0x9E - 0xC; parser->props.content_count = *(uint16_t *)&buf[content_count_start]; // Meta size_t meta_pos = pos + parser->props.tmd_size + parser->props.content_size; if (parser->props.meta_size > 0) { parser->props.core_version = *(uint32_t *)&buf[meta_pos + 0x300]; } } void print_properties(CIAProperties *props) { printf("CIA Properties:\n"); printf("header_size: %u\n", props->header_size); printf("type: %u\n", props->type); // ... print all fields similarly printf("content_flags_sample: "); for (int i = 0; i < props->num_flags_sample; i++) printf("%d ", props->content_flags_sample[i]); printf("\n"); // Add prints for all } CIAParser *load_cia(const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); CIAParser *parser = malloc(sizeof(CIAParser)); parser->file = NULL; parser->data = data; parser->size = size; parse_header(parser); print_properties(&parser->props); return parser; } void write_cia(CIAParser *parser, const char *output) { FILE *f = fopen(output, "wb"); if (f) { fwrite(parser->data, 1, parser->size, f); // Copy; full rebuild packs fclose(f); printf("Written to %s\n", output); } } int main(int argc, char **argv) { if (argc > 1) { CIAParser *p = load_cia(argv[1]); if (p) { write_cia(p, "output.cia"); free(p->data); free(p); } } return 0; } // ===== end task-088 .CIA ===== // ===== task-089 .CIF [C] ===== #include #include #include #include // For regex, or implement simple matching // Structs for properties typedef struct { int line; char* content; } Comment; typedef struct { char* name; int line; // Items: simple map simulation with arrays char** tags; char** values; int item_count; // Loops and frames simplified as counts for demo int loop_count; int save_frame_count; } Block; typedef struct { Block* data_blocks; int block_count; Comment* comments; int comment_count; char** errors; int error_count; } CIFProperties; // Function prototypes CIFProperties* read_cif(const char* filename); void print_properties(CIFProperties* props); void write_cif(CIFProperties* props, const char* output_filename); void free_properties(CIFProperties* props); char* value_to_str(const char* val_type, const char* val); // Simplistic int main(int argc, char* argv[]) { if (argc < 2) { printf("Usage: %s [output.cif]\n", argv[0]); return 1; } CIFProperties* props = read_cif(argv[1]); print_properties(props); if (argc > 2) { write_cif(props, argv[2]); } free_properties(props); return 0; } CIFProperties* read_cif(const char* filename) { CIFProperties* props = malloc(sizeof(CIFProperties)); props->block_count = 0; props->comment_count = 0; props->error_count = 0; props->data_blocks = NULL; props->comments = NULL; props->errors = NULL; FILE* file = fopen(filename, "r"); if (!file) { char* err = malloc(100); snprintf(err, 100, "File not found: %s", filename); props->errors = realloc(props->errors, sizeof(char*) * (props->error_count + 1)); props->errors[props->error_count++] = err; return props; } Block* current_block = NULL; int max_blocks = 10; // Arbitrary max props->data_blocks = malloc(sizeof(Block) * max_blocks); char line[1024]; int line_num = 0; int in_loop = 0; while (fgets(line, sizeof(line), file)) { line_num++; char* stripped = line; while (*stripped == ' ' || *stripped == '\t') stripped++; // Trim left char* end = stripped + strlen(stripped) - 1; while (end > stripped && (*end == ' ' || *end == '\t' || *end == '\n')) *end-- = '\0'; if (stripped[0] == '#') { props->comments = realloc(props->comments, sizeof(Comment) * (props->comment_count + 1)); props->comments[props->comment_count].line = line_num; props->comments[props->comment_count].content = strdup(stripped); props->comment_count++; continue; } // Simple string match for data_ if (strncmp(stripped, "data_", 5) == 0 && strlen(stripped) > 5 && stripped[5] != ' ') { if (current_block) { props->data_blocks[props->block_count++] = *current_block; if (props->block_count >= max_blocks) max_blocks *= 2, props->data_blocks = realloc(props->data_blocks, sizeof(Block) * max_blocks); } current_block = malloc(sizeof(Block)); current_block->name = strdup(stripped + 5); current_block->line = line_num; current_block->item_count = 0; current_block->tags = malloc(sizeof(char*) * 10); // Max items current_block->values = malloc(sizeof(char*) * 10); current_block->loop_count = 0; current_block->save_frame_count = 0; in_loop = 0; continue; } // Similar simplistic matches for save_, loop_, items // For items: check if starts with _ and has space if (stripped[0] == '_' && strchr(stripped, ' ')) { char* space_pos = strchr(stripped, ' '); *space_pos = '\0'; char* tag = strdup(stripped); char* val = strdup(space_pos + 1); current_block->tags[current_block->item_count] = tag; current_block->values[current_block->item_count] = val; current_block->item_count++; continue; } // Loop simplistic: count 'loop_' occurrences if (strcasestr(stripped, "loop_")) { current_block->loop_count++; in_loop = 1; continue; } // Comments/errors etc. } if (current_block) { props->data_blocks[props->block_count++] = *current_block; free(current_block); } fclose(file); return props; } void print_properties(CIFProperties* props) { printf("CIF Properties:\n"); printf("Data Blocks: %d\n", props->block_count); for (int i = 0; i < props->block_count; i++) { printf(" Block %s: %d items, %d loops\n", props->data_blocks[i].name, props->data_blocks[i].item_count, props->data_blocks[i].loop_count); } printf("Comments: %d\n", props->comment_count); for (int i = 0; i < props->error_count; i++) { printf("Error: %s\n", props->errors[i]); } // Full dump would print all } void write_cif(CIFProperties* props, const char* output_filename) { FILE* out = fopen(output_filename, "w"); if (!out) return; fprintf(out, "# Generated CIF\n"); for (int i = 0; i < props->block_count; i++) { Block b = props->data_blocks[i]; fprintf(out, "data_%s\n", b.name); for (int j = 0; j < b.item_count; j++) { fprintf(out, "_%s %s\n", b.tags[j], value_to_str("string", b.values[j])); // Simplistic } // Loops/frames... } fclose(out); printf("Written to %s\n", output_filename); } char* value_to_str(const char* val_type, const char* val) { if (strcmp(val_type, "n/a") == 0) return "."; if (strcmp(val_type, "unknown") == 0) return "?"; char* quoted = malloc(strlen(val) + 3); snprintf(quoted, strlen(val) + 3, "\"%s\"", val); return quoted; } void free_properties(CIFProperties* props) { for (int i = 0; i < props->block_count; i++) { Block b = props->data_blocks[i]; for (int j = 0; j < b.item_count; j++) { free(b.tags[j]); free(b.values[j]); } free(b.tags); free(b.values); free(b.name); } free(props->data_blocks); for (int i = 0; i < props->comment_count; i++) free(props->comments[i].content); free(props->comments); for (int i = 0; i < props->error_count; i++) free(props->errors[i]); free(props->errors); free(props); } // ===== end task-089 .CIF ===== // ===== task-090 .CLASS [C++] ===== #include #include #include #include typedef struct { uint8_t *data; size_t offset; size_t size; int *constant_pool_tags; // Simplified: only tags for demo char **constant_strings; // Approx strings int cp_count; } ClassFileParser; uint8_t u1(ClassFileParser *p) { if (p->offset >= p->size) return 0; return p->data[p->offset++]; } uint16_t u2(ClassFileParser *p) { uint16_t val = (p->data[p->offset] << 8) | p->data[p->offset + 1]; p->offset += 2; return val; } uint32_t u4(ClassFileParser *p) { uint32_t val = (p->data[p->offset] << 24) | (p->data[p->offset + 1] << 16) | (p->data[p->offset + 2] << 8) | p->data[p->offset + 3]; p->offset += 4; return val; } void read_magic(ClassFileParser *p) { uint32_t magic = u4(p); if (magic != 0xCAFEBABE) { fprintf(stderr, "Invalid magic\n"); exit(1); } printf("magic: 0x%08X\n", magic); } void read_versions(ClassFileParser *p) { uint16_t minor = u2(p); uint16_t major = u2(p); printf("versions: minor=%d, major=%d\n", minor, major); } int read_constant_pool_count(ClassFileParser *p) { return u2(p); } void read_constant_pool(ClassFileParser *p, int count) { p->cp_count = count; p->constant_pool_tags = malloc((count - 1) * sizeof(int)); p->constant_strings = malloc((count - 1) * sizeof(char*)); for (int i = 0; i < count - 1; i++) { int tag = u1(p); p->constant_pool_tags[i] = tag; p->constant_strings[i] = NULL; if (tag == 1) { // Utf8 approx int len = u2(p); p->constant_strings[i] = malloc(len + 1); memcpy(p->constant_strings[i], &p->data[p->offset], len); p->constant_strings[i][len] = '\0'; p->offset += len; } else if (tag == 3 || tag == 4) { u4(p); } else if (tag == 5 || tag == 6) { u4(p); u4(p); i++; // Skip } else { u2(p); // Approx skip } } } char* get_constant_string(ClassFileParser *p, int index) { if (index == 0) return "none"; if (index - 1 >= p->cp_count - 1 || !p->constant_strings[index - 1]) { char buf[32]; sprintf(buf, "CONSTANT[%d]", index); return strdup(buf); } return strdup(p->constant_strings[index - 1]); } void read_access_flags(ClassFileParser *p) { uint16_t flags = u2(p); printf("access_flags: 0x%04X\n", flags); } void read_this_class(ClassFileParser *p) { int idx = u2(p); printf("this_class: %s\n", get_constant_string(p, idx)); } void read_super_class(ClassFileParser *p) { int idx = u2(p); printf("super_class: %s\n", get_constant_string(p, idx)); } void read_interfaces(ClassFileParser *p) { int count = u2(p); printf("interfaces_count: %d\n", count); for (int i = 0; i < count; i++) { int idx = u2(p); printf(" interface: %s\n", get_constant_string(p, idx)); } } void read_fields(ClassFileParser *p) { int count = u2(p); printf("fields_count: %d\n", count); for (int i = 0; i < count; i++) { uint16_t acc = u2(p); int name_idx = u2(p); int desc_idx = u2(p); u2(p); // attributes_count, skip printf(" field: access=0x%04X, name=%s, descriptor=%s\n", acc, get_constant_string(p, name_idx), get_constant_string(p, desc_idx)); // Skip attributes } } void read_methods(ClassFileParser *p) { int count = u2(p); printf("methods_count: %d\n", count); for (int i = 0; i < count; i++) { uint16_t acc = u2(p); int name_idx = u2(p); int desc_idx = u2(p); u2(p); // attributes_count, skip printf(" method: access=0x%04X, name=%s, descriptor=%s\n", acc, get_constant_string(p, name_idx), get_constant_string(p, desc_idx)); // Skip attributes } } void read_attributes_count(ClassFileParser *p) { int count = u2(p); printf("attributes_count: %d\n", count); // Skip } void parse(ClassFileParser *p) { read_magic(p); read_versions(p); int cp_count = read_constant_pool_count(p); read_constant_pool(p, cp_count); read_access_flags(p); read_this_class(p); read_super_class(p); read_interfaces(p); read_fields(p); read_methods(p); read_attributes_count(p); } void write(ClassFileParser *p, const char *filename) { FILE *f = fopen(filename, "wb"); if (f) { fwrite(p->data, 1, p->size, f); fclose(f); } } void free_parser(ClassFileParser *p) { if (p->data) free(p->data); if (p->constant_pool_tags) free(p->constant_pool_tags); if (p->constant_strings) { for (int i = 0; i < p->cp_count - 1; i++) { if (p->constant_strings[i]) free(p->constant_strings[i]); } free(p->constant_strings); } free(p); } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: ./parser \n"); return 1; } FILE *f = fopen(argv[1], "rb"); if (!f) { perror("Open file"); return 1; } fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); ClassFileParser p = { .data = data, .offset = 0, .size = size }; parse(&p); // write(&p, "output.class"); free_parser(&p); return 0; } // ===== end task-090 .CLASS ===== // ===== task-091 .CLS [C] ===== #include #include #include #define MAX_LINE 1024 #define MAX_CLASSES 100 #define MAX_SAMPLES 10000 typedef struct { char filename[256]; char file_type[32]; int num_samples; int num_classes; char class_names[MAX_CLASSES][256]; int num_class_names; int phenotype_labels[MAX_SAMPLES]; int num_labels; } CLSProperties; void init_properties(CLSProperties *props) { strcpy(props->file_type, ""); props->num_samples = 0; props->num_classes = 0; props->num_class_names = 0; props->num_labels = 0; strcpy(props->filename, ""); } int parse_file(const char *filename, CLSProperties *props) { FILE *file = fopen(filename, "r"); if (!file) { perror("File not found"); return 0; } char line[MAX_LINE]; char *lines[3]; int line_count = 0; // Read first three lines while (line_count < 3 && fgets(line, sizeof(line), file)) { line[strcspn(line, "\n")] = 0; // Remove newline if (strlen(line) > 0) { lines[line_count] = strdup(line); line_count++; } } fclose(file); if (line_count < 3) { fprintf(stderr, "Invalid CLS file: insufficient lines.\n"); return 0; } // Parse first line int parts[3]; if (sscanf(lines[0], "%d %d %d", &parts[0], &parts[1], &parts[2]) != 3 || parts[2] != 1) { strcpy(props->file_type, "continuous or invalid"); strcpy(props->filename, filename); return 1; // Partial success } strcpy(props->file_type, "categorical"); props->num_samples = parts[0]; props->num_classes = parts[1]; // Parse second line if (strncmp(lines[1], "# ", 2) != 0) { fprintf(stderr, "Invalid second line.\n"); return 0; } char *name_start = lines[1] + 2; props->num_class_names = 0; char *token = strtok(name_start, " \t"); while (token && props->num_class_names < MAX_CLASSES) { strncpy(props->class_names[props->num_class_names], token, 255); props->class_names[props->num_class_names][255] = 0; props->num_class_names++; token = strtok(NULL, " \t"); } // Parse third line props->num_labels = 0; char *label_start = lines[1]; // Reuse for simplicity; in full impl, read properly token = strtok(lines[2], " \t"); while (token && props->num_labels < MAX_SAMPLES) { props->phenotype_labels[props->num_labels] = atoi(token); props->num_labels++; token = strtok(NULL, " \t"); } if (props->num_labels != props->num_samples || props->num_class_names != props->num_classes) { fprintf(stderr, "Mismatch in counts.\n"); return 0; } strcpy(props->filename, filename); return 1; } void print_properties(const CLSProperties *props) { printf("File Type: %s\n", props->file_type); if (strcmp(props->file_type, "categorical") == 0) { printf("Number of Samples: %d\n", props->num_samples); printf("Number of Classes: %d\n", props->num_classes); printf("Class Names: "); for (int i = 0; i < props->num_class_names; i++) { printf("%s", props->class_names[i]); if (i < props->num_class_names - 1) printf(", "); } printf("\n"); printf("Phenotype Labels: ["); for (int i = 0; i < props->num_labels; i++) { printf("%d", props->phenotype_labels[i]); if (i < props->num_labels - 1) printf(", "); } printf("]\n"); } else { printf("Note: Continuous format detected.\n"); } } int write_file(const char *filename, const CLSProperties *props) { if (strcmp(props->file_type, "categorical") != 0) { fprintf(stderr, "Write supports categorical only.\n"); return 0; } FILE *file = fopen(filename, "w"); if (!file) { perror("Write failed"); return 0; } fprintf(file, "%d %d 1\n", props->num_samples, props->num_classes); fprintf(file, "# "); for (int i = 0; i < props->num_class_names; i++) { fprintf(file, "%s", props->class_names[i]); if (i < props->num_class_names - 1) fprintf(file, " "); } fprintf(file, "\n"); for (int i = 0; i < props->num_labels; i++) { fprintf(file, "%d", props->phenotype_labels[i]); if (i < props->num_labels - 1) fprintf(file, " "); } fprintf(file, "\n"); fclose(file); return 1; } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } CLSProperties props; init_properties(&props); if (!parse_file(argv[1], &props)) { fprintf(stderr, "Parse failed.\n"); return 1; } print_properties(&props); // Example write to output.cls write_file("output.cls", &props); return 0; } // ===== end task-091 .CLS ===== // ===== task-092 .CMD [C] ===== #include #include #include #include #define HEADER_SIZE 128 #define NUM_GROUPS 8 #define GROUP_DESC_SIZE 9 #define PARAGRAPH_SIZE 16 typedef struct { uint8_t type; uint16_t length; // in paragraphs uint16_t base_addr; uint16_t min_size; uint16_t max_size; } GroupDesc; typedef struct { GroupDesc groups[NUM_GROUPS]; uint16_t rsx_index; uint16_t fixups_offset; uint8_t flags; uint8_t first_type; size_t file_size; uint8_t* header; uint8_t** group_data; } CMDProperties; const char* get_type_name(uint8_t type) { switch (type) { case 1: return "Code"; case 2: return "Data"; case 3: return "Extra Data"; case 4: return "Stack"; case 5: return "Aux1"; case 6: return "Aux2"; case 7: return "Aux3"; case 8: return "Aux4"; case 9: return "Shared Code"; default: return "Unknown/Unused"; } } void parse_flags(uint8_t flags, char* details, size_t buf_size) { details[0] = '\0'; char* ptr = details; size_t len = 0; if (flags & 0x80) { len = snprintf(ptr, buf_size - len, "Perform fixups; "); ptr += len; } if (flags & 0x40) { len = snprintf(ptr, buf_size - len, "Allocate imaginary 8087; "); ptr += len; } if (flags & 0x20) { len = snprintf(ptr, buf_size - len, "Allocate 8087 if present; "); ptr += len; } if (flags & 0x10) { len = snprintf(ptr, buf_size - len, "This is an RSX; "); ptr += len; } if (details[0] == '\0') strcpy(details, "None"); } void print_properties(CMDProperties* props) { printf("=== .CMD File Properties ===\n"); printf("File Size: %zu bytes\n", props->file_size); printf("Header Size: 128 bytes\n\n"); printf("Group Descriptors:\n"); for (int i = 0; i < NUM_GROUPS; i++) { GroupDesc* g = &props->groups[i]; printf(" Group %d: Type=%u (%s), Length=%u bytes, Base=%u paragraphs, Min=%u paragraphs, Max=%u paragraphs\n", i + 1, g->type, get_type_name(g->type), g->length * PARAGRAPH_SIZE, g->base_addr, g->min_size, g->max_size); } printf("\nRSX Index Record Offset: %u (128-byte records)\n", props->rsx_index); printf("Fixups Record Offset: %u (128-byte records)\n", props->fixups_offset); char flags_details[256]; parse_flags(props->flags, flags_details, sizeof(flags_details)); printf("\nFlags (0x%02X): %s\n", props->flags, flags_details); printf("\nValidation: First byte (type) = %u (valid if 1-9)\n", props->first_type); } CMDProperties* read_cmd(const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) { perror("Error opening file"); return NULL; } fseek(f, 0, SEEK_END); size_t file_size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(file_size); fread(data, 1, file_size, f); fclose(f); if (file_size < HEADER_SIZE) { free(data); fprintf(stderr, "Invalid .CMD file: too small.\n"); return NULL; } CMDProperties* props = malloc(sizeof(CMDProperties)); props->header = malloc(HEADER_SIZE); memcpy(props->header, data, HEADER_SIZE); props->group_data = malloc(NUM_GROUPS * sizeof(uint8_t*)); uint8_t* header_view = props->header; size_t offset = HEADER_SIZE; for (int i = 0; i < NUM_GROUPS; i++) { size_t base = i * GROUP_DESC_SIZE; props->groups[i].type = header_view[base]; props->groups[i].length = *(uint16_t*)(header_view + base + 1); // Assume little-endian props->groups[i].base_addr = *(uint16_t*)(header_view + base + 3); props->groups[i].min_size = *(uint16_t*)(header_view + base + 5); props->groups[i].max_size = *(uint16_t*)(header_view + base + 7); size_t group_size = props->groups[i].length * PARAGRAPH_SIZE; if (offset + group_size > file_size) group_size = file_size - offset; props->group_data[i] = malloc(group_size); memcpy(props->group_data[i], data + offset, group_size); offset += group_size; } props->rsx_index = *(uint16_t*)(header_view + 123); props->fixups_offset = *(uint16_t*)(header_view + 125); props->flags = header_view[127]; props->first_type = header_view[0]; props->file_size = file_size; free(data); print_properties(props); return props; } void write_cmd(CMDProperties* props, const char* output_filename) { FILE* f = fopen(output_filename, "wb"); if (!f) { perror("Error writing file"); return; } fwrite(props->header, 1, HEADER_SIZE, f); for (int i = 0; i < NUM_GROUPS; i++) { if (props->group_data[i]) { fwrite(props->group_data[i], 1, props->groups[i].length * PARAGRAPH_SIZE, f); // Simplified } } fclose(f); printf("Wrote reconstructed .CMD to %s\n", output_filename); } void free_props(CMDProperties* props) { free(props->header); for (int i = 0; i < NUM_GROUPS; i++) { free(props->group_data[i]); } free(props->group_data); free(props); } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } CMDProperties* props = read_cmd(argv[1]); if (props) { write_cmd(props, "output.cmd"); free_props(props); } return 0; } // ===== end task-092 .CMD ===== // ===== task-093 .CML [C] ===== #include #include #include #include "cJSON.h" // Assume cJSON.h and lib is available typedef struct { char* file_path; cJSON* data; } CMLHandler; CMLHandler* cml_handler_new(const char* file_path) { CMLHandler* handler = malloc(sizeof(CMLHandler)); handler->file_path = strdup(file_path); handler->data = NULL; return handler; } void cml_handler_free(CMLHandler* handler) { if (handler) { free(handler->file_path); if (handler->data) cJSON_Delete(handler->data); free(handler); } } void print_properties(cJSON* obj, const char* path) { if (!obj) return; if (cJSON_IsObject(obj)) { cJSON* item = NULL; cJSON_ArrayForEach(item, obj) { char* full_path = malloc(strlen(path) + strlen(item->string) + 2); sprintf(full_path, "%s.%s", path, item->string); if (strcmp(path, "root") == 0) { strcpy(full_path, item->string); } printf("%s: %s\n", full_path, cJSON_GetTypeName(item)); if (cJSON_IsObject(item) || cJSON_IsArray(item)) { print_properties(item, full_path); } free(full_path); } } else if (cJSON_IsArray(obj)) { int i = 0; cJSON* item = NULL; cJSON_ArrayForEach(item, obj) { char full_path[1024]; sprintf(full_path, "%s[%d]", path, i++); printf("%s: %s\n", full_path, cJSON_GetTypeName(item)); if (cJSON_IsObject(item) || cJSON_IsArray(item)) { print_properties(item, full_path); } } } else { printf("%s: %s (%s)\n", path, cJSON_PrintUnformatted(obj), cJSON_GetTypeName(obj)); } } int read_and_decode(CMLHandler* handler) { FILE* f = fopen(handler->file_path, "r"); if (!f) { fprintf(stderr, "File not found: %s\n", handler->file_path); return -1; } fseek(f, 0, SEEK_END); long len = ftell(f); fseek(f, 0, SEEK_SET); char* content = malloc(len + 1); fread(content, 1, len, f); content[len] = '\0'; fclose(f); handler->data = cJSON_Parse(content); free(content); if (!handler->data) { fprintf(stderr, "Error decoding CML\n"); return -1; } print_properties(handler->data, "root"); return 0; } void write(CMLHandler* handler, const char* output_path) { if (!handler->data) { fprintf(stderr, "No data loaded\n"); return; } char* json_str = cJSON_Print(handler->data); FILE* f = fopen(output_path, "w"); if (f) { fputs(json_str, f); fclose(f); printf("Wrote to %s\n", output_path); } else { fprintf(stderr, "Error writing\n"); } free(json_str); } int main(int argc, char** argv) { if (argc < 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } CMLHandler* handler = cml_handler_new(argv[1]); if (read_and_decode(handler) == 0) { write(handler, "output.cml"); } cml_handler_free(handler); return 0; } // ===== end task-093 .CML ===== // ===== task-094 .CMOD [C] ===== #include #include #include // Simple structs for properties typedef struct { char* key; void* value; // Can be float[3], float, char* } Property; typedef struct { Property* props; int count; } Material; typedef struct { char* semantic; char* format; } VertexDesc; typedef struct { char* type; int materialIndex; int indexCount; int* indices; } PrimGroup; typedef struct { VertexDesc* vertexDesc; int vertexDescCount; int verticesCount; PrimGroup* primGroups; int primGroupCount; } Mesh; typedef struct { Material* materials; int materialCount; Mesh* meshes; int meshCount; } CMODProperties; void initProperties(CMODProperties* props) { props->materials = NULL; props->materialCount = 0; props->meshes = NULL; props->meshCount = 0; } void freeProperties(CMODProperties* props) { // Free memory (omitted for brevity) } int isBinary(FILE* f) { char header[17]; fseek(f, 0, SEEK_SET); fread(header, 16, 1, f); header[16] = '\0'; if (strcmp(header, "#celmodel_binary") == 0) return 1; if (strcmp(header, "#celmodel__ascii") == 0) return 0; return -1; } void parseAscii(FILE* f, CMODProperties* props) { fseek(f, 0, SEEK_SET); char line[1024]; Material* currentMaterial = NULL; Mesh* currentMesh = NULL; int inMaterial = 0, inMesh = 0, inVertexDesc = 0; while (fgets(line, sizeof(line), f)) { char* trim = strtok(line, "\n "); if (trim == NULL || trim[0] == '#') continue; if (strcmp(trim, "material") == 0) { props->materials = realloc(props->materials, sizeof(Material) * (++props->materialCount)); currentMaterial = &props->materials[props->materialCount - 1]; currentMaterial->props = NULL; currentMaterial->count = 0; inMaterial = 1; } else if (strcmp(trim, "end_material") == 0) { inMaterial = 0; } else if (strcmp(trim, "mesh") == 0) { props->meshes = realloc(props->meshes, sizeof(Mesh) * (++props->meshCount)); currentMesh = &props->meshes[props->meshCount - 1]; currentMesh->vertexDesc = NULL; currentMesh->vertexDescCount = 0; currentMesh->verticesCount = 0; currentMesh->primGroups = NULL; currentMesh->primGroupCount = 0; inMesh = 1; } else if (strcmp(trim, "end_mesh") == 0) { inMesh = 0; } else if (strcmp(trim, "vertexdesc") == 0) { inVertexDesc = 1; } else if (strcmp(trim, "end_vertexdesc") == 0) { inVertexDesc = 0; } else if (strcmp(trim, "vertices") == 0) { currentMesh->verticesCount = atoi(strtok(NULL, " ")); } else if (strcmp(trim, "trilist") == 0 || strcmp(trim, "tristrip") == 0 || strcmp(trim, "trifan") == 0 || strcmp(trim, "linelist") == 0 || strcmp(trim, "linestrip") == 0 || strcmp(trim, "pointlist") == 0 || strcmp(trim, "spritelist") == 0) { PrimGroup group; group.type = strdup(trim); group.materialIndex = atoi(strtok(NULL, " ")); group.indexCount = atoi(strtok(NULL, " ")); group.indices = malloc(sizeof(int) * group.indexCount); for (int i = 0; i < group.indexCount; i++) { group.indices[i] = atoi(strtok(NULL, " ")); } currentMesh->primGroups = realloc(currentMesh->primGroups, sizeof(PrimGroup) * (++currentMesh->primGroupCount)); currentMesh->primGroups[currentMesh->primGroupCount - 1] = group; } else if (inMaterial) { // Parse property (omitted details) } else if (inVertexDesc) { VertexDesc desc; desc.semantic = strdup(trim); desc.format = strdup(strtok(NULL, " ")); currentMesh->vertexDesc = realloc(currentMesh->vertexDesc, sizeof(VertexDesc) * (++currentMesh->vertexDescCount)); currentMesh->vertexDesc[currentMesh->vertexDescCount - 1] = desc; } } } void parseBinary(FILE* f, CMODProperties* props) { fseek(f, 16, SEEK_SET); unsigned int materialCount; fread(&materialCount, sizeof(unsigned int), 1, f); props->materials = malloc(sizeof(Material) * materialCount); props->materialCount = materialCount; for (int i = 0; i < materialCount; i++) { Material* mat = &props->materials[i]; unsigned int blend; fread(&blend, sizeof(unsigned int), 1, f); // Similar for colors, floats, textures (length + chars) // Omitted for brevity } unsigned int meshCount; fread(&meshCount, sizeof(unsigned int), 1, f); props->meshes = malloc(sizeof(Mesh) * meshCount); props->meshCount = meshCount; for (int i = 0; i < meshCount; i++) { Mesh* mesh = &props->meshes[i]; unsigned int attrCount; fread(&attrCount, sizeof(unsigned int), 1, f); mesh->vertexDesc = malloc(sizeof(VertexDesc) * attrCount); mesh->vertexDescCount = attrCount; for (int j = 0; j < attrCount; j++) { unsigned int semantic, format; fread(&semantic, sizeof(unsigned int), 1, f); fread(&format, sizeof(unsigned int), 1, f); // Map to strings if needed } fread(&mesh->verticesCount, sizeof(unsigned int), 1, f); // Skip vertex data unsigned int groupCount; fread(&groupCount, sizeof(unsigned int), 1, f); mesh->primGroups = malloc(sizeof(PrimGroup) * groupCount); mesh->primGroupCount = groupCount; for (int j = 0; j < groupCount; j++) { PrimGroup* group = &mesh->primGroups[j]; unsigned int type; fread(&type, sizeof(unsigned int), 1, f); fread(&group->materialIndex, sizeof(unsigned int), 1, f); fread(&group->indexCount, sizeof(unsigned int), 1, f); group->indices = malloc(sizeof(int) * group->indexCount); for (int k = 0; k < group->indexCount; k++) { fread(&group->indices[k], sizeof(unsigned int), 1, f); } } } } void printProperties(const CMODProperties* props) { printf("Materials: %d\n", props->materialCount); // Print details printf("Meshes: %d\n", props->meshCount); for (int i = 0; i < props->meshCount; i++) { Mesh mesh = props->meshes[i]; printf("Mesh %d: Vertices %d, PrimGroups %d\n", i, mesh.verticesCount, mesh.primGroupCount); // Print more } } void writeCMOD(const CMODProperties* props, const char* newFilepath) { FILE* f = fopen(newFilepath, "w"); fprintf(f, "#celmodel__ascii\n"); for (int i = 0; i < props->materialCount; i++) { fprintf(f, "material\n"); // Write props fprintf(f, "end_material\n"); } for (int i = 0; i < props->meshCount; i++) { Mesh mesh = props->meshes[i]; fprintf(f, "mesh\n"); fprintf(f, "vertexdesc\n"); for (int j = 0; j < mesh.vertexDescCount; j++) { fprintf(f, "%s %s\n", mesh.vertexDesc[j].semantic, mesh.vertexDesc[j].format); } fprintf(f, "end_vertexdesc\n"); fprintf(f, "vertices %d\n", mesh.verticesCount); // Vertex data for (int j = 0; j < mesh.primGroupCount; j++) { PrimGroup group = mesh.primGroups[j]; fprintf(f, "%s %d %d", group.type, group.materialIndex, group.indexCount); for (int k = 0; k < group.indexCount; k++) { fprintf(f, " %d", group.indices[k]); } fprintf(f, "\n"); } fprintf(f, "end_mesh\n"); } fclose(f); } // Example // int main() { // FILE* f = fopen("example.cmod", "rb"); // CMODProperties props; // initProperties(&props); // if (isBinary(f) == 1) parseBinary(f, &props); // else parseAscii(f, &props); // printProperties(&props); // writeCMOD(&props, "new.cmod"); // freeProperties(&props); // fclose(f); // return 0; // } // ===== end task-094 .CMOD ===== // ===== task-095 .CMOD [C] ===== #include #include #include #define MAX_LINE 256 #define MAX_MATERIALS 10 #define MAX_MESHES 10 #define MAX_VERTEXDESC 20 #define MAX_VERTICES 1000 #define MAX_GROUPS 10 #define MAX_INDICES 1000 typedef struct { char key[MAX_LINE]; char value[MAX_LINE]; } Property; typedef struct { Property props[10]; // Diffuse, etc. int propCount; } Material; typedef struct { char vertexdesc[MAX_VERTEXDESC][MAX_LINE]; int vdCount; char vertices[MAX_VERTICES][MAX_LINE]; int vertexCount; struct { char type[MAX_LINE]; char material[MAX_LINE]; char indices[MAX_INDICES][MAX_LINE]; int indexCount; } groups[MAX_GROUPS]; int groupCount; } Mesh; typedef struct { char filepath[MAX_LINE]; char header[MAX_LINE]; Material materials[MAX_MATERIALS]; int materialCount; Mesh meshes[MAX_MESHES]; int meshCount; } CMODHandler; void initCMODHandler(CMODHandler *handler, const char *filepath) { strcpy(handler->filepath, filepath); handler->materialCount = 0; handler->meshCount = 0; FILE *f = fopen(filepath, "r"); if (!f) return; char content[10000] = {0}; // Simplified buffer fread(content, 1, sizeof(content), f); fclose(f); if (strstr(content, "#celmodel__ascii")) { strcpy(handler->header, "#celmodel__ascii"); // Parsing logic similar to Python, but manual // Omitted detailed parsing code for brevity; implement line-by-line scanning like above languages // For example, use strtok or sscanf to parse lines into structs printf("Parsing ASCII .CMOD...\n"); // Add parsing here... } else { printf("Binary or invalid .CMOD. ASCII only supported.\n"); } } void printProperties(CMODHandler *handler) { printf("Header: %s\n", handler->header); for (int i = 0; i < handler->materialCount; i++) { printf("Material %d:\n", i); for (int j = 0; j < handler->materials[i].propCount; j++) { printf(" %s: %s\n", handler->materials[i].props[j].key, handler->materials[i].props[j].value); } } for (int i = 0; i < handler->meshCount; i++) { printf("Mesh %d:\n", i); printf(" VertexDesc:\n"); for (int j = 0; j < handler->meshes[i].vdCount; j++) { printf(" %s\n", handler->meshes[i].vertexdesc[j]); } printf(" Vertices (%d):\n", handler->meshes[i].vertexCount); for (int j = 0; j < handler->meshes[i].vertexCount; j++) { printf(" %s\n", handler->meshes[i].vertices[j]); } for (int k = 0; k < handler->meshes[i].groupCount; k++) { printf(" Group %d: Type %s, Material %s\n", k, handler->meshes[i].groups[k].type, handler->meshes[i].groups[k].material); for (int j = 0; j < handler->meshes[i].groups[k].indexCount; j++) { printf(" Index: %s\n", handler->meshes[i].groups[k].indices[j]); } } } } void writeCMOD(CMODHandler *handler, const char *outputPath) { FILE *f = fopen(outputPath, "w"); if (!f) return; fprintf(f, "%s\n", handler->header); // Write materials, meshes similarly... fclose(f); } // Example usage: // int main() { // CMODHandler handler; // initCMODHandler(&handler, "example.cmod"); // printProperties(&handler); // writeCMOD(&handler, "output.cmod"); // return 0; // } // ===== end task-095 .CMOD ===== // ===== task-096 .CNOFF [C] ===== #include #include #include #include typedef struct { float position[3]; float normal[3]; float color[4]; } Vertex; typedef struct { int nv; int *indices; float *face_color; // NULL if none int color_count; } Face; typedef struct { char header[256]; int n_vertices; int n_faces; int n_edges; Vertex *vertices; Face *faces; bool is_binary; } CNOFF; CNOFF* cnoff_init() { CNOFF* c = malloc(sizeof(CNOFF)); memset(c, 0, sizeof(CNOFF)); return c; } void cnoff_free(CNOFF* c) { if (c->vertices) free(c->vertices); for (int i = 0; i < c->n_faces; i++) { if (c->faces[i].indices) free(c->faces[i].indices); if (c->faces[i].face_color) free(c->faces[i].face_color); } if (c->faces) free(c->faces); free(c); } int cnoff_read(CNOFF* c, const char* filepath) { FILE* f = fopen(filepath, "r"); if (!f) return 1; fgets(c->header, 256, f); c->header[strcspn(c->header, "\n")] = 0; if (strstr(c->header, "BINARY")) { fclose(f); return cnoff_read_binary(c, filepath); } fscanf(f, "%d %d %d", &c->n_vertices, &c->n_faces, &c->n_edges); c->vertices = malloc(c->n_vertices * sizeof(Vertex)); for (int i = 0; i < c->n_vertices; i++) { Vertex* v = &c->vertices[i]; fscanf(f, "%f %f %f %f %f %f %f %f %f %f", &v->position[0], &v->position[1], &v->position[2], &v->normal[0], &v->normal[1], &v->normal[2], &v->color[0], &v->color[1], &v->color[2], &v->color[3]); } c->faces = malloc(c->n_faces * sizeof(Face)); char line[1024]; for (int i = 0; i < c->n_faces; i++) { fgets(line, 1024, f); // To handle variable face colors Face* face = &c->faces[i]; char* token = strtok(line, " "); face->nv = atoi(token); face->indices = malloc(face->nv * sizeof(int)); for (int j = 0; j < face->nv; j++) { token = strtok(NULL, " "); face->indices[j] = atoi(token); } face->color_count = 0; face->face_color = NULL; token = strtok(NULL, " "); while (token) { face->color_count++; face->face_color = realloc(face->face_color, face->color_count * sizeof(float)); face->face_color[face->color_count - 1] = atof(token); token = strtok(NULL, " "); } } fclose(f); return 0; } int cnoff_read_binary(CNOFF* c, const char* filepath) { FILE* f = fopen(filepath, "rb"); if (!f) return 1; // Skip header char ch; while ((ch = fgetc(f)) != '\n'); fread(&c->n_vertices, sizeof(int), 1, f); fread(&c->n_faces, sizeof(int), 1, f); fread(&c->n_edges, sizeof(int), 1, f); c->vertices = malloc(c->n_vertices * sizeof(Vertex)); for (int i = 0; i < c->n_vertices; i++) { Vertex* v = &c->vertices[i]; fread(v->position, sizeof(float), 3, f); fread(v->normal, sizeof(float), 3, f); fread(v->color, sizeof(float), 4, f); } c->faces = malloc(c->n_faces * sizeof(Face)); for (int i = 0; i < c->n_faces; i++) { Face* face = &c->faces[i]; fread(&face->nv, sizeof(int), 1, f); face->indices = malloc(face->nv * sizeof(int)); fread(face->indices, sizeof(int), face->nv, f); fread(&face->color_count, sizeof(int), 1, f); if (face->color_count > 0) { face->face_color = malloc(face->color_count * sizeof(float)); fread(face->face_color, sizeof(float), face->color_count, f); } else { face->face_color = NULL; } } fclose(f); c->is_binary = true; return 0; } int cnoff_write(CNOFF* c, const char* filepath, bool binary) { FILE* f = fopen(filepath, binary ? "wb" : "w"); if (!f) return 1; if (binary) { fprintf(f, "%s BINARY\n", c->header); fwrite(&c->n_vertices, sizeof(int), 1, f); fwrite(&c->n_faces, sizeof(int), 1, f); fwrite(&c->n_edges, sizeof(int), 1, f); for (int i = 0; i < c->n_vertices; i++) { Vertex v = c->vertices[i]; fwrite(v.position, sizeof(float), 3, f); fwrite(v.normal, sizeof(float), 3, f); fwrite(v.color, sizeof(float), 4, f); } for (int i = 0; i < c->n_faces; i++) { Face face = c->faces[i]; fwrite(&face.nv, sizeof(int), 1, f); fwrite(face.indices, sizeof(int), face.nv, f); fwrite(&face.color_count, sizeof(int), 1, f); if (face.color_count > 0) { fwrite(face.face_color, sizeof(float), face.color_count, f); } } } else { fprintf(f, "%s\n", c->header); fprintf(f, "%d %d %d\n", c->n_vertices, c->n_faces, c->n_edges); for (int i = 0; i < c->n_vertices; i++) { Vertex v = c->vertices[i]; fprintf(f, "%.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f\n", v.position[0], v.position[1], v.position[2], v.normal[0], v.normal[1], v.normal[2], v.color[0], v.color[1], v.color[2], v.color[3]); } for (int i = 0; i < c->n_faces; i++) { Face face = c->faces[i]; fprintf(f, "%d", face.nv); for (int j = 0; j < face.nv; j++) { fprintf(f, " %d", face.indices[j]); } for (int j = 0; j < face.color_count; j++) { fprintf(f, " %.6f", face.face_color[j]); } fprintf(f, "\n"); } } fclose(f); return 0; } void cnoff_print_properties(CNOFF* c) { printf("Header: %s\n", c->header); printf("Number of vertices: %d\n", c->n_vertices); printf("Number of faces: %d\n", c->n_faces); printf("Number of edges: %d\n", c->n_edges); printf("Vertices:\n"); for (int i = 0; i < c->n_vertices; i++) { Vertex v = c->vertices[i]; printf(" Vertex %d: Position=[%.2f, %.2f, %.2f], Normal=[%.2f, %.2f, %.2f], Color=[%.2f, %.2f, %.2f, %.2f]\n", i, v.position[0], v.position[1], v.position[2], v.normal[0], v.normal[1], v.normal[2], v.color[0], v.color[1], v.color[2], v.color[3]); } printf("Faces:\n"); for (int i = 0; i < c->n_faces; i++) { Face face = c->faces[i]; printf(" Face %d: Nv=%d, Indices=[", i, face.nv); for (int j = 0; j < face.nv; j++) { printf("%d%s", face.indices[j], j < face.nv - 1 ? ", " : ""); } printf("], Face Color="); if (face.color_count > 0) { printf("["); for (int j = 0; j < face.color_count; j++) { printf("%.2f%s", face.face_color[j], j < face.color_count - 1 ? ", " : ""); } printf("]"); } else { printf("null"); } printf("\n"); } } int main(int argc, char** argv) { if (argc < 2) return 1; CNOFF* c = cnoff_init(); if (cnoff_read(c, argv[1]) == 0) { cnoff_print_properties(c); } cnoff_free(c); return 0; } // ===== end task-096 .CNOFF ===== // ===== task-097 .COB [C++] ===== #include #include #include #include struct Header { std::string identifier; std::string version; char mode; std::string bitmode; std::string blank; char newline; }; struct Face { short numVerts; std::vector vertIndices; std::vector uvIndices; short matIndex; short flags; }; struct Chunk { std::string type; short majorVersion; short minorVersion; int id; int parentId; int dataSize; short nameDupecount; short nameLength; std::string name; float center[3]; float dirX[3]; float dirY[3]; float dirZ[3]; float matrixRow1[4]; float matrixRow2[4]; float matrixRow3[4]; int numVertices; std::vector vertices; int numUvs; std::vector uvs; int numFaces; std::vector faces; }; class CobFileC { private: Header header; std::vector chunks; public: void read(const std::string& filename) { std::ifstream f(filename, std::ios::binary); if (!f) return; char buf[14]; // Max str size +1 f.read(buf, 9); header.identifier = std::string(buf, 9); f.read(buf, 6); header.version = std::string(buf, 6); f.read(&header.mode, 1); f.read(buf, 2); header.bitmode = std::string(buf, 2); f.read(buf, 13); header.blank = std::string(buf, 13); f.read(&header.newline, 1); while (f.good()) { Chunk chunk; f.read(buf, 4); chunk.type = std::string(buf, 4); f.read(reinterpret_cast(&chunk.majorVersion), sizeof(short)); f.read(reinterpret_cast(&chunk.minorVersion), sizeof(short)); f.read(reinterpret_cast(&chunk.id), sizeof(int)); f.read(reinterpret_cast(&chunk.parentId), sizeof(int)); f.read(reinterpret_cast(&chunk.dataSize), sizeof(int)); if (chunk.dataSize > 0) { f.read(reinterpret_cast(&chunk.nameDupecount), sizeof(short)); f.read(reinterpret_cast(&chunk.nameLength), sizeof(short)); std::vector nameBuf(chunk.nameLength + 1); f.read(nameBuf.data(), chunk.nameLength + 1); chunk.name = std::string(nameBuf.data(), chunk.nameLength); f.read(reinterpret_cast(chunk.center), sizeof(float)*3); f.read(reinterpret_cast(chunk.dirX), sizeof(float)*3); f.read(reinterpret_cast(chunk.dirY), sizeof(float)*3); f.read(reinterpret_cast(chunk.dirZ), sizeof(float)*3); f.read(reinterpret_cast(chunk.matrixRow1), sizeof(float)*4); f.read(reinterpret_cast(chunk.matrixRow2), sizeof(float)*4); f.read(reinterpret_cast(chunk.matrixRow3), sizeof(float)*4); f.read(reinterpret_cast(&chunk.numVertices), sizeof(int)); chunk.vertices.resize(chunk.numVertices); for (int i = 0; i < chunk.numVertices; i++) { f.read(reinterpret_cast(chunk.vertices[i]), sizeof(float)*3); } f.read(reinterpret_cast(&chunk.numUvs), sizeof(int)); chunk.uvs.resize(chunk.numUvs); for (int i = 0; i < chunk.numUvs; i++) { f.read(reinterpret_cast(chunk.uvs[i]), sizeof(float)*2); } f.read(reinterpret_cast(&chunk.numFaces), sizeof(int)); chunk.faces.resize(chunk.numFaces); for (int i = 0; i < chunk.numFaces; i++) { Face& face = chunk.faces[i]; f.read(reinterpret_cast(&face.numVerts), sizeof(short)); face.vertIndices.resize(face.numVerts); for (int j = 0; j < face.numVerts; j++) { f.read(reinterpret_cast(&face.vertIndices[j]), sizeof(short)); } face.uvIndices.resize(face.numVerts); for (int j = 0; j < face.numVerts; j++) { f.read(reinterpret_cast(&face.uvIndices[j]), sizeof(short)); } f.read(reinterpret_cast(&face.matIndex), sizeof(short)); f.read(reinterpret_cast(&face.flags), sizeof(short)); } } chunks.push_back(chunk); } } void printProperties() { std::cout << "File Header:" << std::endl; std::cout << " Identifier: " << header.identifier << std::endl; // ... (print all) for (size_t i = 0; i < chunks.size(); i++) { const Chunk& chunk = chunks[i]; std::cout << "\nChunk " << i << ":" << std::endl; std::cout << " Type: " << chunk.type << std::endl; // ... (print all fields, loops for lists) } } void write(const std::string& filename) { std::ofstream f(filename, std::ios::binary); if (!f) return; f.write(header.identifier.c_str(), 9); // ... (write all, similar to read) } }; // Example // CobFileC cob; // cob.read("example.cob"); // cob.printProperties(); // cob.write("output.cob"); // ===== end task-097 .COB ===== // ===== task-098 .COE [C] ===== #include #include #include #include #define MAX_LINE 1024 #define MAX_VALUES 10000 // Arbitrary max for vector size typedef struct { int radix; int* vector; size_t vector_size; } COEFile; COEFile* coe_create() { COEFile* coe = malloc(sizeof(COEFile)); coe->radix = -1; coe->vector = NULL; coe->vector_size = 0; return coe; } void coe_destroy(COEFile* coe) { free(coe->vector); free(coe); } int coe_load(COEFile* coe, const char* filename) { FILE* fp = fopen(filename, "r"); if (!fp) return -1; char line[MAX_LINE]; char text[1024 * 1024] = {0}; // Arbitrary large buffer while (fgets(line, sizeof(line), fp)) { strcat(text, line); } fclose(fp); // Remove comments char* p = text; while ((p = strchr(p, ';')) != NULL) { while (*p != '\n' && *p != '\0') *p++ = ' '; } // Parse radix char* radix_str = strstr(text, "memory_initialization_radix"); if (radix_str) { radix_str = strchr(radix_str, '='); if (radix_str) coe->radix = atoi(radix_str + 1); } // Parse vector char* vector_str = strstr(text, "memory_initialization_vector"); if (vector_str) { vector_str = strchr(vector_str, '='); if (vector_str) { vector_str++; coe->vector = malloc(sizeof(int) * MAX_VALUES); char* token = strtok(vector_str, ",;"); size_t i = 0; while (token && i < MAX_VALUES) { while (isspace(*token)) token++; if (*token) { coe->vector[i++] = (int)strtol(token, NULL, coe->radix); } token = strtok(NULL, ",;"); } coe->vector_size = i; } } return 0; } void coe_print_properties(const COEFile* coe) { if (coe->radix == -1) { printf("No properties loaded.\n"); return; } printf("Memory Initialization Radix: %d\n", coe->radix); printf("Memory Initialization Vector (decoded to integers):\n"); for (size_t i = 0; i < coe->vector_size; i++) { printf("%d", coe->vector[i]); if (i < coe->vector_size - 1) printf(", "); } printf("\n"); } int coe_write(const char* filename, int radix, const int* vector, size_t vector_size) { FILE* fp = fopen(filename, "w"); if (!fp) return -1; fprintf(fp, "; Generated .COE file\n"); fprintf(fp, "memory_initialization_radix = %d;\n", radix); fprintf(fp, "memory_initialization_vector =\n"); for (size_t i = 0; i < vector_size; i++) { if (radix == 2) { fprintf(fp, "%b", vector[i]); // Note: %b not standard, use custom conversion if needed } else if (radix == 8) { fprintf(fp, "%o", vector[i]); } else if (radix == 10) { fprintf(fp, "%d", vector[i]); } else if (radix == 16) { char buf[32]; sprintf(buf, "%x", vector[i]); for (char* p = buf; *p; p++) *p = tolower(*p); fprintf(fp, "%s", buf); } else { fclose(fp); return -2; // Unsupported radix } if (i < vector_size - 1) fprintf(fp, ",\n"); } fprintf(fp, ";\n"); fclose(fp); return 0; } // Example usage: // int main() { // COEFile* coe = coe_create(); // coe_load(coe, "input.coe"); // coe_print_properties(coe); // int vector[] = {0, 1, 2, 3}; // coe_write("output.coe", 16, vector, 4); // coe_destroy(coe); // return 0; // } // ===== end task-098 .COE ===== // ===== task-099 .COFF [C] ===== #include #include #include #include typedef struct { uint16_t machine; uint16_t numberOfSections; uint32_t timeDateStamp; uint32_t pointerToSymbolTable; uint32_t numberOfSymbols; uint16_t sizeOfOptionalHeader; uint16_t characteristics; } CoffFileHeader; // Other structs for optional header, section header, etc. typedef struct { char* filename; uint8_t* data; size_t size; CoffFileHeader fileHeader; // Other members } CoffParser; CoffParser* coff_parser_create(const char* filename) { CoffParser* parser = malloc(sizeof(CoffParser)); parser->filename = strdup(filename); // Initialize others return parser; } void coff_parser_read(CoffParser* parser) { FILE* f = fopen(parser->filename, "rb"); fseek(f, 0, SEEK_END); parser->size = ftell(f); fseek(f, 0, SEEK_SET); parser->data = malloc(parser->size); fread(parser->data, 1, parser->size, f); fclose(f); // Parse file header memcpy(&parser->fileHeader, parser->data, sizeof(CoffFileHeader)); // Parse others based on endian (assume little) } void coff_parser_print_properties(const CoffParser* parser) { printf("File Header:\n"); printf("Machine: 0x%X\n", parser->fileHeader.machine); // Print others // Print optional, sections, etc. } void coff_parser_write(const CoffParser* parser, const char* newFilename) { FILE* f = fopen(newFilename, "wb"); fwrite(parser->data, 1, parser->size, f); fclose(f); } void coff_parser_destroy(CoffParser* parser) { free(parser->data); free(parser->filename); free(parser); } // Usage example int main() { CoffParser* parser = coff_parser_create("example.obj"); coff_parser_read(parser); coff_parser_print_properties(parser); coff_parser_write(parser, "modified.obj"); coff_parser_destroy(parser); return 0; } // ===== end task-099 .COFF ===== // ===== task-100 .COL [C] ===== #include #include #include #include typedef struct { char *variant; size_t file_size; uint16_t id; uint16_t version; int num_entries; uint8_t *palette; // Raw RGB data } ColFile; ColFile *col_new() { ColFile *col = malloc(sizeof(ColFile)); col->variant = NULL; col->file_size = 0; col->id = 0; col->version = 0; col->num_entries = 0; col->palette = NULL; return col; } void col_read(ColFile *col, const char *filepath) { FILE *f = fopen(filepath, "rb"); if (!f) { fprintf(stderr, "Cannot open file\n"); return; } fseek(f, 0, SEEK_END); col->file_size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(col->file_size); fread(data, 1, col->file_size, f); fclose(f); if (col->file_size == 768) { col->variant = "Original"; col->num_entries = 256; col->palette = data; } else { col->variant = "Pro"; uint32_t size_field = *(uint32_t *)(data); col->id = *(uint16_t *)(data + 4); col->version = *(uint16_t *)(data + 6); int calc_entries = (col->file_size - 8) / 3; if ((col->file_size - 8) % 3 != 0 || col->id != 0xB123 || size_field != col->file_size) { free(data); fprintf(stderr, "Invalid .COL file\n"); return; } col->num_entries = calc_entries; col->palette = malloc(3 * col->num_entries); memcpy(col->palette, data + 8, 3 * col->num_entries); free(data); } } void col_print_properties(const ColFile *col) { printf("Variant: %s\n", col->variant); printf("File Size: %zu bytes\n", col->file_size); if (strcmp(col->variant, "Pro") == 0) { printf("Header ID: 0x%04X\n", col->id); printf("Header Version: %u\n", col->version); } printf("Number of Palette Entries: %d\n", col->num_entries); printf("Palette Data (first 5 entries):\n"); for (int i = 0; i < 5 && i < col->num_entries; i++) { uint8_t r = col->palette[i * 3]; uint8_t g = col->palette[i * 3 + 1]; uint8_t b = col->palette[i * 3 + 2]; printf("Entry %d: R=%u, G=%u, B=%u\n", i + 1, r, g, b); } } void col_write(const ColFile *col, const char *filepath) { FILE *f = fopen(filepath, "wb"); if (!f) { fprintf(stderr, "Cannot open file for writing\n"); return; } if (strcmp(col->variant, "Pro") == 0) { uint32_t calc_size = 8 + 3 * col->num_entries; fwrite(&calc_size, sizeof(uint32_t), 1, f); uint16_t temp_id = 0xB123; fwrite(&temp_id, sizeof(uint16_t), 1, f); uint16_t temp_version = 0; fwrite(&temp_version, sizeof(uint16_t), 1, f); } fwrite(col->palette, 1, 3 * col->num_entries, f); fclose(f); } void col_free(ColFile *col) { free(col->palette); free(col); } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } ColFile *col = col_new(); col_read(col, argv[1]); col_print_properties(col); col_free(col); return 0; } // ===== end task-100 .COL ===== // ===== task-101 .COM [C] ===== #include #include #include #include #include #include #ifdef _WIN32 #include #endif typedef struct { char* filepath; struct stat stats; } ComFileHandler; void init_ComFileHandler(ComFileHandler* handler, const char* filepath) { if (strstr(filepath, ".com") == NULL && strstr(filepath, ".COM") == NULL) { fprintf(stderr, "File must have .COM extension\n"); exit(1); } handler->filepath = strdup(filepath); if (stat(filepath, &handler->stats) != 0) { perror("stat"); exit(1); } } void print_properties(ComFileHandler* handler) { char* filename = strrchr(handler->filepath, '/'); filename = filename ? filename + 1 : handler->filepath; char* ext = strrchr(filename, '.'); char name[256]; strncpy(name, filename, ext - filename); name[ext - filename] = '\0'; struct tm* tm; char buf[32]; printf("Filename: %s\n", name); printf("Extension: COM\n"); #ifdef _WIN32 DWORD attrs = GetFileAttributes(handler->filepath); printf("Attributes: "); if (attrs & FILE_ATTRIBUTE_READONLY) printf("Read-only "); if (attrs & FILE_ATTRIBUTE_HIDDEN) printf("Hidden "); if (attrs & FILE_ATTRIBUTE_SYSTEM) printf("System "); if (attrs & FILE_ATTRIBUTE_ARCHIVE) printf("Archive"); printf("\n"); #else printf("Attributes: %s\n", (handler->stats.st_mode & S_IWUSR) == 0 ? "Read-only" : "None"); #endif printf("Reserved: N/A\n"); printf("Creation time tenths: N/A\n"); tm = localtime(&handler->stats.st_ctime); strftime(buf, sizeof(buf), "%H:%M:%S", tm); printf("Creation time: %s\n", buf); strftime(buf, sizeof(buf), "%Y-%m-%d", tm); printf("Creation date: %s\n", buf); tm = localtime(&handler->stats.st_atime); strftime(buf, sizeof(buf), "%Y-%m-%d", tm); printf("Last access date: %s\n", buf); printf("High starting cluster: N/A\n"); tm = localtime(&handler->stats.st_mtime); strftime(buf, sizeof(buf), "%H:%M:%S", tm); printf("Last modification time: %s\n", buf); strftime(buf, sizeof(buf), "%Y-%m-%d", tm); printf("Last modification date: %s\n", buf); printf("Low starting cluster: N/A\n"); printf("File size: %ld bytes\n", (long)handler->stats.st_size); } void write_property(ComFileHandler* handler, const char* prop, const char* value) { if (strcmp(prop, "Last modification time") == 0) { struct tm tm; strptime(value, "%Y-%m-%d %H:%M:%S", &tm); time_t mod_time = mktime(&tm); struct utimbuf ut; ut.actime = handler->stats.st_atime; ut.modtime = mod_time; utime(handler->filepath, &ut); } else if (strcmp(prop, "Read-only") == 0) { mode_t mode = handler->stats.st_mode; chmod(handler->filepath, atoi(value) ? mode & ~0222 : mode | 0222); } else { fprintf(stderr, "Only select properties can be written\n"); } } void free_ComFileHandler(ComFileHandler* handler) { free(handler->filepath); } // Example usage: // int main() { // ComFileHandler handler; // init_ComFileHandler(&handler, "path/to/file.com"); // print_properties(&handler); // write_property(&handler, "Last modification time", "2025-09-11 12:00:00"); // free_ComFileHandler(&handler); // return 0; // } // ===== end task-101 .COM ===== // ===== task-102 .COMPILE [C++] ===== #include #include #include #include // Assume tinyxml2 library is included class CompileFileHandler { private: std::string filepath; std::map properties; std::vector filedeps; public: CompileFileHandler(const std::string& fp) : filepath(fp) {} void read() { tinyxml2::XMLDocument doc; if (doc.LoadFile(filepath.c_str()) != tinyxml2::XML_SUCCESS) { std::cout << "Error reading file: " << doc.ErrorStr() << std::endl; return; } tinyxml2::XMLElement* root = doc.FirstChildElement("preserve"); if (root) { properties["resultType"] = root->Attribute("resultType") ? root->Attribute("resultType") : ""; properties["virtualPath"] = root->Attribute("virtualPath") ? root->Attribute("virtualPath") : ""; properties["hash"] = root->Attribute("hash") ? root->Attribute("hash") : ""; properties["filehash"] = root->Attribute("filehash") ? root->Attribute("filehash") : ""; properties["flags"] = root->Attribute("flags") ? root->Attribute("flags") : ""; properties["assembly"] = root->Attribute("assembly") ? root->Attribute("assembly") : ""; properties["type"] = root->Attribute("type") ? root->Attribute("type") : ""; tinyxml2::XMLElement* filedepsElem = root->FirstChildElement("filedeps"); if (filedepsElem) { tinyxml2::XMLElement* dep = filedepsElem->FirstChildElement("filedep"); while (dep) { filedeps.push_back(dep->Attribute("name") ? dep->Attribute("name") : ""); dep = dep->NextSiblingElement("filedep"); } } } else { std::cout << "Invalid .COMPILE file format" << std::endl; } } void printProperties() { if (!properties.empty()) { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } std::cout << "filedeps: "; for (const auto& dep : filedeps) { std::cout << dep << " "; } std::cout << std::endl; } else { std::cout << "No properties loaded. Call read() first." << std::endl; } } void write(const std::string& newFilepath, const std::map& newProperties = {}) { tinyxml2::XMLDocument doc; tinyxml2::XMLDeclaration* decl = doc.NewDeclaration(); doc.InsertFirstChild(decl); tinyxml2::XMLElement* root = doc.NewElement("preserve"); for (const auto& pair : properties) { root->SetAttribute(pair.first.c_str(), pair.second.c_str()); } for (const auto& pair : newProperties) { root->SetAttribute(pair.first.c_str(), pair.second.c_str()); } tinyxml2::XMLElement* filedepsElem = doc.NewElement("filedeps"); for (const auto& dep : filedeps) { tinyxml2::XMLElement* depElem = doc.NewElement("filedep"); depElem->SetAttribute("name", dep.c_str()); filedepsElem->InsertEndChild(depElem); } root->InsertEndChild(filedepsElem); doc.InsertEndChild(root); if (doc.SaveFile(newFilepath.c_str()) != tinyxml2::XML_SUCCESS) { std::cout << "Error writing file: " << doc.ErrorStr() << std::endl; } else { std::cout << "File written to " << newFilepath << std::endl; } } }; // Example usage: // int main() { // CompileFileHandler handler("example.COMPILE"); // handler.read(); // handler.printProperties(); // std::map updates = {{"hash", "newhash"}}; // handler.write("new.COMPILE", updates); // return 0; // } // ===== end task-102 .COMPILE ===== // ===== task-103 .CONFIG [C] ===== #include #include #include #include #define MAX_LINE_LENGTH 256 #define MAX_PROPERTIES 10000 // Arbitrary max for properties typedef struct { char *key; char *value; } Property; typedef struct { char *filepath; Property *properties; int count; } ConfigFileHandler; ConfigFileHandler* createHandler(const char *filepath) { ConfigFileHandler *handler = malloc(sizeof(ConfigFileHandler)); handler->filepath = strdup(filepath); handler->properties = malloc(MAX_PROPERTIES * sizeof(Property)); handler->count = 0; return handler; } void destroyHandler(ConfigFileHandler *handler) { for (int i = 0; i < handler->count; i++) { free(handler->properties[i].key); free(handler->properties[i].value); } free(handler->properties); free(handler->filepath); free(handler); } bool readAndDecode(ConfigFileHandler *handler) { FILE *file = fopen(handler->filepath, "r"); if (!file) { perror("File not found"); return false; } char line[MAX_LINE_LENGTH]; while (fgets(line, sizeof(line), file)) { char *trimmed = strtok(line, "\n"); if (trimmed && trimmed[0] != '#' && strchr(trimmed, '=')) { char *key = strtok(trimmed, "="); char *value = strtok(NULL, "="); if (key && value && handler->count < MAX_PROPERTIES) { handler->properties[handler->count].key = strdup(key); handler->properties[handler->count].value = strdup(value); handler->count++; } } } fclose(file); return true; } void printProperties(ConfigFileHandler *handler) { if (handler->count == 0) { printf("No properties loaded.\n"); return; } for (int i = 0; i < handler->count; i++) { printf("%s = %s\n", handler->properties[i].key, handler->properties[i].value); } } bool writeProperties(ConfigFileHandler *handler, const char *newKey, const char *newValue) { // Simple append/update example; for full map, extend as needed FILE *file = fopen(handler->filepath, "w"); if (!file) { perror("Cannot write file"); return false; } fprintf(file, "# Automatically generated .CONFIG file\n"); for (int i = 0; i < handler->count; i++) { fprintf(file, "%s=%s\n", handler->properties[i].key, handler->properties[i].value); } if (newKey && newValue) { fprintf(file, "%s=%s\n", newKey, newValue); } fclose(file); return true; } // Example usage: // int main() { // ConfigFileHandler *handler = createHandler("path/to/.config"); // if (readAndDecode(handler)) { // printProperties(handler); // writeProperties(handler, "CONFIG_NEW", "y"); // } // destroyHandler(handler); // return 0; // } // ===== end task-103 .CONFIG ===== // ===== task-104 .CPC [C] ===== #include #include #include #include typedef struct { const unsigned char magic[4]; char* filepath; long size; bool is_valid; } CPCFile; const unsigned char CPC_MAGIC[4] = {0x43, 0x50, 0x43, 0xB2}; CPCFile* cpcfile_new(const char* filepath) { CPCFile* cpc = malloc(sizeof(CPCFile)); memcpy((void*)cpc->magic, CPC_MAGIC, 4); cpc->filepath = strdup(filepath); cpc->size = 0; cpc->is_valid = false; return cpc; } void cpcfile_open(CPCFile* cpc) { FILE* f = fopen(cpc->filepath, "rb"); if (!f) { perror("File not found"); exit(1); } fseek(f, 0, SEEK_END); cpc->size = ftell(f); fclose(f); } void cpcfile_decode_read(CPCFile* cpc) { FILE* f = fopen(cpc->filepath, "rb"); unsigned char magic_read[4]; fread(magic_read, 1, 4, f); cpc->is_valid = memcmp(magic_read, cpc->magic, 4) == 0; fclose(f); } void cpcfile_print_properties(const CPCFile* cpc) { printf("File Name: %s\n", strrchr(cpc->filepath, '/') ? strrchr(cpc->filepath, '/') + 1 : cpc->filepath); printf("File Size: %ld bytes\n", cpc->size); printf("Magic Bytes: %02X %02X %02X %02X\n", cpc->magic[0], cpc->magic[1], cpc->magic[2], cpc->magic[3]); printf("Valid Magic: %s\n", cpc->is_valid ? "Yes" : "No"); printf("Extension: .cpc\n"); printf("Type: Bi-level raster image (proprietary compression)\n"); printf("Intended Use: Document imaging\n"); printf("Developer: Cartesian Products, Inc.\n"); printf("Patent: US #5,303,313\n"); printf("Note: Full decoding not possible; proprietary format.\n"); } void cpcfile_write(const CPCFile* cpc, const char* new_filepath) { FILE* f = fopen(new_filepath, "wb"); fwrite(cpc->magic, 1, 4, f); // Stub: Write dummy data unsigned char dummy[100] = {0}; fwrite(dummy, 1, 100, f); fclose(f); printf("Stub .CPC file written to %s (not fully valid due to proprietary format)\n", new_filepath); } void cpcfile_free(CPCFile* cpc) { free(cpc->filepath); free(cpc); } int main() { CPCFile* cpc = cpcfile_new("example.cpc"); cpcfile_open(cpc); cpcfile_decode_read(cpc); cpcfile_print_properties(cpc); cpcfile_write(cpc, "new_example.cpc"); cpcfile_free(cpc); return 0; } // ===== end task-104 .CPC ===== // ===== task-105 .CPIO [C++] ===== #include #include #include #include #include #include #include class CpioFile { private: std::string filename; std::vector> entries; std::vector> datas; // Store data for each entry public: CpioFile(const std::string& fn) : filename(fn) {} void readAndDecode() { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) { throw std::runtime_error("Cannot open file"); } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); std::vector data(size); if (!file.read(data.data(), size)) { throw std::runtime_error("Cannot read file"); } size_t offset = 0; while (offset < data.size()) { std::string magic(data.begin() + offset, data.begin() + offset + 6); if (magic != "070701") { throw std::runtime_error("Invalid or unsupported cpio format (expecting newc)."); } offset += 6; long long ino = std::stoll(std::string(data.begin() + offset, data.begin() + offset + 8), nullptr, 16); offset += 8; long long mode = std::stoll(std::string(data.begin() + offset, data.begin() + offset + 8), nullptr, 16); offset += 8; long long uid = std::stoll(std::string(data.begin() + offset, data.begin() + offset + 8), nullptr, 16); offset += 8; long long gid = std::stoll(std::string(data.begin() + offset, data.begin() + offset + 8), nullptr, 16); offset += 8; long long nlink = std::stoll(std::string(data.begin() + offset, data.begin() + offset + 8), nullptr, 16); offset += 8; long long mtime = std::stoll(std::string(data.begin() + offset, data.begin() + offset + 8), nullptr, 16); offset += 8; long long filesize = std::stoll(std::string(data.begin() + offset, data.begin() + offset + 8), nullptr, 16); offset += 8; long long devmaj = std::stoll(std::string(data.begin() + offset, data.begin() + offset + 8), nullptr, 16); offset += 8; long long devmin = std::stoll(std::string(data.begin() + offset, data.begin() + offset + 8), nullptr, 16); offset += 8; long long rdevmaj = std::stoll(std::string(data.begin() + offset, data.begin() + offset + 8), nullptr, 16); offset += 8; long long rdevmin = std::stoll(std::string(data.begin() + offset, data.begin() + offset + 8), nullptr, 16); offset += 8; long long namesize = std::stoll(std::string(data.begin() + offset, data.begin() + offset + 8), nullptr, 16); offset += 8; long long check = std::stoll(std::string(data.begin() + offset, data.begin() + offset + 8), nullptr, 16); offset += 8; std::string fn(data.begin() + offset, data.begin() + offset + namesize - 1); offset += namesize; size_t pad = (4 - ((110 + namesize) % 4)) % 4; offset += pad; std::vector filedata(data.begin() + offset, data.begin() + offset + filesize); offset += filesize; pad = (4 - (filesize % 4)) % 4; offset += pad; if (fn == "TRAILER!!!") break; std::map entry; entry["ino"] = ino; entry["mode"] = mode; entry["uid"] = uid; entry["gid"] = gid; entry["nlink"] = nlink; entry["mtime"] = mtime; entry["filesize"] = filesize; entry["devmaj"] = devmaj; entry["devmin"] = devmin; entry["rdevmaj"] = rdevmaj; entry["rdevmin"] = rdevmin; entry["check"] = check; entries.push_back(entry); datas.push_back(filedata); } } void printProperties() { for (size_t i = 0; i < entries.size(); ++i) { auto& entry = entries[i]; std::cout << "Filename: " << /* Note: filename not stored in map, adjust if needed */ << std::endl; // Filename not in map; extend map with string if needed std::cout << "Inode number: " << entry["ino"] << std::endl; std::cout << "File mode: 0" << std::oct << entry["mode"] << " (octal)" << std::dec << std::endl; std::cout << "User ID (UID): " << entry["uid"] << std::endl; std::cout << "Group ID (GID): " << entry["gid"] << std::endl; std::cout << "Number of hard links (nlink): " << entry["nlink"] << std::endl; time_t t = entry["mtime"]; std::cout << "Modification time (mtime): " << entry["mtime"] << " (" << std::ctime(&t) << ")" << std::endl; std::cout << "File size: " << entry["filesize"] << std::endl; std::cout << "Device major number: " << entry["devmaj"] << std::endl; std::cout << "Device minor number: " << entry["devmin"] << std::endl; std::cout << "Rdevice major number: " << entry["rdevmaj"] << std::endl; std::cout << "Rdevice minor number: " << entry["rdevmin"] << std::endl; std::cout << "Checksum: " << entry["check"] << std::endl; std::cout << std::endl; } } void write(const std::string& outFilename) { std::ofstream file(outFilename, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open output file"); } for (size_t i = 0; i < entries.size(); ++i) { auto& entry = entries[i]; file << "070701"; file << std::setfill('0') << std::setw(8) << std::hex << entry["ino"]; file << std::setfill('0') << std::setw(8) << std::hex << entry["mode"]; file << std::setfill('0') << std::setw(8) << std::hex << entry["uid"]; file << std::setfill('0') << std::setw(8) << std::hex << entry["gid"]; file << std::setfill('0') << std::setw(8) << std::hex << entry["nlink"]; file << std::setfill('0') << std::setw(8) << std::hex << entry["mtime"]; file << std::setfill('0') << std::setw(8) << std::hex << entry["filesize"]; file << std::setfill('0') << std::setw(8) << std::hex << entry["devmaj"]; file << std::setfill('0') << std::setw(8) << std::hex << entry["devmin"]; file << std::setfill('0') << std::setw(8) << std::hex << entry["rdevmaj"]; file << std::setfill('0') << std::setw(8) << std::hex << entry["rdevmin"]; long long namesize = /* filename.length() + 1 */; // Extend with filename file << std::setfill('0') << std::setw(8) << std::hex << namesize; file << std::setfill('0') << std::setw(8) << std::hex << entry["check"]; file << /* filename + '\0' */; size_t pad = (4 - ((110 + namesize) % 4)) % 4; file.write("\0", pad); file.write(datas[i].data(), datas[i].size()); pad = (4 - (datas[i].size() % 4)) % 4; file.write("\0", pad); } // Trailer file << "070701"; for (int i = 0; i < 11; ++i) file << "00000000"; long long namesize = 11; file << std::setfill('0') << std::setw(8) << std::hex << namesize; file << "00000000"; file << "TRAILER!!!\0"; size_t pad = (4 - ((110 + namesize) % 4)) % 4; file.write("\0", pad); } }; // Example usage: // int main() { // CpioFile c("example.cpio"); // c.readAndDecode(); // c.printProperties(); // c.write("output.cpio"); // return 0; // } // ===== end task-105 .CPIO ===== // ===== task-106 .CPL [C++] ===== #include #include #include #include #include class CPLParser { private: std::string filepath; std::vector headers; std::vector> data; public: CPLParser(const std::string& filepath) : filepath(filepath) {} void read() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file" << std::endl; return; } std::string line; if (std::getline(file, line)) { std::stringstream ss(line); std::string token; while (std::getline(ss, token, ',')) { headers.push_back(token); } } while (std::getline(file, line)) { if (line.empty()) continue; std::stringstream ss(line); std::string token; std::vector row; while (std::getline(ss, token, ',')) { row.push_back(token); } data.push_back(row); } file.close(); } void decode() { // Decoding is trivial for CSV read(); } void printProperties() { std::cout << "Headers: "; for (size_t i = 0; i < headers.size(); ++i) { std::cout << headers[i]; if (i < headers.size() - 1) std::cout << ", "; } std::cout << std::endl; for (size_t i = 0; i < data.size(); ++i) { std::cout << "Component " << (i + 1) << ":" << std::endl; for (size_t j = 0; j < headers.size(); ++j) { std::cout << " " << headers[j] << ": " << (j < data[i].size() ? data[i][j] : "") << std::endl; } std::cout << std::endl; } } void write(const std::string& newFilepath) { std::ofstream file(newFilepath); if (!file.is_open()) { std::cerr << "Error opening file for writing" << std::endl; return; } for (size_t i = 0; i < headers.size(); ++i) { file << headers[i]; if (i < headers.size() - 1) file << ","; } file << std::endl; for (const auto& row : data) { for (size_t i = 0; i < row.size(); ++i) { file << row[i]; if (i < row.size() - 1) file << ","; } file << std::endl; } file.close(); } }; // Example usage // int main() { // CPLParser parser("example.cpl"); // parser.decode(); // parser.printProperties(); // parser.write("modified.cpl"); // return 0; // } // ===== end task-106 .CPL ===== // ===== task-107 .CPP [C++] ===== #include #include #include #include #include class CppFile { private: std::string path; struct stat statbuf; public: CppFile(const std::string& filePath) : path(filePath) { if (stat(path.c_str(), &statbuf) != 0) { std::cerr << "Error getting file stats" << std::endl; } } std::string read() { // Read and "decode" as text std::ifstream file(path); if (!file) { return "Error opening file"; } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); return content; } void write(const std::string& content) { // Write text content std::ofstream file(path); if (file) { file << content; } else { std::cerr << "Error writing to file" << std::endl; } } void printProperties() { // Print file system properties to console std::cout << "File size: " << statbuf.st_size << " bytes" << std::endl; std::cout << "Creation time: N/A (use st_ctime for status change: " << std::ctime(&statbuf.st_ctime) << ")" << std::endl; // True creation not always available std::cout << "Last modification time: " << std::ctime(&statbuf.st_mtime); std::cout << "Last access time: " << std::ctime(&statbuf.st_atime); std::cout << "Mode (permissions): " << std::oct << statbuf.st_mode << std::endl; std::cout << "Owner UID: " << statbuf.st_uid << std::endl; std::cout << "Owner GID: " << statbuf.st_gid << std::endl; } }; // Example usage: // int main() { // CppFile cpp("example.cpp"); // std::cout << cpp.read() << std::endl; // cpp.write("New content"); // cpp.printProperties(); // return 0; // } // ===== end task-107 .CPP ===== // ===== task-109 .CR2 [C++] ===== #include #include #include #include #include #include class CR2File { private: std::string filepath; std::vector data; std::string byteOrder; bool littleEndian; std::map properties; uint16_t getUint16(size_t offset) { uint16_t val; memcpy(&val, &data[offset], 2); if (!littleEndian) val = __builtin_bswap16(val); return val; } uint32_t getUint32(size_t offset) { uint32_t val; memcpy(&val, &data[offset], 4); if (!littleEndian) val = __builtin_bswap32(val); return val; } void parseHeader() { byteOrder = std::string(1, data[0]) + std::string(1, data[1]); littleEndian = (byteOrder == "II"); properties["TIFF Magic Number"] = std::to_string(getUint16(2)); properties["Offset to IFD0"] = std::to_string(getUint32(4)); properties["CR Signature"] = std::string(1, data[8]) + std::string(1, data[9]); properties["Major Version"] = std::to_string(data[10]); properties["Minor Version"] = std::to_string(data[11]); properties["Raw IFD Offset"] = std::to_string(getUint32(12)); // Parse IFD0 (example: Make) size_t offset = getUint32(4); uint16_t numEntries = getUint16(offset); offset += 2; for (uint16_t i = 0; i < numEntries; ++i) { uint16_t tag = getUint16(offset); if (tag == 0x010F) { // Make uint32_t count = getUint32(offset + 4); size_t valOffset = getUint32(offset + 8); std::string make; for (uint32_t j = 0; j < count - 1; ++j) { make += static_cast(data[valOffset + j]); } properties["Make"] = make; } offset += 12; } // Extend for other tags } public: CR2File(const std::string& fp) : filepath(fp) { std::ifstream file(filepath, std::ios::binary); if (file) { file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(reinterpret_cast(data.data()), size); parseHeader(); } } void printProperties() { for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } void write(const std::string& outputPath, const std::string& modifyTag = "", const std::string& newValue = "") { std::vector newData = data; // Implement modification (e.g., find tag and update) if (!modifyTag.empty()) { // Search and update logic } std::ofstream out(outputPath, std::ios::binary); out.write(reinterpret_cast(newData.data()), newData.size()); } }; // Usage: // int main() { // CR2File cr2("sample.cr2"); // cr2.printProperties(); // cr2.write("modified.cr2"); // return 0; // } // ===== end task-109 .CR2 ===== // ===== task-110 .CR3 [C++] ===== #include #include #include #include #include #include #include class CR3Parser { private: std::string filepath; std::vector data; size_t offset = 0; std::map> properties; struct Box { uint32_t size; std::string type; size_t data_offset; }; Box read_box() { uint32_t size; std::memcpy(&size, data.data() + offset, 4); size = __builtin_bswap32(size); std::string type(data.begin() + offset + 4, data.begin() + offset + 8); offset += 8; size_t data_offset = offset; if (size == 1) { uint64_t large_size; std::memcpy(&large_size, data.data() + offset, 8); large_size = __builtin_bswap64(large_size); offset += 8; size = static_cast(large_size); // Assume fits } Box box = {size, type, data_offset}; offset = data_offset + size - 8; return box; } std::string read_string(size_t len) { std::string str(data.begin() + offset, data.begin() + offset + len); offset += len; return str; } public: CR3Parser(const std::string& fp) : filepath(fp) { std::ifstream file(fp, std::ios::binary | std::ios::ate); std::streamsize file_size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(file_size); file.read(data.data(), file_size); } void parse() { while (offset < data.size()) { Box box = read_box(); properties[box.type]["size"] = std::to_string(box.size); if (box.type == "ftyp") { properties["ftyp"]["major_brand"] = read_string(4); uint32_t minor; std::memcpy(&minor, data.data() + offset, 4); minor = __builtin_bswap32(minor); properties["ftyp"]["minor_version"] = std::to_string(minor); offset += 4; } else if (box.type == "moov") { parse_moov(box.data_offset, box.size); } else if (box.type == "uuid") { std::string uuid = read_uuid(); parse_uuid(uuid, offset, box.size - 24); } else if (box.type == "mdat") { properties["mdat"]["data_size"] = std::to_string(box.size - 8); } } } std::string read_uuid() { char hex[33]; for (int i = 0; i < 16; ++i) { sprintf(hex + i*2, "%02x", static_cast(data[offset + i])); } offset += 16; return std::string(hex); } void parse_moov(size_t start, uint32_t size) { offset = start; size_t end = start + size - 8; properties["moov"] = {}; while (offset < end) { Box sub_box = read_box(); properties["moov"][sub_box.type] = std::to_string(sub_box.size); if (sub_box.type == "uuid") { std::string uuid = read_uuid(); properties["moov"]["uuid_" + uuid] = ""; parse_uuid(uuid, offset, sub_box.size - 24); } else if (sub_box.type == "mvhd") { uint32_t creation, timescale; std::memcpy(&creation, data.data() + offset + 4, 4); creation = __builtin_bswap32(creation); std::memcpy(×cale, data.data() + offset + 12, 4); timescale = __builtin_bswap32(timescale); properties["moov"]["mvhd_creation_time"] = std::to_string(creation); properties["moov"]["mvhd_timescale"] = std::to_string(timescale); } else if (sub_box.type == "trak") { parse_trak(offset, sub_box.size - 8); } else if (sub_box.type.substr(0, 3) == "CMT") { parse_tiff(offset, sub_box.size - 8); } else if (sub_box.type == "THMB") { uint16_t version, width, height; std::memcpy(&version, data.data() + offset, 2); version = __builtin_bswap16(version); std::memcpy(&width, data.data() + offset + 2, 2); width = __builtin_bswap16(width); std::memcpy(&height, data.data() + offset + 4, 2); height = __builtin_bswap16(height); properties["moov"]["THMB_version"] = std::to_string(version); properties["moov"]["THMB_width"] = std::to_string(width); properties["moov"]["THMB_height"] = std::to_string(height); } else if (sub_box.type == "CNCV") { properties["moov"]["CNCV_version"] = read_string(sub_box.size - 8); } } } void parse_uuid(const std::string& uuid, size_t start, uint32_t size) { offset = start; if (uuid == "eaf42b5e1c984b88b9fbb7dc406e4d16") { Box sub_box = read_box(); if (sub_box.type == "PRVW") { uint16_t width, height; std::memcpy(&width, data.data() + offset + 8, 2); width = __builtin_bswap16(width); std::memcpy(&height, data.data() + offset + 10, 2); height = __builtin_bswap16(height); properties["preview_width"] = std::to_string(width); properties["preview_height"] = std::to_string(height); } } } void parse_trak(size_t start, uint32_t size) { offset = start; size_t end = start + size; properties["trak"] = {}; while (offset < end) { Box sub_box = read_box(); if (sub_box.type == "tkhd") { uint32_t width_fixed, height_fixed; std::memcpy(&width_fixed, data.data() + offset + 76, 4); width_fixed = __builtin_bswap32(width_fixed); std::memcpy(&height_fixed, data.data() + offset + 80, 4); height_fixed = __builtin_bswap32(height_fixed); properties["trak"]["tkhd_width"] = std::to_string(width_fixed / 65536.0); properties["trak"]["tkhd_height"] = std::to_string(height_fixed / 65536.0); } else if (sub_box.type == "mdia") { parse_mdia(offset, sub_box.size - 8); } } } void parse_mdia(size_t start, uint32_t size) { // Extend } void parse_tiff(size_t start, uint32_t size) { offset = start; std::string byte_order = read_string(2); properties["tiff"]["byte_order"] = byte_order; // Extend IFD } void print_properties() { for (const auto& p : properties) { std::cout << p.first << ": " << std::endl; for (const auto& sp : p.second) { std::cout << " " << sp.first << ": " << sp.second << std::endl; } } } void write(const std::string& new_filepath) { std::ofstream out(new_filepath, std::ios::binary); out.write(data.data(), data.size()); // Extend to modify data vector } }; int main() { CR3Parser parser("example.CR3"); parser.parse(); parser.print_properties(); parser.write("modified.CR3"); return 0; } // ===== end task-110 .CR3 ===== // ===== task-111 .CRAFT [C++] ===== #include #include #include #include #include #include class CraftFileHandler { private: std::string filepath; std::map topLevel; std::vector>> parts; // parts[part][key or subblock][value or submap] public: CraftFileHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file\n"; return; } std::string line; std::map> currentPart; std::map currentSub; bool inBlock = false; std::string blockType = ""; while (std::getline(file, line)) { line.erase(0, line.find_first_not_of(" \t")); // Trim line.erase(line.find_last_not_of(" \t") + 1); if (line.empty()) continue; if (line == "PART") { if (!currentPart.empty()) parts.push_back(currentPart); currentPart.clear(); inBlock = true; blockType = "PART"; } else if (line == "EVENTS" || line == "ACTIONS" || line == "MODULE" || line == "RESOURCE" || line == "PARTDATA") { blockType = line; currentSub.clear(); inBlock = true; } else if (line == "{") { continue; } else if (line == "}") { if (!currentSub.empty() && !blockType.empty() && blockType != "PART") { currentPart[blockType.ToLower()] = currentSub; // Pseudo toLower } inBlock = false; currentSub.clear(); if (blockType == "PART") { parts.push_back(currentPart); currentPart.clear(); } blockType = ""; } else if (inBlock) { size_t pos = line.find('='); if (pos != std::string::npos) { std::string key = line.substr(0, pos); std::string value = line.substr(pos + 1); key.erase(key.find_last_not_of(" \t") + 1); value.erase(0, value.find_first_not_of(" \t")); if (!currentSub.empty()) { currentSub[key] = value; } else { currentPart[key] = {{"value", value}}; // Simplified } } } else { size_t pos = line.find('='); if (pos != std::string::npos) { std::string key = line.substr(0, pos); std::string value = line.substr(pos + 1); key.erase(key.find_last_not_of(" \t") + 1); value.erase(0, value.find_first_not_of(" \t")); topLevel[key] = value; } } } if (!currentPart.empty()) parts.push_back(currentPart); file.close(); } void printProperties() { std::cout << "topLevel: {\n"; for (const auto& kv : topLevel) { std::cout << " " << kv.first << ": " << kv.second << "\n"; } std::cout << "}\nparts: [\n"; for (const auto& part : parts) { std::cout << " {\n"; for (const auto& pkv : part) { if (pkv.second.size() == 1 && pkv.second.count("value")) { std::cout << " " << pkv.first << ": " << pkv.second.at("value") << "\n"; } else { std::cout << " " << pkv.first << ": {\n"; for (const auto& subkv : pkv.second) { std::cout << " " << subkv.first << ": " << subkv.second << "\n"; } std::cout << " }\n"; } } std::cout << " }\n"; } std::cout << "]\n"; } void write(const std::string& outputPath) { std::ofstream file(outputPath.empty() ? filepath : outputPath); if (!file.is_open()) { std::cerr << "Error opening file for write\n"; return; } for (const auto& kv : topLevel) { file << kv.first << " = " << kv.second << "\n"; } for (const auto& part : parts) { file << "PART\n{\n"; for (const auto& pkv : part) { if (pkv.second.size() == 1 && pkv.second.count("value")) { file << " " << pkv.first << " = " << pkv.second.at("value") << "\n"; } else { file << " " << pkv.first << "\n {\n"; for (const auto& subkv : pkv.second) { file << " " << subkv.first << " = " << subkv.second << "\n"; } file << " }\n"; } } file << "}\n"; } file.close(); } }; // Example usage: // int main() { // CraftFileHandler handler("example.craft"); // handler.read(); // handler.printProperties(); // handler.write("modified.craft"); // return 0; // } // ===== end task-111 .CRAFT ===== // ===== task-112 .CRAI [C++] ===== #include #include #include #include #include #include // Requires zlib library struct CRAIEntry { long long ref_id; long long start; long long span; long long container_offset; long long slice_offset; long long slice_size; }; class CRAIHandler { private: std::vector entries; std::string readGzippedFile(const std::string& filepath) { std::ifstream file(filepath, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file: " + filepath); } std::vector compressed(std::istreambuf_iterator(file), {}); file.close(); z_stream zs; memset(&zs, 0, sizeof(zs)); if (inflateInit2(&zs, 16 + MAX_WBITS) != Z_OK) { throw std::runtime_error("inflateInit failed"); } zs.next_in = reinterpret_cast(compressed.data()); zs.avail_in = compressed.size(); std::string decompressed; char buffer[1024]; int ret; do { zs.next_out = reinterpret_cast(buffer); zs.avail_out = sizeof(buffer); ret = inflate(&zs, 0); if (decompressed.size() < zs.total_out) { decompressed.append(buffer, zs.total_out - decompressed.size()); } } while (ret == Z_OK); inflateEnd(&zs); if (ret != Z_STREAM_END) { throw std::runtime_error("inflate failed"); } return decompressed; } void writeGzippedFile(const std::string& filepath, const std::string& data) { std::ofstream file(filepath, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file for writing: " + filepath); } z_stream zs; memset(&zs, 0, sizeof(zs)); if (deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 | 16, 8, Z_DEFAULT_STRATEGY) != Z_OK) { throw std::runtime_error("deflateInit failed"); } zs.next_in = reinterpret_cast(const_cast(data.data())); zs.avail_in = data.size(); char buffer[1024]; int ret; do { zs.next_out = reinterpret_cast(buffer); zs.avail_out = sizeof(buffer); ret = deflate(&zs, Z_FINISH); file.write(buffer, sizeof(buffer) - zs.avail_out); } while (ret == Z_OK); deflateEnd(&zs); if (ret != Z_STREAM_END) { throw std::runtime_error("deflate failed"); } file.close(); } public: CRAIHandler(const std::string& filepath = "") { if (!filepath.empty()) { read(filepath); } } void read(const std::string& filepath) { entries.clear(); std::string decompressed = readGzippedFile(filepath); std::istringstream iss(decompressed); std::string line; while (std::getline(iss, line)) { std::istringstream lineStream(line); CRAIEntry entry; char delim; lineStream >> entry.ref_id >> delim >> entry.start >> delim >> entry.span >> delim >> entry.container_offset >> delim >> entry.slice_offset >> delim >> entry.slice_size; if (lineStream) { entries.push_back(entry); } } std::cout << "Read " << entries.size() << " entries from " << filepath << std::endl; } void decode() { printProperties(); } void write(const std::string& filepath) { std::ostringstream oss; for (const auto& entry : entries) { oss << entry.ref_id << "\t" << entry.start << "\t" << entry.span << "\t" << entry.container_offset << "\t" << entry.slice_offset << "\t" << entry.slice_size << "\n"; } writeGzippedFile(filepath, oss.str()); std::cout << "Wrote " << entries.size() << " entries to " << filepath << std::endl; } void printProperties() { for (size_t i = 0; i < entries.size(); ++i) { const auto& entry = entries[i]; std::cout << "Entry " << (i + 1) << ":" << std::endl; std::cout << " Reference sequence ID: " << entry.ref_id << std::endl; std::cout << " Alignment start: " << entry.start << std::endl; std::cout << " Alignment span: " << entry.span << std::endl; std::cout << " Absolute byte offset of container header: " << entry.container_offset << std::endl; std::cout << " Relative byte offset of slice header block: " << entry.slice_offset << std::endl; std::cout << " Slice size in bytes: " << entry.slice_size << std::endl; std::cout << std::endl; } } }; // Example usage: // int main() { // CRAIHandler handler("example.crai"); // handler.decode(); // handler.write("output.crai"); // return 0; // } // ===== end task-112 .CRAI ===== // ===== task-113 .CRT [C] ===== #include #include #include #include #include // For big-endian conversions if needed; assume host is little-endian typedef struct { char signature[17]; uint32_t header_length; uint16_t version; uint16_t hardware_type; uint8_t exrom; uint8_t game; uint8_t revision; uint8_t reserved[5]; char name[33]; } CRTHeader; typedef struct ChipPacket { char chip_sig[5]; uint32_t packet_len; uint16_t chip_type; uint16_t bank; uint16_t load_addr; uint16_t image_size; uint8_t *data; struct ChipPacket *next; } ChipPacket; typedef struct { CRTHeader header; ChipPacket *chips; } CRTFile; void read_crt(CRTFile *crt, const char *filepath) { FILE *f = fopen(filepath, "rb"); if (!f) { perror("Failed to open file"); exit(1); } fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); int offset = 0; memcpy(crt->header.signature, data + offset, 16); crt->header.signature[16] = '\0'; offset += 16; crt->header.header_length = be32toh(*(uint32_t*)(data + offset)); offset += 4; crt->header.version = be16toh(*(uint16_t*)(data + offset)); offset += 2; crt->header.hardware_type = be16toh(*(uint16_t*)(data + offset)); offset += 2; crt->header.exrom = data[offset++]; crt->header.game = data[offset++]; crt->header.revision = data[offset++]; memcpy(crt->header.reserved, data + offset, 5); offset += 5; memcpy(crt->header.name, data + offset, 32); crt->header.name[32] = '\0'; for (int i = 31; i >= 0; i--) if (crt->header.name[i] == '\0') crt->header.name[i] = '\0'; else break; offset += 32; crt->chips = NULL; ChipPacket *last = NULL; int chip_idx = 1; while (offset < size) { ChipPacket *chip = malloc(sizeof(ChipPacket)); memcpy(chip->chip_sig, data + offset, 4); chip->chip_sig[4] = '\0'; if (strcmp(chip->chip_sig, "CHIP") != 0) { free(chip); break; } offset += 4; chip->packet_len = be32toh(*(uint32_t*)(data + offset)); offset += 4; chip->chip_type = be16toh(*(uint16_t*)(data + offset)); offset += 2; chip->bank = be16toh(*(uint16_t*)(data + offset)); offset += 2; chip->load_addr = be16toh(*(uint16_t*)(data + offset)); offset += 2; chip->image_size = be16toh(*(uint16_t*)(data + offset)); offset += 2; chip->data = malloc(chip->image_size); memcpy(chip->data, data + offset, chip->image_size); offset += chip->image_size; chip->next = NULL; if (!crt->chips) crt->chips = chip; else last->next = chip; last = chip; } free(data); } void print_properties(const CRTFile *crt) { printf("Signature: %s\n", crt->header.signature); printf("Header Length: %u\n", crt->header.header_length); printf("Version: %u\n", crt->header.version); printf("Hardware Type: %u\n", crt->header.hardware_type); printf("EXROM Status: %u\n", crt->header.exrom); printf("GAME Status: %u\n", crt->header.game); printf("Hardware Revision: %u\n", crt->header.revision); printf("Reserved: "); for (int i = 0; i < 5; i++) printf("%02X ", crt->header.reserved[i]); printf("\n"); printf("Name: %s\n", crt->header.name); ChipPacket *chip = crt->chips; int i = 1; while (chip) { printf("\nCHIP Packet %d:\n", i++); printf(" Signature: %s\n", chip->chip_sig); printf(" Packet Length: %u\n", chip->packet_len); printf(" Chip Type: %u\n", chip->chip_type); printf(" Bank Number: %u\n", chip->bank); printf(" Load Address: 0x%04X\n", chip->load_addr); printf(" Image Size: %u\n", chip->image_size); printf(" Data: [Binary data, %u bytes]\n", chip->image_size); chip = chip->next; } } void write_crt(const CRTFile *crt, const char *filepath) { FILE *f = fopen(filepath, "wb"); if (!f) { perror("Failed to write file"); exit(1); } char sig[16]; memset(sig, ' ', 16); strncpy(sig, crt->header.signature, 16); fwrite(sig, 1, 16, f); uint32_t hl = htobe32(crt->header.header_length); fwrite(&hl, 4, 1, f); uint16_t ver = htobe16(crt->header.version); fwrite(&ver, 2, 1, f); uint16_t ht = htobe16(crt->header.hardware_type); fwrite(&ht, 2, 1, f); fwrite(&crt->header.exrom, 1, 1, f); fwrite(&crt->header.game, 1, 1, f); fwrite(&crt->header.revision, 1, 1, f); fwrite(crt->header.reserved, 1, 5, f); char name[32]; memset(name, '\0', 32); strncpy(name, crt->header.name, 32); fwrite(name, 1, 32, f); ChipPacket *chip = crt->chips; while (chip) { fwrite(chip->chip_sig, 1, 4, f); uint32_t pl = htobe32(chip->packet_len); fwrite(&pl, 4, 1, f); uint16_t ct = htobe16(chip->chip_type); fwrite(&ct, 2, 1, f); uint16_t bk = htobe16(chip->bank); fwrite(&bk, 2, 1, f); uint16_t la = htobe16(chip->load_addr); fwrite(&la, 2, 1, f); uint16_t is = htobe16(chip->image_size); fwrite(&is, 2, 1, f); fwrite(chip->data, 1, chip->image_size, f); chip = chip->next; } fclose(f); } void free_crt(CRTFile *crt) { ChipPacket *chip = crt->chips; while (chip) { ChipPacket *next = chip->next; free(chip->data); free(chip); chip = next; } } // Example usage: int main(int argc, char **argv) { CRTFile crt; read_crt(&crt, argv[1]); print_properties(&crt); write_crt(&crt, "modified.crt"); free_crt(&crt); return 0; } // ===== end task-113 .CRT ===== // ===== task-114 .CS [C++] ===== #include #include #include #include #include #include class CSFile { private: std::string filename; std::vector data; std::vector properties; uint8_t readUint8(size_t& pos) { return data[pos++]; } uint16_t readUint16LE(size_t& pos) { uint16_t val = (data[pos + 1] << 8) | data[pos]; pos += 2; return val; } int32_t readInt32LE(size_t& pos) { int32_t val = (data[pos + 3] << 24) | (data[pos + 2] << 16) | (data[pos + 1] << 8) | data[pos]; pos += 4; return val; } uint32_t readUint32LE(size_t& pos) { uint32_t val = (data[pos + 3] << 24) | (data[pos + 2] << 16) | (data[pos + 1] << 8) | data[pos]; pos += 4; return val; } std::string readString(size_t& pos, size_t length) { std::string str(reinterpret_cast(&data[pos]), length); pos += length; str.erase(str.find('\0')); return str; } int32_t parseJump(size_t& pos) { uint16_t opcode = readUint16LE(pos); if (opcode != 0x0002) throw std::runtime_error("Invalid jump opcode"); uint8_t type = readUint8(pos); if (type != 0x01) throw std::runtime_error("Invalid jump type"); return readInt32LE(pos); } public: CSFile(const std::string& fn) : filename(fn) { std::ifstream file(filename, std::ios::binary | std::ios::ate); size_t size = file.tellg(); data.resize(size); file.seekg(0); file.read(reinterpret_cast(data.data()), size); size_t pos = 0; parse(pos); } void parse(size_t& pos) { // First chunk int32_t offset = parseJump(pos); pos = offset; char targetGame = readUint8(pos); properties.push_back("targetGame: " + std::string(1, targetGame)); // Second chunk: Models offset = parseJump(pos); pos = offset; uint8_t chunkIndex = readUint8(pos); if (chunkIndex != 0) throw std::runtime_error("Invalid chunk 0"); uint32_t numModels = readUint32LE(pos); properties.push_back("numModels: " + std::to_string(numModels)); std::string modelNamesStr = "modelNames: ["; for (uint32_t i = 0; i < numModels; ++i) { std::string name = readString(pos, 24); modelNamesStr += name + ", "; } if (numModels > 0) modelNamesStr.erase(modelNamesStr.size() - 2); modelNamesStr += "]"; properties.push_back(modelNamesStr); // Third chunk: Missions offset = parseJump(pos); pos = offset; chunkIndex = readUint8(pos); if (chunkIndex != 1) throw std::runtime_error("Invalid chunk 1"); uint32_t mainSize = readUint32LE(pos); properties.push_back("mainSize: " + std::to_string(mainSize)); uint32_t largestMissionSize = readUint32LE(pos); properties.push_back("largestMissionSize: " + std::to_string(largestMissionSize)); uint16_t numMissions = readUint16LE(pos); properties.push_back("numMissions: " + std::to_string(numMissions)); uint16_t numExclusive = readUint16LE(pos); properties.push_back("numExclusiveMissions: " + std::to_string(numExclusive)); uint32_t largestLocals = readUint32LE(pos); properties.push_back("largestMissionLocals: " + std::to_string(largestLocals)); std::string offsetsStr = "missionOffsets: ["; for (uint16_t i = 0; i < numMissions; ++i) { uint32_t off = readUint32LE(pos); offsetsStr += std::to_string(off) + ", "; } if (numMissions > 0) offsetsStr.erase(offsetsStr.size() - 2); offsetsStr += "]"; properties.push_back(offsetsStr); // Fourth chunk: Streamed offset = parseJump(pos); pos = offset; chunkIndex = readUint8(pos); if (chunkIndex != 2) throw std::runtime_error("Invalid chunk 2"); uint32_t largestStreamed = readUint32LE(pos); properties.push_back("largestStreamedSize: " + std::to_string(largestStreamed)); uint32_t numStreamed = readUint32LE(pos); properties.push_back("numStreamed: " + std::to_string(numStreamed)); std::string streamedStr = "streamedDetails: ["; for (uint32_t i = 0; i < numStreamed; ++i) { std::string name = readString(pos, 20); uint32_t off = readUint32LE(pos); uint32_t size = readUint32LE(pos); streamedStr += "{" + name + ", offset: " + std::to_string(off) + ", size: " + std::to_string(size) + "}, "; } if (numStreamed > 0) streamedStr.erase(streamedStr.size() - 2); streamedStr += "]"; properties.push_back(streamedStr); // Fifth chunk: Unknown offset = parseJump(pos); pos = offset; chunkIndex = readUint8(pos); if (chunkIndex != 3) throw std::runtime_error("Invalid chunk 3"); uint32_t unknown = readUint32LE(pos); properties.push_back("unknown: " + std::to_string(unknown)); // Sixth chunk: Global and build offset = parseJump(pos); pos = offset; chunkIndex = readUint8(pos); if (chunkIndex != 4) throw std::runtime_error("Invalid chunk 4"); uint32_t globalSize = readUint32LE(pos); properties.push_back("globalVarSize: " + std::to_string(globalSize)); uint32_t build = readUint32LE(pos); properties.push_back("buildNumber: " + std::to_string(build)); } void printProperties() { for (const auto& prop : properties) { std::cout << prop << std::endl; } } void write(const std::string& newFilename) { std::ofstream file(newFilename.empty() ? filename : newFilename, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); // Modify data vector for changes before writing } }; // Example usage // int main() { // try { // CSFile cs("example.cs"); // cs.printProperties(); // cs.write("modified.cs"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-114 .CS ===== // ===== task-115 .CSO [C] ===== #include #include #include #include // for deflate typedef struct { char magic[4]; u_int32_t header_size; u_int64_t uncompressed_size; u_int32_t block_size; u_int8_t version; u_int8_t index_shift; u_int16_t unused; u_int32_t *index_table; u_int8_t **data_blocks; int num_blocks; } CSOFile; void cso_read(CSOFile *cso, const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) { perror("fopen"); exit(1); } u_int8_t header[24]; fread(header, 1, 24, f); memcpy(cso->magic, header, 4); if (strncmp(cso->magic, "CISO", 4) != 0) { fprintf(stderr, "Not a CSO file\n"); exit(1); } memcpy(&cso->header_size, header + 4, 4); if (cso->version == 1) { memcpy(&cso->uncompressed_size, header + 8, 4); memcpy(&cso->block_size, header + 16, 4); } else { memcpy(&cso->uncompressed_size, header + 8, 8); memcpy(&cso->block_size, header + 16, 4); } cso->version = header[20]; cso->index_shift = header[21]; memcpy(&cso->unused, header + 22, 2); cso->num_blocks = (cso->uncompressed_size + cso->block_size - 1) / cso->block_size; cso->index_table = malloc((cso->num_blocks + 1) * sizeof(u_int32_t)); fread(cso->index_table, sizeof(u_int32_t), cso->num_blocks + 1, f); cso->data_blocks = malloc(cso->num_blocks * sizeof(u_int8_t *)); for (int i = 0; i < cso->num_blocks; i++) { u_int32_t pos = (cso->index_table[i] & 0x7FFFFFFF) << cso->index_shift; u_int32_t next_pos = (cso->index_table[i+1] & 0x7FFFFFFF) << cso->index_shift; u_int32_t size = next_pos - pos; u_int8_t *data = malloc(size); fseek(f, pos, SEEK_SET); fread(data, 1, size, f); if ((cso->index_table[i] & 0x80000000) == 0) { u_int8_t *decompressed = malloc(cso->block_size); uLongf destLen = cso->block_size; uncompress(decompressed, &destLen, data, size); free(data); data = decompressed; } cso->data_blocks[i] = data; } fclose(f); } void cso_print_properties(CSOFile *cso) { printf("Magic: %.4s\n", cso->magic); printf("Header Size: %u\n", cso->header_size); printf("Uncompressed Size: %llu\n", cso->uncompressed_size); printf("Block Size: %u\n", cso->block_size); printf("Version: %u\n", cso->version); printf("Index Shift: %u\n", cso->index_shift); printf("Unused: %u\n", cso->unused); printf("Index Table (first 5): %u, %u, %u, %u, %u\n", cso->index_table[0], cso->index_table[1], cso->index_table[2], cso->index_table[3], cso->index_table[4]); } void cso_write(CSOFile *cso, const char *filename, const char *original_iso) { FILE *in = fopen(original_iso, "rb"); fseek(in, 0, SEEK_END); cso->uncompressed_size = ftell(in); fseek(in, 0, SEEK_SET); u_int8_t *data = malloc(cso->uncompressed_size); fread(data, 1, cso->uncompressed_size, in); fclose(in); cso->num_blocks = (cso->uncompressed_size + cso->block_size - 1) / cso->block_size; cso->index_table = malloc((cso->num_blocks + 1) * sizeof(u_int32_t)); cso->data_blocks = malloc(cso->num_blocks * sizeof(u_int8_t *)); u_int32_t pos = cso->header_size + (cso->num_blocks + 1) * 4; cso->index_table[0] = pos >> cso->index_shift; FILE *out = fopen(filename, "wb"); // Write header fwrite(cso->magic, 1, 4, out); fwrite(&cso->header_size, 4, 1, out); if (cso->version == 1) { u_int32_t size32 = (u_int32_t) cso->uncompressed_size; fwrite(&size32, 4, 1, out); u_int32_t zero = 0; fwrite(&zero, 4, 1, out); } else { fwrite(&cso->uncompressed_size, 8, 1, out); } fwrite(&cso->block_size, 4, 1, out); fwrite(&cso->version, 1, 1, out); fwrite(&cso->index_shift, 1, 1, out); fwrite(&cso->unused, 2, 1, out); // Placeholder index fseek(out, cso->header_size, SEEK_SET); for (int i = 0; i <= cso->num_blocks; i++) { u_int32_t zero = 0; fwrite(&zero, 4, 1, out); } // Compress for (int i = 0; i < cso->num_blocks; i++) { u_int32_t start = i * cso->block_size; u_int32_t len = (u_int32_t) min(cso->block_size, cso->uncompressed_size - start); u_int8_t *block = malloc(len); memcpy(block, data + start, len); u_int8_t *compressed = malloc(len + 100); // extra for header uLongf compLen = len + 100; int ret = compress2(compressed, &compLen, block, len, 9); if (ret != Z_OK || compLen >= len) { cso->data_blocks[i] = block; cso->index_table[i] = (pos >> cso->index_shift) | 0x80000000; fseek(out, pos, SEEK_SET); fwrite(block, 1, len, out); pos += len; } else { cso->data_blocks[i] = malloc(compLen); memcpy(cso->data_blocks[i], compressed, compLen); cso->index_table[i] = pos >> cso->index_shift; fseek(out, pos, SEEK_SET); fwrite(compressed, 1, compLen, out); pos += compLen; free(block); } free(compressed); } cso->index_table[cso->num_blocks] = pos >> cso->index_shift; // Write index fseek(out, cso->header_size, SEEK_SET); for (int i = 0; i <= cso->num_blocks; i++) { fwrite(&cso->index_table[i], 4, 1, out); } fclose(out); free(data); } int main() { CSOFile cso = {0}; cso_read(&cso, "sample.cso"); cso_print_properties(&cso); // To write cso_write(&cso, "new.cso", "original.iso"); // Free memory free(cso.index_table); for (int i = 0; i < cso.num_blocks; i++) { free(cso.data_blocks[i]); } free(cso.data_blocks); return 0; } // ===== end task-115 .CSO ===== // ===== task-116 .CSPROJ [C++] ===== #include #include #include // Assume pugixml.hpp is included/compiled with this class CSProjHandler { private: std::string filePath; pugi::xml_document doc; public: CSProjHandler(const std::string& path) : filePath(path) { load(); } void load() { if (filePath.substr(filePath.find_last_of(".") + 1) != "csproj") { throw std::invalid_argument("Invalid .csproj file path."); } pugi::xml_parse_result result = doc.load_file(filePath.c_str()); if (!result) { throw std::runtime_error("Failed to parse XML."); } } void printProperties() { std::cout << "Extracted Properties:" << std::endl; for (pugi::xml_node propGroup : doc.child("Project").children("PropertyGroup")) { for (pugi::xml_node prop : propGroup.children()) { std::cout << prop.name() << ": " << prop.child_value() << std::endl; } } } void setProperty(const std::string& name, const std::string& value) { pugi::xml_node propGroup = doc.child("Project").child("PropertyGroup"); if (!propGroup) { propGroup = doc.child("Project").append_child("PropertyGroup"); } pugi::xml_node prop = propGroup.child(name.c_str()); if (!prop) { prop = propGroup.append_child(name.c_str()); } prop.text().set(value.c_str()); } void save(const std::string& outputPath = "") { std::string path = outputPath.empty() ? filePath : outputPath; doc.save_file(path.c_str(), " ", pugi::format_default | pugi::format_write_bom, pugi::encoding_utf8); } }; // Example usage: // int main() { // try { // CSProjHandler handler("path/to/sample.csproj"); // handler.printProperties(); // handler.setProperty("NewProperty", "Value"); // handler.save(); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-116 .CSPROJ ===== // ===== task-117 .CSS [C++] ===== #include #include #include #include #include #include class CSSFileHandler { private: std::string filepath; public: CSSFileHandler(const std::string& fp) : filepath(fp) { if (filepath.substr(filepath.find_last_of(".") + 1) != "css") { throw std::invalid_argument("File must have .css extension"); } } std::string read() { // Read as text (UTF-8 assumed) std::ifstream file(filepath); if (!file) { throw std::runtime_error("Failed to open file for reading"); } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); return content; } void write(const std::string& content) { std::ofstream file(filepath); if (!file) { throw std::runtime_error("Failed to open file for writing"); } file << content; } void printProperties() { struct stat stats; if (stat(filepath.c_str(), &stats) != 0) { throw std::runtime_error("Failed to get file stats"); } std::cout << "Filename: " << filepath.substr(filepath.find_last_of("/\\") + 1) << std::endl; std::cout << "Size (bytes): " << stats.st_size << std::endl; std::cout << "Creation time: N/A (use st_ctime on some systems: " << std::ctime(&stats.st_ctime) << ")" << std::endl; std::cout << "Last modification time: " << std::ctime(&stats.st_mtime) << std::endl; std::cout << "Last access time: " << std::ctime(&stats.st_atime) << std::endl; std::cout << "Mode (permissions): " << std::oct << stats.st_mode << std::endl; std::cout << "Owner user ID (UID): " << stats.st_uid << std::endl; std::cout << "Group ID (GID): " << stats.st_gid << std::endl; } }; // Example usage: // int main() { // try { // CSSFileHandler handler("example.css"); // std::string content = handler.read(); // handler.write("body { color: red; }"); // handler.printProperties(); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-117 .CSS ===== // ===== task-118 .CSV [C] ===== #include #include #include #define MAX_LINES 1000 #define MAX_COLS 100 #define MAX_FIELD 1024 typedef struct { char *filepath; char *data[MAX_LINES][MAX_COLS]; // Simple 2D array for data int num_rows; int num_cols; struct { char *mime_type; char *extension; char *magic_number; char *mac_type; char delimiter; char *quote_char; char *escaping; char *line_term; char *header; char *charset; char *field_consist; } properties; } CSVHandler; void init_properties(CSVHandler *handler) { handler->properties.mime_type = "text/csv"; handler->properties.extension = ".csv"; handler->properties.magic_number = "None"; handler->properties.mac_type = "TEXT"; handler->properties.escaping = "Double quote (\")"; handler->properties.charset = "UTF-8 (assumed)"; handler->properties.field_consist = "Assumed consistent"; handler->properties.header = "Unknown"; handler->properties.quote_char = "\""; handler->num_rows = 0; handler->num_cols = 0; } char *read_file_as_string(const char *filepath) { FILE *file = fopen(filepath, "r"); if (!file) return NULL; fseek(file, 0, SEEK_END); long length = ftell(file); fseek(file, 0, SEEK_SET); char *buffer = malloc(length + 1); fread(buffer, 1, length, file); buffer[length] = '\0'; fclose(file); return buffer; } void detect_properties(CSVHandler *handler, char *content) { // Detect line terminator if (strstr(content, "\r\n")) { handler->properties.line_term = "CRLF"; } else { handler->properties.line_term = "LF"; } // Detect delimiter (simple count on first 5 lines) char delims[] = {',', ';', '\t', '|'}; int max_count = 0; char detected = ','; char *line = strtok(content, "\r\n\n"); int line_count = 0; while (line && line_count < 5) { for (int i = 0; i < 4; i++) { char d = delims[i]; int count = 0; for (char *p = line; *p; p++) if (*p == d) count++; if (count > max_count) { max_count = count; detected = d; } } line = strtok(NULL, "\r\n\n"); line_count++; } handler->delimiter = detected; } void read_csv(CSVHandler *handler) { char *content = read_file_as_string(handler->filepath); if (!content) { printf("Error reading file\n"); return; } detect_properties(handler, content); // Parse (simple, assumes no nested quotes for brevity) char *line = strtok(content, handler->properties.line_term == "CRLF" ? "\r\n" : "\n"); while (line && handler->num_rows < MAX_LINES) { char field[MAX_FIELD]; int field_idx = 0; int col = 0; int in_quotes = 0; for (char *p = line; *p && col < MAX_COLS; p++) { if (*p == '"' && !in_quotes) { in_quotes = 1; } else if (*p == '"' && in_quotes) { in_quotes = 0; } else if (*p == handler->delimiter && !in_quotes) { field[field_idx] = '\0'; handler->data[handler->num_rows][col] = strdup(field); field_idx = 0; col++; } else { field[field_idx++] = *p; } } field[field_idx] = '\0'; handler->data[handler->num_rows][col] = strdup(field); handler->num_cols = col + 1; // Assume consistent handler->num_rows++; line = strtok(NULL, handler->properties.line_term == "CRLF" ? "\r\n" : "\n"); } free(content); } void print_properties(CSVHandler *handler) { printf("MIME Type: %s\n", handler->properties.mime_type); printf("File Extension: %s\n", handler->properties.extension); printf("Magic Number: %s\n", handler->properties.magic_number); printf("Macintosh File Type Code: %s\n", handler->properties.mac_type); printf("Delimiter: %c\n", handler->delimiter); printf("Quote Character: %s\n", handler->properties.quote_char); printf("Escaping Method: %s\n", handler->properties.escaping); printf("Line Terminator: %s\n", handler->properties.line_term); printf("Header: %s\n", handler->properties.header); printf("Character Set: %s\n", handler->properties.charset); printf("Field Consistency: %s\n", handler->properties.field_consist); printf("Number of Rows: %d\n", handler->num_rows); printf("Number of Columns: %d\n", handler->num_cols); } void write_csv(CSVHandler *handler, const char *new_filepath) { char *path = new_filepath ? (char*)new_filepath : handler->filepath; FILE *file = fopen(path, "w"); if (!file) return; char *line_term = strcmp(handler->properties.line_term, "CRLF") == 0 ? "\r\n" : "\n"; for (int i = 0; i < handler->num_rows; i++) { for (int j = 0; j < handler->num_cols; j++) { fprintf(file, "\"%s\"", handler->data[i][j]); // Simple, no escape for brevity if (j < handler->num_cols - 1) fprintf(file, "%c", handler->delimiter); } fprintf(file, "%s", line_term); } fclose(file); } int main() { CSVHandler handler; handler.filepath = "example.csv"; init_properties(&handler); read_csv(&handler); print_properties(&handler); write_csv(&handler, "output.csv"); // Free memory (omitted for brevity) return 0; } // ===== end task-118 .CSV ===== // ===== task-119 .CUBE [C] ===== #include #include #include #include typedef struct { uint32_t ident; char title[123]; // Null-terminated uint16_t allowedSerials[8]; uint8_t pcByteOrder; uint8_t isSecured; uint32_t crc32; uint8_t key[16]; int32_t sizeOfItem; int32_t sizeOfPoint; int32_t hdrItems; int32_t maxPts; float left, top, right, bottom; float maxWidth, maxHeight; float loLaScale; int32_t headerOffset; int32_t dataOffset; int32_t alignment; } CubHeader; typedef struct { float left, top, right, bottom; uint8_t style; uint8_t altStyle; int16_t minAlt, maxAlt; int32_t data; int32_t timeOut; char name[9]; // Null-terminated char radio[9]; // Null-terminated } CubItem; typedef struct { float longitude, latitude; } CubPoint; typedef struct { CubHeader header; CubItem* items; CubPoint* points; } CubFile; void readCubFile(CubFile* cf, const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) { perror("Failed to open file"); return; } fseek(f, 0, SEEK_END); long fileSize = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* buffer = malloc(fileSize); fread(buffer, 1, fileSize, f); fclose(f); uint8_t* ptr = buffer; // Parse Header memcpy(&cf->header.ident, ptr, 4); ptr += 4; memcpy(cf->header.title, ptr, 122); cf->header.title[122] = '\0'; ptr += 122; memcpy(cf->header.allowedSerials, ptr, 16); ptr += 16; cf->header.pcByteOrder = *ptr; ptr += 1; cf->header.isSecured = *ptr; ptr += 1; if (cf->header.isSecured != 0) { printf("Warning: File is encrypted; parsing may fail.\n"); } memcpy(&cf->header.crc32, ptr, 4); ptr += 4; memcpy(cf->header.key, ptr, 16); ptr += 16; memcpy(&cf->header.sizeOfItem, ptr, 4); ptr += 4; memcpy(&cf->header.sizeOfPoint, ptr, 4); ptr += 4; memcpy(&cf->header.hdrItems, ptr, 4); ptr += 4; memcpy(&cf->header.maxPts, ptr, 4); ptr += 4; memcpy(&cf->header.left, ptr, 4); ptr += 4; memcpy(&cf->header.top, ptr, 4); ptr += 4; memcpy(&cf->header.right, ptr, 4); ptr += 4; memcpy(&cf->header.bottom, ptr, 4); ptr += 4; memcpy(&cf->header.maxWidth, ptr, 4); ptr += 4; memcpy(&cf->header.maxHeight, ptr, 4); ptr += 4; memcpy(&cf->header.loLaScale, ptr, 4); ptr += 4; memcpy(&cf->header.headerOffset, ptr, 4); ptr += 4; memcpy(&cf->header.dataOffset, ptr, 4); ptr += 4; memcpy(&cf->header.alignment, ptr, 4); ptr += 4; // Parse Items cf->items = malloc(cf->header.hdrItems * sizeof(CubItem)); ptr = buffer + cf->header.headerOffset; for (int i = 0; i < cf->header.hdrItems; i++) { memcpy(&cf->items[i].left, ptr, 4); ptr += 4; memcpy(&cf->items[i].top, ptr, 4); ptr += 4; memcpy(&cf->items[i].right, ptr, 4); ptr += 4; memcpy(&cf->items[i].bottom, ptr, 4); ptr += 4; cf->items[i].style = *ptr; ptr += 1; cf->items[i].altStyle = *ptr; ptr += 1; memcpy(&cf->items[i].minAlt, ptr, 2); ptr += 2; memcpy(&cf->items[i].maxAlt, ptr, 2); ptr += 2; memcpy(&cf->items[i].data, ptr, 4); ptr += 4; memcpy(&cf->items[i].timeOut, ptr, 4); ptr += 4; memcpy(cf->items[i].name, ptr, 8); cf->items[i].name[8] = '\0'; ptr += 8; memcpy(cf->items[i].radio, ptr, 8); cf->items[i].radio[8] = '\0'; ptr += 8; ptr += (cf->header.sizeOfItem - 42); } // Parse Points cf->points = malloc(cf->header.maxPts * sizeof(CubPoint)); ptr = buffer + cf->header.dataOffset; int pointCount = 0; while (ptr - buffer + cf->header.sizeOfPoint <= fileSize && pointCount < cf->header.maxPts) { memcpy(&cf->points[pointCount].longitude, ptr, 4); ptr += 4; memcpy(&cf->points[pointCount].latitude, ptr, 4); ptr += 4; ptr += (cf->header.sizeOfPoint - 8); pointCount++; } cf->header.maxPts = pointCount; // Update actual count free(buffer); } void printProperties(const CubFile* cf) { printf("CubHeader Properties:\n"); printf("Ident: %x\n", cf->header.ident); printf("Title: %s\n", cf->header.title); printf("AllowedSerials: ["); for (int i = 0; i < 8; i++) printf("%u ", cf->header.allowedSerials[i]); printf("]\n"); printf("PcByteOrder: %u\n", cf->header.pcByteOrder); printf("IsSecured: %u\n", cf->header.isSecured); printf("Crc32: %u\n", cf->header.crc32); printf("Key: ["); for (int i = 0; i < 16; i++) printf("%u ", cf->header.key[i]); printf("]\n"); printf("SizeOfItem: %d\n", cf->header.sizeOfItem); printf("SizeOfPoint: %d\n", cf->header.sizeOfPoint); printf("HdrItems: %d\n", cf->header.hdrItems); printf("MaxPts: %d\n", cf->header.maxPts); printf("Left: %f\n", cf->header.left); printf("Top: %f\n", cf->header.top); printf("Right: %f\n", cf->header.right); printf("Bottom: %f\n", cf->header.bottom); printf("MaxWidth: %f\n", cf->header.maxWidth); printf("MaxHeight: %f\n", cf->header.maxHeight); printf("LoLaScale: %f\n", cf->header.loLaScale); printf("HeaderOffset: %d\n", cf->header.headerOffset); printf("DataOffset: %d\n", cf->header.dataOffset); printf("Alignment: %d\n", cf->header.alignment); printf("\nCubItem Properties:\n"); for (int i = 0; i < cf->header.hdrItems; i++) { printf("Item %d:\n", i + 1); printf(" Left: %f\n", cf->items[i].left); printf(" Top: %f\n", cf->items[i].top); printf(" Right: %f\n", cf->items[i].right); printf(" Bottom: %f\n", cf->items[i].bottom); printf(" Style: %u\n", cf->items[i].style); printf(" AltStyle: %u\n", cf->items[i].altStyle); printf(" MinAlt: %d\n", cf->items[i].minAlt); printf(" MaxAlt: %d\n", cf->items[i].maxAlt); printf(" Data: %d\n", cf->items[i].data); printf(" TimeOut: %d\n", cf->items[i].timeOut); printf(" Name: %s\n", cf->items[i].name); printf(" Radio: %s\n", cf->items[i].radio); } printf("\nCubPoint Properties:\n"); for (int i = 0; i < cf->header.maxPts; i++) { printf("Point %d: Longitude=%f, Latitude=%f\n", i + 1, cf->points[i].longitude, cf->points[i].latitude); } } void writeCubFile(const CubFile* cf, const char* filename) { FILE* f = fopen(filename, "wb"); if (!f) { perror("Failed to open file for writing"); return; } // Write Header fwrite(&cf->header.ident, 4, 1, f); fwrite(cf->header.title, 122, 1, f); fwrite(cf->header.allowedSerials, 2, 8, f); fwrite(&cf->header.pcByteOrder, 1, 1, f); fwrite(&cf->header.isSecured, 1, 1, f); fwrite(&cf->header.crc32, 4, 1, f); fwrite(cf->header.key, 1, 16, f); fwrite(&cf->header.sizeOfItem, 4, 1, f); fwrite(&cf->header.sizeOfPoint, 4, 1, f); fwrite(&cf->header.hdrItems, 4, 1, f); fwrite(&cf->header.maxPts, 4, 1, f); fwrite(&cf->header.left, 4, 1, f); fwrite(&cf->header.top, 4, 1, f); fwrite(&cf->header.right, 4, 1, f); fwrite(&cf->header.bottom, 4, 1, f); fwrite(&cf->header.maxWidth, 4, 1, f); fwrite(&cf->header.maxHeight, 4, 1, f); fwrite(&cf->header.loLaScale, 4, 1, f); fwrite(&cf->header.headerOffset, 4, 1, f); fwrite(&cf->header.dataOffset, 4, 1, f); fwrite(&cf->header.alignment, 4, 1, f); // Write Items for (int i = 0; i < cf->header.hdrItems; i++) { fwrite(&cf->items[i].left, 4, 1, f); fwrite(&cf->items[i].top, 4, 1, f); fwrite(&cf->items[i].right, 4, 1, f); fwrite(&cf->items[i].bottom, 4, 1, f); fwrite(&cf->items[i].style, 1, 1, f); fwrite(&cf->items[i].altStyle, 1, 1, f); fwrite(&cf->items[i].minAlt, 2, 1, f); fwrite(&cf->items[i].maxAlt, 2, 1, f); fwrite(&cf->items[i].data, 4, 1, f); fwrite(&cf->items[i].timeOut, 4, 1, f); fwrite(cf->items[i].name, 8, 1, f); fwrite(cf->items[i].radio, 8, 1, f); uint8_t pad[1024] = {0}; // Assuming max pad fwrite(pad, 1, cf->header.sizeOfItem - 42, f); } // Write Points for (int i = 0; i < cf->header.maxPts; i++) { fwrite(&cf->points[i].longitude, 4, 1, f); fwrite(&cf->points[i].latitude, 4, 1, f); uint8_t pad[1024] = {0}; fwrite(pad, 1, cf->header.sizeOfPoint - 8, f); } fclose(f); } void freeCubFile(CubFile* cf) { free(cf->items); free(cf->points); } // Example usage: // int main() { // CubFile cf = {0}; // readCubFile(&cf, "example.cub"); // printProperties(&cf); // writeCubFile(&cf, "output.cub"); // freeCubFile(&cf); // return 0; // } // ===== end task-119 .CUBE ===== // ===== task-120 .CUBE [C] ===== #include #include #include #include typedef struct { char *comment1; char *comment2; int natoms; double origin[3]; int nx; double vx[3]; int ny; double vy[3]; int nz; double vz[3]; struct Atom *atoms; double *vol_data; // flat array int vol_size; } CubeFile; typedef struct Atom { int num; double charge; double pos[3]; } Atom; CubeFile* cube_new() { CubeFile* cube = (CubeFile*)malloc(sizeof(CubeFile)); memset(cube, 0, sizeof(CubeFile)); cube->comment1 = (char*)malloc(256); cube->comment2 = (char*)malloc(256); return cube; } void cube_free(CubeFile* cube) { free(cube->comment1); free(cube->comment2); free(cube->atoms); free(cube->vol_data); free(cube); } int cube_read(CubeFile* cube, const char* filename) { FILE* fp = fopen(filename, "r"); if (!fp) return -1; fgets(cube->comment1, 256, fp); cube->comment1[strcspn(cube->comment1, "\n")] = 0; fgets(cube->comment2, 256, fp); cube->comment2[strcspn(cube->comment2, "\n")] = 0; fscanf(fp, "%d %lf %lf %lf", &cube->natoms, &cube->origin[0], &cube->origin[1], &cube->origin[2]); fscanf(fp, "%d %lf %lf %lf", &cube->nx, &cube->vx[0], &cube->vx[1], &cube->vx[2]); fscanf(fp, "%d %lf %lf %lf", &cube->ny, &cube->vy[0], &cube->vy[1], &cube->vy[2]); fscanf(fp, "%d %lf %lf %lf", &cube->nz, &cube->vz[0], &cube->vz[1], &cube->vz[2]); int abs_natoms = abs(cube->natoms); cube->atoms = (Atom*)malloc(sizeof(Atom) * abs_natoms); for (int i = 0; i < abs_natoms; i++) { fscanf(fp, "%d %lf %lf %lf %lf", &cube->atoms[i].num, &cube->atoms[i].charge, &cube->atoms[i].pos[0], &cube->atoms[i].pos[1], &cube->atoms[i].pos[2]); } int abs_nx = abs(cube->nx), abs_ny = abs(cube->ny), abs_nz = abs(cube->nz); cube->vol_size = abs_nx * abs_ny * abs_nz; cube->vol_data = (double*)malloc(sizeof(double) * cube->vol_size); int idx = 0; double val; while (fscanf(fp, "%lf", &val) == 1) { if (idx < cube->vol_size) { cube->vol_data[idx++] = val; } } fclose(fp); return 0; } int cube_write(CubeFile* cube, const char* filename) { FILE* fp = fopen(filename, "w"); if (!fp) return -1; fprintf(fp, "%s\n", cube->comment1); fprintf(fp, "%s\n", cube->comment2); fprintf(fp, "%5d %12.6f %12.6f %12.6f\n", cube->natoms, cube->origin[0], cube->origin[1], cube->origin[2]); fprintf(fp, "%5d %12.6f %12.6f %12.6f\n", cube->nx, cube->vx[0], cube->vx[1], cube->vx[2]); fprintf(fp, "%5d %12.6f %12.6f %12.6f\n", cube->ny, cube->vy[0], cube->vy[1], cube->vy[2]); fprintf(fp, "%5d %12.6f %12.6f %12.6f\n", cube->nz, cube->vz[0], cube->vz[1], cube->vz[2]); int abs_natoms = abs(cube->natoms); for (int i = 0; i < abs_natoms; i++) { Atom a = cube->atoms[i]; fprintf(fp, "%5d %12.6f %12.6f %12.6f %12.6f\n", a.num, a.charge, a.pos[0], a.pos[1], a.pos[2]); } int count = 0; for (int i = 0; i < cube->vol_size; i++) { fprintf(fp, "%12.5E ", cube->vol_data[i]); count++; if (count % 6 == 0) { fprintf(fp, "\n"); count = 0; } } if (count != 0) fprintf(fp, "\n"); fclose(fp); return 0; } void cube_print_properties(CubeFile* cube) { printf("Comment 1: %s\n", cube->comment1); printf("Comment 2: %s\n", cube->comment2); printf("Number of Atoms: %d\n", cube->natoms); printf("Origin: %12.6f %12.6f %12.6f\n", cube->origin[0], cube->origin[1], cube->origin[2]); printf("X-Axis: NX=%5d, Vector=%12.6f %12.6f %12.6f\n", cube->nx, cube->vx[0], cube->vx[1], cube->vx[2]); printf("Y-Axis: NY=%5d, Vector=%12.6f %12.6f %12.6f\n", cube->ny, cube->vy[0], cube->vy[1], cube->vy[2]); printf("Z-Axis: NZ=%5d, Vector=%12.6f %12.6f %12.6f\n", cube->nz, cube->vz[0], cube->vz[1], cube->vz[2]); int abs_natoms = abs(cube->natoms); for (int i = 0; i < abs_natoms; i++) { Atom a = cube->atoms[i]; printf("Atom %d: Number=%5d, Charge=%12.6f, Position=%12.6f %12.6f %12.6f\n", i + 1, a.num, a.charge, a.pos[0], a.pos[1], a.pos[2]); } printf("Volumetric Data Size: %d\n", cube->vol_size); printf("Volumetric Data Sample (first 10): "); for (int i = 0; i < 10 && i < cube->vol_size; i++) { printf("%12.5E ", cube->vol_data[i]); } printf("\n"); } // Example usage: // int main() { // CubeFile* cube = cube_new(); // if (cube_read(cube, "example.cube") == 0) { // cube_print_properties(cube); // cube_write(cube, "output.cube"); // } // cube_free(cube); // return 0; // } // ===== end task-120 .CUBE ===== // ===== task-121 .CUR [C++] ===== #include #include #include #include #include class CurFile { private: std::string filename; uint16_t reserved; uint16_t type; uint16_t imageCount; struct Entry { uint8_t width; uint8_t height; uint8_t colorCount; uint8_t entryReserved; uint16_t hotspotX; uint16_t hotspotY; uint32_t imageDataSize; uint32_t imageOffset; }; struct BmpHeader { uint32_t bmpHeaderSize; int32_t bmpWidth; int32_t bmpHeight; uint16_t bmpPlanes; uint16_t bmpBitCount; uint32_t bmpCompression; uint32_t bmpImageSize; int32_t bmpXPelsPerMeter; int32_t bmpYPelsPerMeter; uint32_t bmpColorsUsed; uint32_t bmpColorsImportant; }; std::vector entries; std::vector bmpHeaders; std::vector data; // Full file data for writing public: CurFile(const std::string& filename) : filename(filename) { load(); } void load() { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) { std::cerr << "Failed to open file." << std::endl; return; } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(data.data(), size); size_t offset = 0; memcpy(&reserved, data.data() + offset, sizeof(reserved)); offset += 2; memcpy(&type, data.data() + offset, sizeof(type)); offset += 2; memcpy(&imageCount, data.data() + offset, sizeof(imageCount)); offset += 2; entries.resize(imageCount); bmpHeaders.resize(imageCount); for (uint16_t i = 0; i < imageCount; ++i) { Entry& entry = entries[i]; memcpy(&entry.width, data.data() + offset, 1); offset += 1; entry.width = (entry.width == 0) ? 256 : entry.width; memcpy(&entry.height, data.data() + offset, 1); offset += 1; entry.height = (entry.height == 0) ? 256 : entry.height; memcpy(&entry.colorCount, data.data() + offset, 1); offset += 1; memcpy(&entry.entryReserved, data.data() + offset, 1); offset += 1; memcpy(&entry.hotspotX, data.data() + offset, sizeof(entry.hotspotX)); offset += 2; memcpy(&entry.hotspotY, data.data() + offset, sizeof(entry.hotspotY)); offset += 2; memcpy(&entry.imageDataSize, data.data() + offset, sizeof(entry.imageDataSize)); offset += 4; memcpy(&entry.imageOffset, data.data() + offset, sizeof(entry.imageOffset)); offset += 4; // BMP Header size_t bmpOffset = entry.imageOffset; BmpHeader& bmp = bmpHeaders[i]; memcpy(&bmp.bmpHeaderSize, data.data() + bmpOffset, sizeof(bmp.bmpHeaderSize)); bmpOffset += 4; memcpy(&bmp.bmpWidth, data.data() + bmpOffset, sizeof(bmp.bmpWidth)); bmpOffset += 4; memcpy(&bmp.bmpHeight, data.data() + bmpOffset, sizeof(bmp.bmpHeight)); bmpOffset += 4; memcpy(&bmp.bmpPlanes, data.data() + bmpOffset, sizeof(bmp.bmpPlanes)); bmpOffset += 2; memcpy(&bmp.bmpBitCount, data.data() + bmpOffset, sizeof(bmp.bmpBitCount)); bmpOffset += 2; memcpy(&bmp.bmpCompression, data.data() + bmpOffset, sizeof(bmp.bmpCompression)); bmpOffset += 4; memcpy(&bmp.bmpImageSize, data.data() + bmpOffset, sizeof(bmp.bmpImageSize)); bmpOffset += 4; memcpy(&bmp.bmpXPelsPerMeter, data.data() + bmpOffset, sizeof(bmp.bmpXPelsPerMeter)); bmpOffset += 4; memcpy(&bmp.bmpYPelsPerMeter, data.data() + bmpOffset, sizeof(bmp.bmpYPelsPerMeter)); bmpOffset += 4; memcpy(&bmp.bmpColorsUsed, data.data() + bmpOffset, sizeof(bmp.bmpColorsUsed)); bmpOffset += 4; memcpy(&bmp.bmpColorsImportant, data.data() + bmpOffset, sizeof(bmp.bmpColorsImportant)); } } void printProperties() const { std::cout << "Header:" << std::endl; std::cout << "Reserved: " << reserved << std::endl; std::cout << "Type: " << type << std::endl; std::cout << "Image Count: " << imageCount << std::endl; std::cout << std::endl; for (uint16_t i = 0; i < imageCount; ++i) { const Entry& entry = entries[i]; std::cout << "Image " << (i + 1) << " Directory Entry:" << std::endl; std::cout << "Width: " << static_cast(entry.width) << std::endl; std::cout << "Height: " << static_cast(entry.height) << std::endl; std::cout << "Color Count: " << static_cast(entry.colorCount) << std::endl; std::cout << "Reserved (Entry): " << static_cast(entry.entryReserved) << std::endl; std::cout << "Hotspot X: " << entry.hotspotX << std::endl; std::cout << "Hotspot Y: " << entry.hotspotY << std::endl; std::cout << "Image Data Size: " << entry.imageDataSize << std::endl; std::cout << "Image Offset: " << entry.imageOffset << std::endl; std::cout << std::endl; const BmpHeader& bmp = bmpHeaders[i]; std::cout << "Image " << (i + 1) << " BMP Header:" << std::endl; std::cout << "BMP Header Size: " << bmp.bmpHeaderSize << std::endl; std::cout << "BMP Width: " << bmp.bmpWidth << std::endl; std::cout << "BMP Height: " << bmp.bmpHeight << std::endl; std::cout << "BMP Planes: " << bmp.bmpPlanes << std::endl; std::cout << "BMP Bit Count: " << bmp.bmpBitCount << std::endl; std::cout << "BMP Compression: " << bmp.bmpCompression << std::endl; std::cout << "BMP Image Size: " << bmp.bmpImageSize << std::endl; std::cout << "BMP X Pixels Per Meter: " << bmp.bmpXPelsPerMeter << std::endl; std::cout << "BMP Y Pixels Per Meter: " << bmp.bmpYPelsPerMeter << std::endl; std::cout << "BMP Colors Used: " << bmp.bmpColorsUsed << std::endl; std::cout << "BMP Colors Important: " << bmp.bmpColorsImportant << std::endl; std::cout << std::endl; } } void write(const std::string& outputFilename) const { // Writes the original data; modifications can be applied to data vector std::ofstream outFile(outputFilename, std::ios::binary); if (outFile) { outFile.write(data.data(), data.size()); } } }; // Example usage: // int main() { // CurFile cur("example.cur"); // cur.printProperties(); // cur.write("output.cur"); // return 0; // } // ===== end task-121 .CUR ===== // ===== task-122 .D [C] ===== #include #include #include typedef struct { char *filename; char *target; char **dependencies; int dep_count; } DFileHandler; DFileHandler *dfile_create(const char *filename) { DFileHandler *handler = malloc(sizeof(DFileHandler)); handler->filename = strdup(filename); handler->target = NULL; handler->dependencies = NULL; handler->dep_count = 0; return handler; } void dfile_destroy(DFileHandler *handler) { if (handler->target) free(handler->target); for (int i = 0; i < handler->dep_count; i++) { free(handler->dependencies[i]); } if (handler->dependencies) free(handler->dependencies); free(handler->filename); free(handler); } int dfile_read(DFileHandler *handler) { FILE *f = fopen(handler->filename, "r"); if (!f) return 1; char content[1024]; // Assume small file if (fgets(content, sizeof(content), f) == NULL) { fclose(f); return 1; } fclose(f); char *colon = strchr(content, ':'); if (!colon) return 1; *colon = '\0'; handler->target = strdup(content); char *deps_str = colon + 1; char *dep = strtok(deps_str, " \n"); while (dep) { handler->dependencies = realloc(handler->dependencies, (handler->dep_count + 1) * sizeof(char*)); handler->dependencies[handler->dep_count++] = strdup(dep); dep = strtok(NULL, " \n"); } return 0; } void dfile_print_properties(DFileHandler *handler) { if (handler->target == NULL) { printf("No properties loaded.\n"); return; } printf("Target: %s\n", handler->target); printf("Dependencies:\n"); for (int i = 0; i < handler->dep_count; i++) { printf(" - %s\n", handler->dependencies[i]); } } int dfile_write(DFileHandler *handler, const char *target, const char **dependencies, int dep_count) { FILE *f = fopen(handler->filename, "w"); if (!f) return 1; fprintf(f, "%s:", target); for (int i = 0; i < dep_count; i++) { fprintf(f, " %s", dependencies[i]); } fprintf(f, "\n"); fclose(f); return 0; } // Example usage int main() { DFileHandler *handler = dfile_create("example.d"); if (dfile_read(handler) == 0) { dfile_print_properties(handler); } else { printf("Error reading file.\n"); } // To write const char *deps[] = {"main.c", "defs.h"}; dfile_write(handler, "main.o", deps, 2); dfile_destroy(handler); return 0; } // ===== end task-122 .D ===== // ===== task-123 .DAA [C++] ===== #include #include #include #include #include class DAAFile { private: std::string filepath; std::string magic; uint32_t version; uint64_t offsetToList; uint64_t offsetToData; uint32_t numChunks; std::vector chunkLengths; uint64_t uncompressedSize; std::vector> compressedChunks; std::vector decompressedData; public: DAAFile(const std::string& filepath) : filepath(filepath), version(0), offsetToList(0), offsetToData(0), numChunks(0), uncompressedSize(0) {} void read() { std::ifstream f(filepath, std::ios::binary); f.seekg(0, std::ios::end); size_t size = f.tellg(); f.seekg(0, std::ios::beg); std::vector data(size); f.read((char*)data.data(), size); f.close(); magic = std::string(data.begin(), data.begin() + 4); memcpy(&version, data.data() + 4, 4); memcpy(&offsetToList, data.data() + 0x4C, 8); memcpy(&offsetToData, data.data() + 0x5E, 8); uint64_t listSize = offsetToData - offsetToList; numChunks = listSize / 3; chunkLengths.resize(numChunks); for (uint32_t i = 0; i < numChunks; i++) { uint32_t pos = offsetToList + i * 3; uint8_t b1 = data[pos]; uint8_t b2 = data[pos + 1]; uint8_t b3 = data[pos + 2]; chunkLengths[i] = (b1 << 16) | (b3 << 8) | b2; } uint32_t pos = offsetToData; compressedChunks.resize(numChunks); for (uint32_t i = 0; i < numChunks; i++) { uint32_t length = chunkLengths[i]; compressedChunks[i].resize(length); memcpy(compressedChunks[i].data(), data.data() + pos, length); pos += length; } uncompressedSize = (numChunks - 1) * 65536ULL + (decompressChunk(compressedChunks.back()).size() if numChunks > 0 else 0); } std::vector decompressChunk(const std::vector& chunk) { uLongf destLen = 65536; std::vector output(destLen); int ret = uncompress2(output.data(), &destLen, chunk.data(), (uLongf*)&chunk.size()); if (ret != Z_OK) { std::cerr << "Decompression error" << std::endl; return {}; } output.resize(destLen); return output; } void decode() { decompressedData.clear(); for (const auto& chunk : compressedChunks) { auto d = decompressChunk(chunk); decompressedData.insert(decompressedData.end(), d.begin(), d.end()); } } void printProperties() { std::cout << "Magic: " << magic << std::endl; std::cout << "Version: 0x" << std::hex << version << std::endl; std::cout << "Offset to chunk lengths list: 0x" << std::hex << offsetToList << std::endl; std::cout << "Offset to first chunk: 0x" << std::hex << offsetToData << std::endl; std::cout << "Number of chunks: " << numChunks << std::endl; std::cout << "Chunk lengths: "; for (auto l : chunkLengths) std::cout << l << " "; std::cout << std::endl; std::cout << "Compression type: zlib" << std::endl; std::cout << "Encryption: " << (magic.find("encrypted") != std::string::npos ? "Yes" : "No") << " (basic check)" << std::endl; std::cout << "Multi-volume: " << (filepath.find(".001") != std::string::npos ? "Yes" : "No") << " (basic check)" << std::endl; std::cout << "Uncompressed size: " << uncompressedSize << " bytes" << std::endl; } void write(const std::string& newFilepath) { if (decompressedData.empty()) { std::cerr << "No data to write" << std::endl; return; } std::vector> chunks; for (size_t i = 0; i < decompressedData.size(); i += 65536) { size_t end = std::min(i + 65536, decompressedData.size()); std::vector chunk(decompressedData.begin() + i, decompressedData.begin() + end); chunks.push_back(chunk); } chunkLengths.clear(); compressedChunks.clear(); for (const auto& chunk : chunks) { uLongf destLen = compressBound(chunk.size()); std::vector compressed(destLen); int ret = compress2(compressed.data(), &destLen, chunk.data(), chunk.size(), 9); if (ret != Z_OK) { std::cerr << "Compression error" << std::endl; return; } compressed.resize(destLen); chunkLengths.push_back(destLen); compressedChunks.push_back(compressed); } numChunks = chunks.size(); uncompressedSize = decompressedData.size(); // Build list std::vector listBytes(numChunks * 3); for (uint32_t j = 0; j < numChunks; j++) { uint32_t length = chunkLengths[j]; uint8_t b1 = (length >> 16) & 0xFF; uint8_t b2 = length & 0xFF; uint8_t b3 = (length >> 8) & 0xFF; listBytes[j * 3] = b1; listBytes[j * 3 + 1] = b2; listBytes[j * 3 + 2] = b3; } // Header offsetToList = 0x66; offsetToData = offsetToList + numChunks * 3; std::vector header(0x66, 0); memcpy(header.data(), "DAA\0", 4); memcpy(header.data() + 4, &version, 4); memcpy(header.data() + 0x4C, &offsetToList, 8); memcpy(header.data() + 0x5E, &offsetToData, 8); // Write std::ofstream f(newFilepath, std::ios::binary); f.write((char*)header.data(), header.size()); f.write((char*)listBytes.data(), listBytes.size()); for (const auto& chunk : compressedChunks) { f.write((char*)chunk.data(), chunk.size()); } f.close(); } }; // Example usage // DAAFile daa("example.daa"); // daa.read(); // daa.decode(); // daa.printProperties(); // daa.write("new.daa"); // ===== end task-123 .DAA ===== // ===== task-124 .DAE [C++] ===== #include #include #include #include #include // For time in write class DAEProcessor { private: std::string filepath; std::string xmlContent; std::string extractTag(const std::string& tag) { size_t start = xmlContent.find("<" + tag + ">") ; if (start == std::string::npos) return "N/A"; start += tag.length() + 2; size_t end = xmlContent.find("", start); if (end == std::string::npos) return "N/A"; return xmlContent.substr(start, end - start); } std::vector extractContributors(const std::string& subTag) { std::vector results; size_t pos = 0; while ((pos = xmlContent.find("", pos)) != std::string::npos) { size_t subStart = xmlContent.find("<" + subTag + ">", pos); if (subStart != std::string::npos) { subStart += subTag.length() + 2; size_t subEnd = xmlContent.find("", subStart); if (subEnd != std::string::npos) { results.push_back(xmlContent.substr(subStart, subEnd - subStart)); } } pos += 13; // Skip to next } return results; } public: DAEProcessor(const std::string& fp) : filepath(fp) { std::ifstream file(fp); if (file) { xmlContent.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); } } void printProperties() { if (xmlContent.empty()) { std::cout << "Failed to load file." << std::endl; return; } if (xmlContent.find("") == std::string::npos) { std::cout << "No element found." << std::endl; return; } std::cout << "DAE Properties:" << std::endl; // Contributors (example for author and authoring_tool; extend similarly) auto authors = extractContributors("author"); auto tools = extractContributors("authoring_tool"); // ... (similar for other sub-tags) for (size_t i = 0; i < authors.size(); ++i) { std::cout << "\nContributor " << (i + 1) << ":" << std::endl; std::cout << " Author: " << (i < authors.size() ? authors[i] : "N/A") << std::endl; std::cout << " Authoring Tool: " << (i < tools.size() ? tools[i] : "N/A") << std::endl; // Add more sub-properties similarly } // Geographic (simplified; assume single) std::cout << "\nGeographic Location:" << std::endl; std::cout << " Longitude: " << extractTag("longitude") << std::endl; std::cout << " Latitude: " << extractTag("latitude") << std::endl; std::cout << " Altitude: " << extractTag("altitude") << std::endl; // Mode not extracted for simplicity // Other properties std::cout << "\nCreated: " << extractTag("created") << std::endl; std::cout << "Keywords: " << extractTag("keywords") << std::endl; std::cout << "Modified: " << extractTag("modified") << std::endl; std::cout << "Revision: " << extractTag("revision") << std::endl; std::cout << "Subject: " << extractTag("subject") << std::endl; std::cout << "Title: " << extractTag("title") << std::endl; // Unit (extract attributes manually) size_t unitPos = xmlContent.find(""); if (start != std::string::npos) { size_t end = xmlContent.find("", start); if (end != std::string::npos) { xmlContent.replace(start + key.length() + 2, end - (start + key.length() + 2), value); } } std::ofstream out(newFilepath); out << xmlContent; } }; // Usage example: // int main() { // DAEProcessor processor("example.dae"); // processor.printProperties(); // time_t now = time(0); // char buf[25]; // strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", gmtime(&now)); // processor.updateAndWrite("modified.dae", "modified", buf); // return 0; // } // ===== end task-124 .DAE ===== // ===== task-125 .DAF [C++] ===== #include #include #include #include typedef struct { char locidw[9]; int32_t nd; int32_t ni; char locifn[61]; int32_t fward; int32_t bward; int32_t free; char locfmt[9]; char ftpstr[29]; int ss; int nc; int reservedCount; int recordLength; char endianness[12]; } DAFProperties; class DAFHandler { private: char* filepath; DAFProperties props; public: DAFHandler(const char* fp) : filepath(nullptr) { if (fp) { filepath = strdup(fp); read(); } } ~DAFHandler() { free(filepath); } void read() { FILE* f = fopen(filepath, "rb"); if (!f) return; char buffer[1024]; fread(buffer, 1, 1024, f); strncpy(props.locidw, buffer, 8); props.locidw[8] = '\0'; memcpy(&props.nd, buffer + 8, 4); memcpy(&props.ni, buffer + 12, 4); strncpy(props.locifn, buffer + 16, 60); props.locifn[60] = '\0'; memcpy(&props.fward, buffer + 76, 4); memcpy(&props.bward, buffer + 80, 4); memcpy(&props.free, buffer + 84, 4); strncpy(props.locfmt, buffer + 88, 8); props.locfmt[8] = '\0'; strncpy(props.ftpstr, buffer + 699, 28); props.ftpstr[28] = '\0'; props.ss = props.nd + (props.ni + 1) / 2; props.nc = 8 * props.ss; props.reservedCount = props.fward - 2; props.recordLength = 1024; strcpy(props.endianness, strstr(props.locfmt, "BIG") ? "Big-Endian" : "Little-Endian"); fclose(f); } void printProperties() { printf("LOCIDW: %s\n", props.locidw); printf("ND: %d\n", props.nd); printf("NI: %d\n", props.ni); printf("LOCIFN: %s\n", props.locifn); printf("FWARD: %d\n", props.fward); printf("BWARD: %d\n", props.bward); printf("FREE: %d\n", props.free); printf("LOCFMT: %s\n", props.locfmt); printf("FTPSTR: %s\n", props.ftpstr); printf("Summary Size (SS): %d\n", props.ss); printf("Name Character Count (NC): %d\n", props.nc); printf("Reserved Records Count: %d\n", props.reservedCount); printf("Record Length: %d\n", props.recordLength); printf("Endianness: %s\n", props.endianness); } void write(const char* newFilepath) { FILE* f = fopen(newFilepath, "wb"); if (!f) return; char buffer[1024] = {0}; strncpy(buffer, props.locidw, 8); memcpy(buffer + 8, &props.nd, 4); memcpy(buffer + 12, &props.ni, 4); strncpy(buffer + 16, props.locifn, 60); memcpy(buffer + 76, &props.fward, 4); memcpy(buffer + 80, &props.bward, 4); memcpy(buffer + 84, &props.free, 4); strncpy(buffer + 88, props.locfmt, 8); strncpy(buffer + 699, props.ftpstr, 28); fwrite(buffer, 1, 1024, f); fclose(f); } }; // Example usage // int main() { // DAFHandler daf("path/to/file.bsp"); // daf.printProperties(); // daf.write("new.daf"); // return 0; // } // ===== end task-125 .DAF ===== // ===== task-126 .DART [C++] ===== #include #include #include #include #include #include class DARTFile { private: std::string path; struct stat fileStat; public: DARTFile(const std::string& filePath) : path(filePath) { if (stat(filePath.c_str(), &fileStat) != 0 || path.substr(path.find_last_of('.')) != ".DART") { throw std::invalid_argument("Invalid .DART file path"); } } std::string read() { std::ifstream file(path); if (!file) { throw std::runtime_error("Failed to open file for reading"); } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); return content; } void write(const std::string& content) { std::ofstream file(path); if (!file) { throw std::runtime_error("Failed to open file for writing"); } file << content; } void printProperties() { std::cout << "File Name: " << path.substr(path.find_last_of("/\\") + 1) << std::endl; std::cout << "File Path: " << path << std::endl; std::cout << "File Size: " << fileStat.st_size << " bytes" << std::endl; std::cout << "Creation Time: " << std::ctime(&fileStat.st_ctime); std::cout << "Modification Time: " << std::ctime(&fileStat.st_mtime); std::cout << "Access Time: " << std::ctime(&fileStat.st_atime); std::cout << "Permissions: " << std::oct << fileStat.st_mode << std::endl; std::cout << "Owner UID: " << fileStat.st_uid << std::endl; std::cout << "Group GID: " << fileStat.st_gid << std::endl; std::cout << "Inode Number: " << fileStat.st_ino << std::endl; } }; // Example usage: // int main() { // try { // DARTFile dartFile("example.DART"); // std::cout << dartFile.read() << std::endl; // dartFile.write("New content"); // dartFile.printProperties(); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-126 .DART ===== // ===== task-127 .DAT [C++] ===== #include #include #include #include #include class DatFile { private: std::map properties; public: void openAndDecode(const std::string& filename) { std::ifstream file(filename, std::ios::binary); if (!file.is_open()) { throw std::runtime_error("File " + filename + " not found."); } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); // Parse header size_t pos = 0; while (pos < content.size() && content[pos] == '%') { size_t nlPos = content.find('\n', pos); if (nlPos == std::string::npos) break; std::string line = content.substr(pos + 1, nlPos - pos - 1); std::istringstream iss(line); std::string key, value; iss >> key; std::getline(iss >> std::ws, value); if (!key.empty()) { properties[key] = value; } pos = nlPos + 1; } } void printProperties() const { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& filename) const { std::ofstream file(filename, std::ios::binary); if (!file.is_open()) { throw std::runtime_error("Could not open file " + filename + " for writing."); } for (const auto& pair : properties) { file << "% " << pair.first << " " << pair.second << "\n"; } // Add minimal binary section char binary[] = {0x0C, 0x08}; file.write(binary, sizeof(binary)); } }; // Example usage: // int main() { // try { // DatFile dat; // dat.openAndDecode("sample.dat"); // dat.printProperties(); // dat.write("new.dat"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-127 .DAT ===== // ===== task-128 .DATS [C++] ===== #include #include #include using json = nlohmann::json; class DATSHandler { private: std::string filepath; json data; public: DATSHandler(const std::string& fp) : filepath(fp) { data = read(); } json read() { std::ifstream file(filepath); json j; file >> j; return j; } void printProperties() { std::vector properties = {"identifier", "alternateIdentifiers", "relatedIdentifiers", "title", "description", "types", "keywords", "version", "licenses", "creators", "acknowledges", "dates", "privacy", "spatialCoverage", "temporalCoverage", "storedIn", "distributions", "primaryPublications", "citations", "producedBy", "isAbout", "hasPart", "isPartOf", "dimensions", "extraProperties"}; for (const auto& prop : properties) { if (data.contains(prop)) { std::cout << prop << ": " << data[prop].dump(2) << std::endl; } } } void write(const std::string& newFilepath = "") { std::string path = newFilepath.empty() ? filepath : newFilepath; std::ofstream file(path); file << data.dump(2); } json& getData() { return data; } }; // Example usage: // int main() { // DATSHandler handler("example.dats"); // handler.printProperties(); // handler.getData()["title"] = "Updated Title"; // handler.write("updated.dats"); // return 0; // } // ===== end task-128 .DATS ===== // ===== task-129 .DB [C] ===== #include #include #include #include #include typedef struct { char* filepath; uint8_t header[512]; // Properties stored as strings for simplicity char file_signature[24]; // "XX XX ..." format // ... other properties can be added similarly } DBFileHandler; void init(DBFileHandler* self, char* filepath) { self->filepath = filepath; } void read_and_decode(DBFileHandler* self) { FILE* f = fopen(self->filepath, "rb"); if (f) { fread(self->header, 1, 512, f); fclose(f); } } void print_properties(DBFileHandler* self) { if (self->header[0] == 0) read_and_decode(self); // Ensure read printf("File Signature: "); for (int i = 0; i < 8; i++) printf("%02X ", self->header[i]); printf("\n"); printf("CLSID: "); for (int i = 8; i < 24; i++) printf("%02X ", self->header[i]); printf("\n"); uint16_t* u16 = (uint16_t*)self->header; printf("Minor Version: %u\n", u16[12]); printf("Major Version: %u\n", u16[13]); printf("Byte Order: %u\n", u16[14]); printf("Sector Shift: %u\n", u16[15]); printf("Mini Sector Shift: %u\n", u16[16]); uint64_t* u64 = (uint64_t*)self->header; printf("Reserved Fields: %llu\n", u64[4] & 0xFFFFFFFFFFFF); // 6 bytes uint32_t* u32 = (uint32_t*)self->header; printf("Number of Directory Sectors: %u\n", u32[10]); printf("Number of FAT Sectors: %u\n", u32[11]); printf("First Directory Sector Location: %u\n", u32[12]); printf("Transaction Signature Number: %u\n", u32[13]); printf("Mini Stream Cutoff Size: %u\n", u32[14]); printf("First Mini FAT Sector Location: %u\n", u32[15]); printf("Number of Mini FAT Sectors: %u\n", u32[16]); printf("First DIFAT Sector Location: %u\n", u32[17]); printf("Number of DIFAT Sectors: %u\n", u32[18]); struct stat st; stat(self->filepath, &st); printf("Hidden Attribute: %s\n", (st.st_mode & S_IFREG) ? "False" : "True"); // Simplified printf("System Attribute: Assumed (platform dependent)\n"); } void write(DBFileHandler* self, char* new_filepath) { FILE* f_in = fopen(self->filepath, "rb"); FILE* f_out = fopen(new_filepath, "wb"); if (f_in && f_out) { uint8_t byte; while (fread(&byte, 1, 1, f_in)) fwrite(&byte, 1, 1, f_out); // Modify transaction signature to 0 fseek(f_out, 52, SEEK_SET); uint32_t zero = 0; fwrite(&zero, sizeof(uint32_t), 1, f_out); fclose(f_in); fclose(f_out); } } // Example usage: // int main() { // DBFileHandler handler; // init(&handler, "path/to/Thumbs.db"); // print_properties(&handler); // write(&handler, "path/to/new.db"); // return 0; // } // ===== end task-129 .DB ===== // ===== task-130 .DBA [C] ===== #include #include #include #include #include typedef struct { char* filename; uint8_t* data; size_t size; // Properties as structs/arrays (e.g., char* version_tag; etc.) } DBAHandler; char* read_cstring(uint8_t* data, size_t* offset) { uint8_t len = data[(*offset)++]; uint16_t length = len; if (len == 0xFF) { length = (data[(*offset)++] << 8) | data[(*offset)++]; } char* str = malloc(length + 1); memcpy(str, &data[*offset], length); str[length] = '\0'; *offset += length; return str; } DBAHandler* create_handler(const char* filename) { DBAHandler* h = malloc(sizeof(DBAHandler)); h->filename = strdup(filename); // Read file into h->data, h->size FILE* f = fopen(filename, "rb"); fseek(f, 0, SEEK_END); h->size = ftell(f); fseek(f, 0, SEEK_SET); h->data = malloc(h->size); fread(h->data, 1, h->size, f); fclose(f); return h; } void open_and_decode(DBAHandler* h) { size_t offset = 0; // Parsing logic similar to Python (read version, etc.) // Store in handler fields } void print_properties(DBAHandler* h) { // Print all stored properties } void write(DBAHandler* h, const char* output_filename) { // Write data back } void destroy_handler(DBAHandler* h) { free(h->data); free(h->filename); free(h); } // Usage: // DBAHandler* h = create_handler("example.dba"); // open_and_decode(h); // print_properties(h); // write(h, "new.dba"); // destroy_handler(h); // ===== end task-130 .DBA ===== // ===== task-131 .DBC [C++] ===== #include #include #include #include #include #include class DBCHandler { private: std::string filepath; std::map simpleProps; std::map> listProps; std::vector> sgProps; // For SG_ with message-signal pairs public: DBCHandler(const std::string& fp = "") : filepath(fp) { simpleProps["VERSION"] = ""; simpleProps["BS_"] = ""; listProps["NS_"] = {}; listProps["BU_"] = {}; listProps["BO_"] = {}; listProps["CM_"] = {}; listProps["BA_DEF_"] = {}; listProps["BA_DEF_DEF_"] = {}; listProps["BA_"] = {}; listProps["VAL_"] = {}; listProps["SIG_VALTYPE_"] = {}; listProps["BO_TX_BU_"] = {}; listProps["Relations"] = {}; if (!filepath.empty()) { readAndDecode(); } } void readAndDecode() { std::ifstream file(filepath); if (!file.is_open()) { throw std::runtime_error("File " + filepath + " not found."); } std::string line, currentBO; bool inNS = false; while (std::getline(file, line)) { std::istringstream iss(line); std::string token; iss >> token; if (token == "VERSION") { std::string ver; std::getline(iss, ver); ver.erase(std::remove(ver.begin(), ver.end(), '"'), ver.end()); simpleProps["VERSION"] = ver; } else if (token == "NS_") { inNS = true; } else if (inNS && token == "BS_") { inNS = false; std::string bs; std::getline(iss, bs); bs.erase(0, bs.find_first_not_of(" :")); simpleProps["BS_"] = bs; } else if (inNS) { listProps["NS_"].push_back(line); } else if (token == "BS_:") { std::string bs; std::getline(iss, bs); simpleProps["BS_"] = bs; } else if (token == "BU_:") { std::string node; while (iss >> node) { listProps["BU_"].push_back(node); } } else if (token == "BO_") { currentBO = line; listProps["BO_"].push_back(line); } else if (token == "SG_" && !currentBO.empty()) { std::map sgMap; sgMap["message"] = currentBO; sgMap["signal"] = line; sgProps.push_back(sgMap); } else if (token == "CM_") { listProps["CM_"].push_back(line); } else if (token == "BA_DEF_") { listProps["BA_DEF_"].push_back(line); } else if (token == "BA_DEF_DEF_") { listProps["BA_DEF_DEF_"].push_back(line); } else if (token == "BA_") { listProps["BA_"].push_back(line); } else if (token == "VAL_") { listProps["VAL_"].push_back(line); } else if (token == "SIG_VALTYPE_") { listProps["SIG_VALTYPE_"].push_back(line); } else if (token == "BO_TX_BU_") { listProps["BO_TX_BU_"].push_back(line); } else if (token == "BA_DEF_REL_" || token == "BA_REL_" || token == "BU_SG_REL_") { listProps["Relations"].push_back(line); } } file.close(); } void printProperties() const { for (const auto& entry : simpleProps) { std::cout << entry.first << ":" << std::endl << entry.second << std::endl << std::endl; } for (const auto& entry : listProps) { std::cout << entry.first << ":" << std::endl; for (const auto& item : entry.second) { std::cout << "- " << item << std::endl; } std::cout << std::endl; } std::cout << "SG_:" << std::endl; for (const auto& sg : sgProps) { std::cout << "- Message: " << sg.at("message") << std::endl; std::cout << " Signal: " << sg.at("signal") << std::endl; } std::cout << std::endl; } void write(const std::string& newFilepath = "") const { std::string outPath = newFilepath.empty() ? (filepath.empty() ? "output.dbc" : filepath) : newFilepath; std::ofstream outFile(outPath); if (!outFile.is_open()) { throw std::runtime_error("Error writing to file " + outPath); } if (!simpleProps.at("VERSION").empty()) { outFile << "VERSION \"" << simpleProps.at("VERSION") << "\"\n\n"; } if (!listProps.at("NS_").empty()) { outFile << "NS_ :\n"; for (const auto& ns : listProps.at("NS_")) { outFile << " " << ns << "\n"; } } if (!simpleProps.at("BS_").empty()) { outFile << "\nBS_: " << simpleProps.at("BS_") << "\n"; } if (!listProps.at("BU_").empty()) { outFile << "\nBU_: "; for (const auto& bu : listProps.at("BU_")) { outFile << bu << " "; } outFile << "\n"; } for (const auto& bo : listProps.at("BO_")) { outFile << "\n" << bo << "\n"; for (const auto& sg : sgProps) { if (sg.at("message") == bo) { outFile << " " << sg.at("signal") << "\n"; } } } for (const auto& cm : listProps.at("CM_")) { outFile << "\n" << cm << "\n"; } for (const auto& baDef : listProps.at("BA_DEF_")) { outFile << baDef << "\n"; } for (const auto& baDefDef : listProps.at("BA_DEF_DEF_")) { outFile << baDefDef << "\n"; } for (const auto& ba : listProps.at("BA_")) { outFile << ba << "\n"; } for (const auto& val : listProps.at("VAL_")) { outFile << val << "\n"; } for (const auto& sigVal : listProps.at("SIG_VALTYPE_")) { outFile << sigVal << "\n"; } for (const auto& boTx : listProps.at("BO_TX_BU_")) { outFile << boTx << "\n"; } for (const auto& rel : listProps.at("Relations")) { outFile << rel << "\n"; } outFile.close(); } }; // Example usage: // int main() { // try { // DBCHandler handler("path/to/file.dbc"); // handler.printProperties(); // handler.write("path/to/new.dbc"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-131 .DBC ===== // ===== task-132 .DBF [C++] ===== #include #include #include #include #include #include struct FieldDescriptor { std::string name; char type; uint8_t length; uint8_t decimals; bool indexed; }; class DBFHandler { private: std::string filepath; std::vector data; struct Header { uint8_t version; uint16_t year; uint8_t month; uint8_t day; uint32_t num_records; uint16_t header_length; uint16_t record_length; uint8_t transaction_flag; uint8_t encryption_flag; uint8_t mdx_flag; uint8_t language_id; } header; std::vector fields; uint16_t readUint16(size_t offset) { return data[offset] | (data[offset + 1] << 8); } uint32_t readUint32(size_t offset) { return data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24); } public: DBFHandler(const std::string& filepath) : filepath(filepath) { std::ifstream file(filepath, std::ios::binary | std::ios::ate); size_t size = file.tellg(); data.resize(size); file.seekg(0); file.read(reinterpret_cast(data.data()), size); readHeader(); } void readHeader() { header.version = data[0]; header.year = 1900 + data[1]; header.month = data[2]; header.day = data[3]; header.num_records = readUint32(4); header.header_length = readUint16(8); header.record_length = readUint16(10); header.transaction_flag = data[14]; header.encryption_flag = data[15]; header.mdx_flag = data[28]; header.language_id = data[29]; // Read fields size_t offset = 32; while (offset < header.header_length && data[offset] != 0x0D) { FieldDescriptor field; field.name = ""; for (int i = 0; i < 11; ++i) { if (data[offset + i] == 0) break; field.name += static_cast(data[offset + i]); } field.type = static_cast(data[offset + 11]); field.length = data[offset + 16]; field.decimals = data[offset + 17]; field.indexed = data[offset + 31] != 0; fields.push_back(field); offset += 32; } } void printProperties() { std::cout << "DBF Properties:" << std::endl; std::cout << "Version: " << static_cast(header.version) << std::endl; std::cout << "Year: " << header.year << std::endl; std::cout << "Month: " << static_cast(header.month) << std::endl; std::cout << "Day: " << static_cast(header.day) << std::endl; std::cout << "Num Records: " << header.num_records << std::endl; std::cout << "Header Length: " << header.header_length << std::endl; std::cout << "Record Length: " << header.record_length << std::endl; std::cout << "Transaction Flag: " << static_cast(header.transaction_flag) << std::endl; std::cout << "Encryption Flag: " << static_cast(header.encryption_flag) << std::endl; std::cout << "MDX Flag: " << static_cast(header.mdx_flag) << std::endl; std::cout << "Language ID: " << static_cast(header.language_id) << std::endl; std::cout << "Field Descriptors:" << std::endl; for (const auto& field : fields) { std::cout << "Name: " << field.name << ", Type: " << field.type << ", Length: " << static_cast(field.length) << ", Decimals: " << static_cast(field.decimals) << ", Indexed: " << (field.indexed ? "Yes" : "No") << std::endl; } } void write(const std::string& outputPath, bool updateDate) { if (updateDate) { time_t now = time(nullptr); tm* local = localtime(&now); data[1] = static_cast(local->tm_year); data[2] = static_cast(local->tm_mon + 1); data[3] = static_cast(local->tm_mday); } std::ofstream outfile(outputPath, std::ios::binary); outfile.write(reinterpret_cast(data.data()), data.size()); } }; // Example usage: // int main() { // DBFHandler handler("sample.dbf"); // handler.printProperties(); // handler.write("output.dbf", true); // return 0; // } // ===== end task-132 .DBF ===== // ===== task-133 .DBG [C] ===== #include #include #include #define MAX_LINE 1024 #define MAX_DIRECTIVES 1000 #define MAX_PARTS 20 typedef struct { char *filename; char **directives[MAX_DIRECTIVES]; int num_directives; } DBGFile; DBGFile* dbgfile_create(const char *filename) { DBGFile *dbg = malloc(sizeof(DBGFile)); dbg->filename = strdup(filename); dbg->num_directives = 0; return dbg; } void dbgfile_read(DBGFile *dbg) { FILE *f = fopen(dbg->filename, "r"); if (!f) return; char line[MAX_LINE]; while (fgets(line, MAX_LINE, f)) { if (strstr(line, ".dbg") == line) { char *parts[MAX_PARTS]; int count = 0; char *token = strtok(line + 4, ","); while (token && count < MAX_PARTS) { parts[count] = strdup(token); token = strtok(NULL, ","); count++; } dbg->directives[dbg->num_directives] = malloc(count * sizeof(char*)); for (int i = 0; i < count; i++) { // Trim spaces and quotes char *p = parts[i]; while (*p == ' ') p++; if (*p == '"') p++; char *end = p + strlen(p) - 1; if (*end == '"') *end = '\0'; dbg->directives[dbg->num_directives][i] = strdup(p); } dbg->num_directives++; } } fclose(f); } void dbgfile_print_properties(DBGFile *dbg) { printf("Extracted Properties from .DBG File:\n"); for (int i = 0; i < dbg->num_directives; i++) { for (int j = 0; dbg->directives[i][j]; j++) { printf("%s", dbg->directives[i][j]); if (dbg->directives[i][j+1]) printf(", "); } printf("\n"); } } void dbgfile_write(DBGFile *dbg, const char *new_filename) { FILE *f = fopen(new_filename, "w"); if (!f) return; for (int i = 0; i < dbg->num_directives; i++) { fprintf(f, ".dbg %s", dbg->directives[i][0]); for (int j = 1; dbg->directives[i][j]; j++) { int is_num = 1; for (char *p = dbg->directives[i][j]; *p; p++) { if (!isdigit(*p)) is_num = 0; } if (is_num) { fprintf(f, ", %s", dbg->directives[i][j]); } else { fprintf(f, ", \"%s\"", dbg->directives[i][j]); } } fprintf(f, "\n"); } fclose(f); } void dbgfile_destroy(DBGFile *dbg) { for (int i = 0; i < dbg->num_directives; i++) { for (int j = 0; dbg->directives[i][j]; j++) { free(dbg->directives[i][j]); } free(dbg->directives[i]); } free(dbg->filename); free(dbg); } // ===== end task-133 .DBG ===== // ===== task-134 .DEB [C++] ===== #include #include #include #include #include #include #include #include // For gzip struct TarEntry { std::string name; mode_t mode; uid_t uid; gid_t gid; size_t size; time_t mtime; char typeflag; std::string linkname; std::vector content; }; struct ArMember { std::string name; time_t timestamp; uid_t owner; gid_t group; mode_t mode; size_t size; std::vector content; }; class DebHandler { private: std::string arMagic = "!\n"; std::map properties; std::vector decompress(const std::vector& data, const std::string& type) { if (type == "gz") { z_stream strm; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = data.size(); strm.next_in = (Bytef*)data.data(); inflateInit2(&strm, 15 + 32); // gzip std::vector out; char buf[1024]; do { strm.avail_out = sizeof(buf); strm.next_out = (Bytef*)buf; inflate(&strm, Z_NO_FLUSH); out.insert(out.end(), buf, buf + sizeof(buf) - strm.avail_out); } while (strm.avail_out == 0); inflateEnd(&strm); return out; } // Add for xz, bz2 return data; } std::vector parseTar(const std::vector& data) { std::vector files; size_t offset = 0; while (offset < data.size()) { const char* header = data.data() + offset; if (std::all_of(header, header + 512, [](char c){ return c == 0; })) break; TarEntry entry; entry.name = std::string(header, 100); entry.name = entry.name.substr(0, entry.name.find('\0')); entry.mode = std::stoi(std::string(header + 100, 8), nullptr, 8); entry.uid = std::stoi(std::string(header + 108, 8), nullptr, 8); entry.gid = std::stoi(std::string(header + 116, 8), nullptr, 8); entry.size = std::stoi(std::string(header + 124, 12), nullptr, 8); entry.mtime = std::stoi(std::string(header + 136, 12), nullptr, 8); entry.typeflag = header[156]; entry.linkname = std::string(header + 157, 100); entry.linkname = entry.linkname.substr(0, entry.linkname.find('\0')); offset += 512; if (entry.size > 0) { entry.content.assign(data.begin() + offset, data.begin() + offset + entry.size); offset += entry.size; } offset += (512 - (entry.size % 512)) % 512; files.push_back(entry); } return files; } std::map parseControl(const std::string& content) { std::map fields; std::istringstream iss(content); std::string line, key; while (std::getline(iss, line)) { if (line[0] == ' ') { if (!key.empty()) fields[key] += "\n" + line.substr(1); } else { size_t pos = line.find(':'); if (pos != std::string::npos) { key = line.substr(0, pos); fields[key] = line.substr(pos + 1); } } } return fields; } public: void open(const std::string& filepath) { std::ifstream file(filepath, std::ios::binary); file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(data.data(), size); parse(data); } void parse(const std::vector& data) { size_t offset = 0; std::string magic(data.begin(), data.begin() + 8); if (magic != arMagic) throw std::runtime_error("Not a valid .deb file"); properties["magic"] = magic; offset += 8; std::vector members; properties["members"] = members; while (offset < data.size()) { if (data[offset] == 0) break; ArMember member; member.name = std::string(data.begin() + offset, data.begin() + offset + 16); member.name.erase(member.name.find_last_not_of(' ') + 1); member.timestamp = std::stoll(std::string(data.begin() + offset + 16, data.begin() + offset + 28)); member.owner = std::stoi(std::string(data.begin() + offset + 28, data.begin() + offset + 34)); member.group = std::stoi(std::string(data.begin() + offset + 34, data.begin() + offset + 40)); member.mode = std::stoi(std::string(data.begin() + offset + 40, data.begin() + offset + 48), nullptr, 8); member.size = std::stoll(std::string(data.begin() + offset + 48, data.begin() + offset + 58)); if (std::string(data.begin() + offset + 58, data.begin() + offset + 60) != "`\n") throw std::runtime_error("Invalid header"); offset += 60; member.content.assign(data.begin() + offset, data.begin() + offset + member.size); members.push_back(member); offset += member.size + (member.size % 2); if (member.name == "debian-binary") { properties["version"] = std::string(member.content.begin(), member.content.end()).substr(0, member.content.size() - 1); } else if (member.name.find("control.tar") == 0) { size_t dot = member.name.rfind('.'); std::string comp = (dot != std::string::npos) ? member.name.substr(dot + 1) : "none"; properties["controlCompression"] = comp; auto tarData = decompress(member.content, comp); auto controlFiles = parseTar(tarData); properties["controlFiles"] = controlFiles; auto it = std::find_if(controlFiles.begin(), controlFiles.end(), [](const TarEntry& e){ return e.name == "./control"; }); std::string controlContent(it != controlFiles.end() ? std::string(it->content.begin(), it->content.end()) : ""); properties["controlFields"] = parseControl(controlContent); } else if (member.name.find("data.tar") == 0) { size_t dot = member.name.rfind('.'); std::string comp = (dot != std::string::npos) ? member.name.substr(dot + 1) : "none"; properties["dataCompression"] = comp; auto tarData = decompress(member.content, comp); properties["dataFiles"] = parseTar(tarData); } } } void printProperties() { std::cout << "DEB Properties:" << std::endl; std::cout << "Magic: " << std::any_cast(properties["magic"]) << std::endl; std::cout << "Version: " << std::any_cast(properties["version"]) << std::endl; std::cout << "Control Compression: " << std::any_cast(properties["controlCompression"]) << std::endl; std::cout << "Control Fields:" << std::endl; auto fields = std::any_cast>(properties["controlFields"]); for (const auto& [key, value] : fields) { std::cout << " " << key << ": " << value << std::endl; } std::cout << "Data Compression: " << std::any_cast(properties["dataCompression"]) << std::endl; std::cout << "Data Files:" << std::endl; auto dataFiles = std::any_cast>(properties["dataFiles"]); for (const auto& file : dataFiles) { std::cout << " Path: " << file.name << ", Mode: " << std::oct << file.mode << ", UID: " << std::dec << file.uid << ", GID: " << file.gid << ", Size: " << file.size << ", MTime: " << std::ctime(&file.mtime); } } void write(const std::string& filepath) { std::ofstream out(filepath, std::ios::binary); out << arMagic; auto members = std::any_cast>(properties["members"]); for (auto& member : members) { if (member.name == "debian-binary") { member.content = {'2', '.', '1', '\n'}; member.size = member.content.size(); member.timestamp = time(nullptr); } out << std::left << std::setw(16) << member.name << std::right << std::setw(12) << member.timestamp << std::setw(6) << member.owner << std::setw(6) << member.group << std::setw(8) << std::oct << member.mode << std::dec << std::setw(10) << member.size << "`\n"; out.write(member.content.data(), member.size); if (member.size % 2) out << '\n'; } // Full write would handle compression } }; // Usage example: // int main() { // DebHandler handler; // handler.open("example.deb"); // handler.printProperties(); // handler.write("modified.deb"); // return 0; // } // ===== end task-134 .DEB ===== // ===== task-135 .DEM [C] ===== #include #include #include typedef struct { char file_name[145]; int dem_level_code; // ... (other properties) } DEMProperties; void read_dem(const char* filepath, DEMProperties* props) { FILE* fp = fopen(filepath, "r"); if (fp) { char buffer[1025]; // For block reads fgets(buffer, 1025, fp); strncpy(props->file_name, buffer, 144); props->file_name[144] = '\0'; // ... (parse using sscanf or strtol on substrings) print_properties(props); fclose(fp); } } void print_properties(const DEMProperties* props) { printf("File Name: %s\n", props->file_name); // ... (print all) } void write_dem(const char* new_filepath, const DEMProperties* props) { FILE* fp = fopen(new_filepath, "w"); if (fp) { fprintf(fp, "%-144s", props->file_name); // ... (fprintf with formats for all) fclose(fp); } } // Usage example: DEMProperties props; read_dem("file.dem", &props); // ===== end task-135 .DEM ===== // ===== task-136 .DGN [C++] ===== #include #include #include #include #include class DGNHandlerC { private: std::string filename; std::map properties; std::vector data; int32_t middleEndianLong(const uint8_t* bytes) { return (bytes[1] << 24) | (bytes[0] << 16) | (bytes[3] << 8) | bytes[2]; } double vaxToIeee(const uint8_t* vax) { // Placeholder double d; memcpy(&d, vax, 8); return d; } public: DGNHandlerC(const std::string& fn) : filename(fn) {} void read() { std::ifstream file(filename, std::ios::binary); file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0); data.resize(size); file.read(reinterpret_cast(data.data()), size); size_t offset = 0; while (offset < size) { uint16_t word1 = *reinterpret_cast(&data[offset]); int type = (word1 >> 1) & 0x7F; offset += 2; uint16_t wordsToFollow = *reinterpret_cast(&data[offset]); offset += 2; if (type == 9) { offset += 24; // Range offset += 4; offset += 18; // Flags offset += 1062; // ViewInfo properties["master_units_per_design"] = std::to_string(middleEndianLong(&data[offset])); offset += 4; // Similar for others... uint8_t flag = data[offset + 90 + 4 + 4 + 4 + 2 + 2]; properties["is_3d"] = (flag & 0x40) ? "3D" : "2D"; // Global origins... break; } offset += wordsToFollow * 2; } } void printProperties() { std::cout << "DGN Properties:" << std::endl; for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::map& newProperties) { // Placeholder update std::cout << "Writing updated properties (placeholder)." << std::endl; std::ofstream file(filename, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); } }; // ===== end task-136 .DGN ===== // ===== task-137 .DICOM [C] ===== #include #include #include #include #include // For byte order (if available; otherwise assume little-endian host) typedef struct { char *meta_names[9]; uint8_t *buffer; size_t buffer_size; } DicomHandler; void init_dicom_handler(DicomHandler *handler) { handler->meta_names[0] = "File Meta Information Group Length"; handler->meta_names[1] = "File Meta Information Version"; handler->meta_names[2] = "Media Storage SOP Class UID"; handler->meta_names[3] = "Media Storage SOP Instance UID"; handler->meta_names[4] = "Transfer Syntax UID"; handler->meta_names[5] = "Implementation Class UID"; handler->meta_names[6] = "Implementation Version Name"; handler->meta_names[7] = "Source Application Entity Title"; handler->meta_names[8] = "Sending Application Entity Title"; handler->buffer = NULL; handler->buffer_size = 0; } void read_dicom(DicomHandler *handler, const char *filepath) { FILE *f = fopen(filepath, "rb"); if (!f) { perror("Failed to open file"); return; } fseek(f, 0, SEEK_END); handler->buffer_size = ftell(f); fseek(f, 0, SEEK_SET); handler->buffer = malloc(handler->buffer_size); fread(handler->buffer, 1, handler->buffer_size, f); fclose(f); printf("File Preamble: 128 bytes\n"); if (strncmp((char*)(handler->buffer + 128), "DICM", 4) != 0) { printf("Invalid DICOM Prefix\n"); free(handler->buffer); handler->buffer = NULL; return; } printf("DICOM Prefix: DICM\n"); size_t offset = 132; uint32_t group_length = 0; while (offset < handler->buffer_size) { uint16_t group = le16toh(*(uint16_t*)(handler->buffer + offset)); if (group != 0x0002) break; uint16_t element = le16toh(*(uint16_t*)(handler->buffer + offset + 2)); char vr[3] = {handler->buffer[offset + 4], handler->buffer[offset + 5], '\0'}; uint32_t length; size_t value_offset; if (strstr("OB OW OF SQ UN UT", vr)) { value_offset = offset + 12; length = le32toh(*(uint32_t*)(handler->buffer + offset + 8)); } else { value_offset = offset + 8; length = le16toh(*(uint16_t*)(handler->buffer + offset + 6)); } char *value = malloc(length + 1); memcpy(value, handler->buffer + value_offset, length); value[length] = '\0'; uint32_t tag = (group << 16) | element; char *name = "Unknown"; switch (tag) { case 0x00020000: name = handler->meta_names[0]; break; case 0x00020001: name = handler->meta_names[1]; break; case 0x00020002: name = handler->meta_names[2]; break; case 0x00020003: name = handler->meta_names[3]; break; case 0x00020010: name = handler->meta_names[4]; break; case 0x00020012: name = handler->meta_names[5]; break; case 0x00020013: name = handler->meta_names[6]; break; case 0x00020016: name = handler->meta_names[7]; break; case 0x00020017: name = handler->meta_names[8]; break; } char *val_str = value; if (strcmp(vr, "UL") == 0) { uint32_t ul_val = le32toh(*(uint32_t*)value); printf("%s (%04x,%04x): %u\n", name, group, element, ul_val); } else if (strcmp(vr, "OB") == 0) { printf("%s (%04x,%04x): [Binary data]\n", name, group, element); } else { printf("%s (%04x,%04x): %s\n", name, group, element, val_str); } if (tag == 0x00020000) { group_length = le32toh(*(uint32_t*)value); } free(value); offset = value_offset + length; } } void write_dicom(DicomHandler *handler, const char *output_filepath) { if (handler->buffer == NULL) { printf("No file read yet\n"); return; } FILE *f = fopen(output_filepath, "wb"); if (!f) { perror("Failed to write file"); return; } fwrite(handler->buffer, 1, handler->buffer_size, f); fclose(f); printf("File written to %s\n", output_filepath); } void free_dicom_handler(DicomHandler *handler) { free(handler->buffer); handler->buffer = NULL; } // Example usage: // int main() { // DicomHandler handler; // init_dicom_handler(&handler); // read_dicom(&handler, "path/to/file.dcm"); // write_dicom(&handler, "path/to/output.dcm"); // free_dicom_handler(&handler); // return 0; // } // ===== end task-137 .DICOM ===== // ===== task-138 .DIF [C++] ===== #include #include #include #include #include #include struct PropertyEntry { int line; std::string value; }; class DIFHandler { private: std::string filename; int version; std::string title; int num_vectors; int num_tuples; std::map> labels; std::map> comments; std::map sizes; std::map periodicities; std::map major_starts; std::map minor_starts; std::map true_lengths; std::map units; std::map display_units; public: DIFHandler(const std::string& fn = "") : filename(fn), version(-1), num_vectors(-1), num_tuples(-1) { if (!filename.empty()) { read(); } } void read() { std::ifstream file(filename); if (!file.is_open()) { std::cerr << "File not found." << std::endl; return; } std::stringstream content; content << file.rdbuf(); decode(content.str()); } void decode(const std::string& content) { std::istringstream iss(content); std::string line; std::vector lines; while (std::getline(iss, line)) { lines.push_back(line); } for (size_t i = 0; i < lines.size() && lines[i] != "DATA"; i += 3) { std::string topic = lines[i]; std::string part_line = lines[i + 1]; size_t comma_pos = part_line.find(','); int vector = std::stoi(part_line.substr(0, comma_pos)); int num_value = std::stoi(part_line.substr(comma_pos + 1)); std::string str_value = lines[i + 2]; str_value = str_value.substr(1, str_value.size() - 2); // Remove quotes if (topic == "TABLE") { version = num_value; title = str_value; } else if (topic == "VECTORS") { num_vectors = num_value; } else if (topic == "TUPLES") { num_tuples = num_value; } else if (topic == "LABEL") { labels[vector].push_back({num_value, str_value}); } else if (topic == "COMMENT") { comments[vector].push_back({num_value, str_value}); } else if (topic == "SIZE") { sizes[vector] = num_value; } else if (topic == "PERIODICITY") { periodicities[vector] = num_value; } else if (topic == "MAJORSTART") { major_starts[vector] = num_value; } else if (topic == "MINORSTART") { minor_starts[vector] = num_value; } else if (topic == "TRUELENGTH") { true_lengths[vector] = num_value; } else if (topic == "UNITS") { units[vector] = str_value; } else if (topic == "DISPLAYUNITS") { display_units[vector] = str_value; } } } void printProperties() { std::cout << "version: " << version << std::endl; std::cout << "title: " << title << std::endl; std::cout << "num_vectors: " << num_vectors << std::endl; std::cout << "num_tuples: " << num_tuples << std::endl; // Print labels std::cout << "labels: "; for (const auto& pair : labels) { std::cout << "vector " << pair.first << ": "; for (const auto& entry : pair.second) { std::cout << "{line: " << entry.line << ", label: " << entry.value << "} "; } } std::cout << std::endl; // Similarly for other maps (omitted for brevity; implement as needed) } void write(const std::string& output_filename, const std::map& new_properties, const std::vector& example_data) { // Update properties if provided (simplified; parse new_properties as needed) std::ofstream file(output_filename); if (!file.is_open()) { std::cerr << "Error opening output file." << std::endl; return; } file << "TABLE\n"; file << "0," << version << "\n"; file << "\"" << title << "\"\n"; file << "VECTORS\n"; file << "0," << num_vectors << "\n"; file << "\"\"\n"; file << "TUPLES\n"; file << "0," << num_tuples << "\n"; file << "\"\"\n"; // Write labels example for (const auto& pair : labels) { for (const auto& entry : pair.second) { file << "LABEL\n"; file << pair.first << "," << entry.line << "\n"; file << "\"" << entry.value << "\"\n"; } } // Similarly for others file << "DATA\n"; file << "0,0\n"; file << "\"\"\n"; if (!example_data.empty()) { file << "-1,0\n"; file << "BOT\n"; for (const auto& cell : example_data) { // Assume string for simplicity file << "1,0\n"; file << "\"" << cell << "\"\n"; } file << "-1,0\n"; file << "EOD\n"; } file.close(); } }; // ===== end task-138 .DIF ===== // ===== task-139 .DIRED [C] ===== #include #include #include #include typedef struct { char *directory; char fileType; char *permissions; int hardLinks; char *owner; char *group; int size; char *month; char *day; char *timeOrYear; char *fileName; char *symlinkTarget; } DiredEntry; typedef struct { char *filepath; DiredEntry *entries; int count; } DiredFileHandler; DiredFileHandler* createHandler(const char *filepath) { DiredFileHandler *handler = malloc(sizeof(DiredFileHandler)); handler->filepath = strdup(filepath); handler->entries = NULL; handler->count = 0; return handler; } void decodeAndRead(DiredFileHandler *handler) { FILE *file = fopen(handler->filepath, "r"); if (!file) return; char line[1024]; char *currentDir = NULL; while (fgets(line, sizeof(line), file)) { char *trimmed = strtok(line, "\n"); if (!trimmed) continue; if (trimmed[strlen(trimmed) - 1] == ':') { free(currentDir); currentDir = strdup(trimmed); currentDir[strlen(currentDir) - 1] = '\0'; } else if (strncmp(trimmed, "total", 5) != 0) { handler->entries = realloc(handler->entries, (handler->count + 1) * sizeof(DiredEntry)); DiredEntry *entry = &handler->entries[handler->count++]; entry->directory = strdup(currentDir); sscanf(trimmed, "%c%9s %d %s %s %d %s %s %s", &entry->fileType, entry->permissions = malloc(10), &entry->hardLinks, entry->owner = malloc(32), entry->group = malloc(32), &entry->size, entry->month = malloc(4), entry->day = malloc(3), entry->timeOrYear = malloc(5)); // Parse file name and symlink char *nameStart = strstr(trimmed, entry->timeOrYear) + strlen(entry->timeOrYear) + 1; char *arrow = strstr(nameStart, " -> "); if (arrow) { entry->fileName = strndup(nameStart, arrow - nameStart); entry->symlinkTarget = strdup(arrow + 4); } else { entry->fileName = strdup(nameStart); entry->symlinkTarget = NULL; } } } free(currentDir); fclose(file); } void printProperties(DiredFileHandler *handler) { for (int i = 0; i < handler->count; i++) { DiredEntry *entry = &handler->entries[i]; printf("Directory: %s\nFile Type: %c\nPermissions: %s\nHard Links: %d\nOwner: %s\nGroup: %s\nSize: %d\nMonth: %s\nDay: %s\nTime/Year: %s\nFile Name: %s\nSymlink Target: %s\n\n", entry->directory, entry->fileType, entry->permissions, entry->hardLinks, entry->owner, entry->group, entry->size, entry->month, entry->day, entry->timeOrYear, entry->fileName, entry->symlinkTarget ? entry->symlinkTarget : "None"); } } void write(DiredFileHandler *handler, const char *newFilepath) { FILE *file = fopen(newFilepath ? newFilepath : handler->filepath, "w"); if (!file) return; char *currentDir = NULL; for (int i = 0; i < handler->count; i++) { DiredEntry *entry = &handler->entries[i]; if (!currentDir || strcmp(entry->directory, currentDir) != 0) { free(currentDir); currentDir = strdup(entry->directory); fprintf(file, "%s:\n", currentDir); fprintf(file, "total 0\n"); // Placeholder } char *symlink = entry->symlinkTarget ? malloc(strlen(entry->symlinkTarget) + 5) : ""; if (entry->symlinkTarget) sprintf(symlink, " -> %s", entry->symlinkTarget); fprintf(file, "%c%s %d %s %s %d %s %s %s %s%s\n", entry->fileType, entry->permissions, entry->hardLinks, entry->owner, entry->group, entry->size, entry->month, entry->day, entry->timeOrYear, entry->fileName, symlink); free(symlink); } free(currentDir); fclose(file); } void destroyHandler(DiredFileHandler *handler) { for (int i = 0; i < handler->count; i++) { free(handler->entries[i].directory); free(handler->entries[i].permissions); free(handler->entries[i].owner); free(handler->entries[i].group); free(handler->entries[i].month); free(handler->entries[i].day); free(handler->entries[i].timeOrYear); free(handler->entries[i].fileName); free(handler->entries[i].symlinkTarget); } free(handler->entries); free(handler->filepath); free(handler); } // Example usage: // int main() { // DiredFileHandler *handler = createHandler("example.dired"); // decodeAndRead(handler); // printProperties(handler); // write(handler, "new.dired"); // destroyHandler(handler); // return 0; // } // ===== end task-139 .DIRED ===== // ===== task-140 .DIVX [C] ===== #include #include #include #include typedef struct { char *filepath; char *data; size_t size; // Properties as key-value (simplified with struct fields) char file_signature[9]; uint32_t file_size; double frame_rate; uint32_t total_frames; uint32_t num_streams; uint32_t video_width; uint32_t video_height; double duration; char video_codec[5]; uint16_t video_bit_depth; char audio_codec[5]; uint16_t audio_channels; uint32_t audio_sample_rate; // Add more fields as needed } DIVXFile; DIVXFile* divx_create(const char *filepath) { DIVXFile *divx = malloc(sizeof(DIVXFile)); divx->filepath = strdup(filepath); return divx; } void divx_read_decode(DIVXFile *divx) { FILE *f = fopen(divx->filepath, "rb"); if (!f) return; fseek(f, 0, SEEK_END); divx->size = ftell(f); fseek(f, 0, SEEK_SET); divx->data = malloc(divx->size); fread(divx->data, 1, divx->size, f); fclose(f); // Parse (simplified) if (strncmp(divx->data, "RIFF", 4) != 0) { printf("Not a valid DIVX/AVI file\n"); return; } strcpy(divx->file_signature, "RIFF AVI "); memcpy(&divx->file_size, divx->data + 4, 4); // Little-endian int offset = 12; while (offset < divx->size) { char chunk_id[5] = {0}; memcpy(chunk_id, divx->data + offset, 4); uint32_t chunk_size; memcpy(&chunk_size, divx->data + offset + 4, 4); if (strcmp(chunk_id, "LIST") == 0) { char list_type[5] = {0}; memcpy(list_type, divx->data + offset + 8, 4); if (strcmp(list_type, "hdrl") == 0) { offset += 12; char sub_chunk[5] = {0}; memcpy(sub_chunk, divx->data + offset, 4); if (strcmp(sub_chunk, "avih") == 0) { uint32_t avih_size; memcpy(&avih_size, divx->data + offset + 4, 4); uint32_t microsec_per_frame; memcpy(µsec_per_frame, divx->data + offset + 8, 4); memcpy(&divx->total_frames, divx->data + offset + 24, 4); memcpy(&divx->num_streams, divx->data + offset + 32, 4); memcpy(&divx->video_width, divx->data + offset + 40, 4); memcpy(&divx->video_height, divx->data + offset + 44, 4); divx->frame_rate = 1000000.0 / microsec_per_frame; divx->duration = divx->total_frames / divx->frame_rate; offset += 8 + avih_size; } // Add strl parsing similarly } } offset += 8 + chunk_size; } // Placeholders strcpy(divx->video_codec, "DIVX"); divx->video_bit_depth = 24; strcpy(divx->audio_codec, "MP3"); divx->audio_channels = 2; divx->audio_sample_rate = 48000; // Print divx_print_properties(divx); } void divx_print_properties(DIVXFile *divx) { printf("File Signature: %s\n", divx->file_signature); printf("File Size: %u\n", divx->file_size); printf("Frame Rate: %.2f\n", divx->frame_rate); printf("Total Frames: %u\n", divx->total_frames); printf("Number of Streams: %u\n", divx->num_streams); printf("Video Width: %u\n", divx->video_width); printf("Video Height: %u\n", divx->video_height); printf("Duration: %.2f\n", divx->duration); printf("Video Codec FourCC: %s\n", divx->video_codec); printf("Video Bit Depth: %u\n", divx->video_bit_depth); printf("Audio Codec: %s\n", divx->audio_codec); printf("Audio Channels: %u\n", divx->audio_channels); printf("Audio Sample Rate: %u\n", divx->audio_sample_rate); // Add more } void divx_write(DIVXFile *divx, const char *new_filepath) { FILE *f = fopen(new_filepath, "wb"); if (f) { fwrite(divx->data, 1, divx->size, f); fclose(f); } } void divx_destroy(DIVXFile *divx) { free(divx->data); free(divx->filepath); free(divx); } // Example usage: // int main() { // DIVXFile *divx = divx_create("sample.divx"); // divx_read_decode(divx); // divx_write(divx, "modified.divx"); // divx_destroy(divx); // return 0; // } // ===== end task-140 .DIVX ===== // ===== task-141 .DMG [C] ===== #include #include #include #include #include #include #include #include // Assume base64 library or implement typedef struct { char signature[5]; uint32_t version; uint32_t headerSize; uint32_t flags; uint64_t runningDataForkOffset; uint64_t dataForkOffset; uint64_t dataForkLength; uint64_t rsrcForkOffset; uint64_t rsrcForkLength; uint32_t segmentNumber; uint32_t segmentCount; uuid_t segmentID; uint32_t dataChecksumType; uint32_t dataChecksumSize; uint8_t dataChecksum[128]; uint64_t xmlOffset; uint64_t xmlLength; uint32_t checksumType; uint32_t checksumSize; uint8_t checksum[128]; uint32_t imageVariant; uint64_t sectorCount; uint32_t reserved2; uint32_t reserved3; uint32_t reserved4; // Plist and blkx would be stored in dynamic arrays/maps; simplified here // For full, use hashmap or structs array } DMGProperties; void parseDMG(const char* filename, DMGProperties* props) { FILE* f = fopen(filename, "rb"); if (!f) return; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, size - 512, SEEK_SET); uint8_t koly[512]; fread(koly, 512, 1, f); uint8_t* p = koly; memcpy(props->signature, p, 4); props->signature[4] = '\0'; p += 4; props->version = *(uint32_t*)p; p += 4; props->headerSize = *(uint32_t*)p; p += 4; props->flags = *(uint32_t*)p; p += 4; props->runningDataForkOffset = *(uint64_t*)p; p += 8; props->dataForkOffset = *(uint64_t*)p; p += 8; props->dataForkLength = *(uint64_t*)p; p += 8; props->rsrcForkOffset = *(uint64_t*)p; p += 8; props->rsrcForkLength = *(uint64_t*)p; p += 8; props->segmentNumber = *(uint32_t*)p; p += 4; props->segmentCount = *(uint32_t*)p; p += 4; memcpy(props->segmentID, p, 16); p += 16; props->dataChecksumType = *(uint32_t*)p; p += 4; props->dataChecksumSize = *(uint32_t*)p; p += 4; memcpy(props->dataChecksum, p, 128); p += 128; props->xmlOffset = *(uint64_t*)p; p += 8; props->xmlLength = *(uint64_t*)p; p += 8; p += 120; // Reserved1 props->checksumType = *(uint32_t*)p; p += 4; props->checksumSize = *(uint32_t*)p; p += 4; memcpy(props->checksum, p, 128); p += 128; props->imageVariant = *(uint32_t*)p; p += 4; props->sectorCount = *(uint64_t*)p; p += 8; props->reserved2 = *(uint32_t*)p; p += 4; props->reserved3 = *(uint32_t*)p; p += 4; props->reserved4 = *(uint32_t*)p; // Parse XML (using libxml2) fseek(f, props->xmlOffset, SEEK_SET); uint8_t* xmlData = malloc(props->xmlLength); fread(xmlData, props->xmlLength, 1, f); xmlDocPtr doc = xmlReadMemory((char*)xmlData, props->xmlLength, NULL, NULL, 0); // Extract plist, blkx, mish (complex parsing; pseudo-code) // For each blkx: base64_decode Data, parse mish struct similarly // Print or store free(xmlData); xmlFreeDoc(doc); fclose(f); printProperties(props); } void printProperties(const DMGProperties* props) { printf("DMG Properties:\n"); printf("Signature: %s\n", props->signature); printf("Version: %u\n", props->version); // ... (print all koly fields) // For plist/blkx: implement loop to print } void writeDMG(const char* filename, DMGProperties* props) { FILE* f = fopen(filename, "rb+"); if (!f) return; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, size - 512, SEEK_SET); uint8_t koly[512] = {0}; uint8_t* p = koly; memcpy(p, props->signature, 4); p += 4; *(uint32_t*)p = props->version; p += 4; *(uint32_t*)p = props->headerSize; p += 4; *(uint32_t*)p = props->flags | 0x1; // Example update // ... (pack all) fwrite(koly, 512, 1, f); fclose(f); printf("File written with updated properties.\n"); } int main(int argc, char** argv) { if (argc < 2) return 1; DMGProperties props; parseDMG(argv[1], &props); // writeDMG(argv[1], &props); return 0; } // ===== end task-141 .DMG ===== // ===== task-142 .DMP [C] ===== #include #include #include #include typedef struct { uint32_t signature; uint32_t version; uint32_t numberOfStreams; uint32_t streamDirectoryRva; uint32_t checksum; uint32_t timeDateStamp; uint64_t flags; } DmpFileHandler; void dmp_init(DmpFileHandler *handler) { handler->signature = 0x504D444D; handler->version = 42899; handler->numberOfStreams = 0; handler->streamDirectoryRva = 32; handler->checksum = 0; handler->timeDateStamp = (uint32_t)time(NULL); handler->flags = 0; } int dmp_read(DmpFileHandler *handler, const char *filepath) { FILE *f = fopen(filepath, "rb"); if (!f) return -1; fread(handler, sizeof(DmpFileHandler), 1, f); fclose(f); if (handler->signature != 0x504D444D) return -2; // Invalid signature return 0; } void dmp_print_properties(const DmpFileHandler *handler) { struct tm *tm = gmtime((time_t *)&handler->timeDateStamp); char date[32]; strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S UTC", tm); printf("Signature: 0x%08X\n", handler->signature); printf("Version: %u\n", handler->version); printf("NumberOfStreams: %u\n", handler->numberOfStreams); printf("StreamDirectoryRva: 0x%08X\n", handler->streamDirectoryRva); printf("CheckSum: 0x%08X\n", handler->checksum); printf("TimeDateStamp: %s\n", date); printf("Flags: 0x%016llX\n", (unsigned long long)handler->flags); } int dmp_write(const DmpFileHandler *handler, const char *filepath) { FILE *f = fopen(filepath, "wb"); if (!f) return -1; fwrite(handler, sizeof(DmpFileHandler), 1, f); fclose(f); return 0; } int main() { DmpFileHandler handler; dmp_init(&handler); if (dmp_read(&handler, "sample.dmp") == 0) { dmp_print_properties(&handler); dmp_write(&handler, "new.dmp"); } return 0; } // ===== end task-142 .DMP ===== // ===== task-143 .DN [C] ===== #include #include #include #include // Assuming libzip or minizip library typedef struct { char* filepath; char** properties; int prop_count; } DNFileHandler; DNFileHandler* create_dn_handler(const char* filepath) { DNFileHandler* handler = malloc(sizeof(DNFileHandler)); handler->filepath = strdup(filepath); handler->properties = NULL; handler->prop_count = 0; return handler; } void destroy_dn_handler(DNFileHandler* handler) { free(handler->filepath); for (int i = 0; i < handler->prop_count; i++) { free(handler->properties[i]); } free(handler->properties); free(handler); } int open_and_decode(DNFileHandler* handler) { if (strstr(handler->filepath, ".dn") == NULL) { fprintf(stderr, "File must have .dn extension.\n"); return 1; } zip_t* zf = zip_open(handler->filepath, ZIP_RDONLY, NULL); if (!zf) { fprintf(stderr, "Error opening ZIP.\n"); return 1; } int num_entries = zip_get_num_entries(zf, 0); handler->properties = malloc(num_entries * sizeof(char*)); for (int i = 0; i < num_entries; i++) { const char* name = zip_get_name(zf, i, 0); handler->properties[i] = strdup(name); handler->prop_count++; } zip_close(zf); printf("Decoded properties:\n"); for (int i = 0; i < handler->prop_count; i++) { printf("- %s\n", handler->properties[i]); } return 0; } void read(DNFileHandler* handler) { if (handler->prop_count == 0) { printf("No properties decoded yet. Call open_and_decode first.\n"); } else { printf("Read properties:\n"); for (int i = 0; i < handler->prop_count; i++) { printf("- %s\n", handler->properties[i]); } } } int write_dn(DNFileHandler* handler, const char* new_filepath, const char** files_to_add, int add_count) { if (strstr(new_filepath, ".dn") == NULL) { fprintf(stderr, "New file must have .dn extension.\n"); return 1; } zip_t* zf = zip_open(new_filepath, ZIP_CREATE | ZIP_TRUNCATE, NULL); if (!zf) { fprintf(stderr, "Error creating ZIP.\n"); return 1; } for (int i = 0; i < add_count; i++) { zip_source_t* src = zip_source_file(zf, files_to_add[i], 0, 0); if (src == NULL || zip_file_add(zf, strrchr(files_to_add[i], '/') + 1, src, ZIP_FL_OVERWRITE) < 0) { zip_source_free(src); zip_close(zf); fprintf(stderr, "Error adding file.\n"); return 1; } } zip_close(zf); printf("New .DN file written to %s with %d properties.\n", new_filepath, add_count); return 0; } // Example usage: // int main() { // DNFileHandler* handler = create_dn_handler("example.dn"); // open_and_decode(handler); // read(handler); // const char* files[] = {"model.obj", "material.mdl"}; // write_dn(handler, "new.dn", files, 2); // destroy_dn_handler(handler); // return 0; // } // ===== end task-143 .DN ===== // ===== task-144 .DNG [C++] ===== #include #include #include #include #include #include class DNGParser { private: std::string filepath; std::vector data; bool littleEndian; std::map tags; uint16_t readUint16(size_t offset) { uint16_t val = (data[offset] | (data[offset+1] << 8)); if (!littleEndian) val = (data[offset+1] | (data[offset] << 8)); return val; } uint32_t readUint32(size_t offset) { uint32_t val = (data[offset] | (data[offset+1] << 8) | (data[offset+2] << 16) | (data[offset+3] << 24)); if (!littleEndian) val = (data[offset+3] | (data[offset+2] << 8) | (data[offset+1] << 16) | (data[offset] << 24)); return val; } public: DNGParser(const std::string& filepath) : filepath(filepath) { std::ifstream file(filepath, std::ios::binary); if (file) { file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(reinterpret_cast(data.data()), size); } std::string byteOrder(reinterpret_cast(data.data()), 2); littleEndian = (byteOrder == "II"); uint16_t magic = readUint16(2); if (magic != 42) { throw std::runtime_error("Invalid TIFF magic number"); } parseIFDs(readUint32(4)); } void parseIFDs(uint32_t offset) { while (offset != 0) { uint16_t numEntries = readUint16(offset); offset += 2; for (uint16_t i = 0; i < numEntries; ++i) { size_t entryOffset = offset + i * 12; uint16_t tag = readUint16(entryOffset); uint16_t typ = readUint16(entryOffset + 2); uint32_t count = readUint32(entryOffset + 4); uint32_t valOffset = readUint32(entryOffset + 8); auto it = getDNGTagMap().find(tag); if (it != getDNGTagMap().end()) { std::string value = readTagValue(typ, count, valOffset); tags[it->second] = value; } } offset += numEntries * 12; offset = readUint32(offset); } } std::string readTagValue(uint16_t typ, uint32_t count, uint32_t offset) { std::string val; if (typ == 1 || typ == 7) { // BYTE/UNDEF for (uint32_t i = 0; i < count; ++i) { val += std::to_string(data[offset + i]) + " "; } } else if (typ == 2) { // ASCII val = std::string(reinterpret_cast(data.data() + offset), count).c_str(); } else if (typ == 3) { // SHORT val = std::to_string(readUint16(offset)); } else if (typ == 4) { // LONG val = std::to_string(readUint32(offset)); } else if (typ == 5) { // RATIONAL uint32_t num = readUint32(offset); uint32_t den = readUint32(offset + 4); val = std::to_string(num) + "/" + std::to_string(den); } // Add more return val; } std::map getDNGTagMap() { std::map map; map[50706] = "DNGVersion"; map[50707] = "DNGBackwardVersion"; // Include all... map[51182] = "EnhanceParams"; return map; } void printProperties() { for (const auto& pair : tags) { std::cout << pair.first << ": " << pair.second << std::endl; } } void writeFile(const std::string& outputPath) { std::ofstream file(outputPath, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); std::cout << "File written to " << outputPath << std::endl; } }; // Example usage: // int main() { // DNGParser parser("example.dng"); // parser.printProperties(); // parser.writeFile("modified.dng"); // return 0; // } // ===== end task-144 .DNG ===== // ===== task-145 .DO [C++] ===== #include #include #include #include #include class DOFileHandler { private: std::string filepath; public: DOFileHandler(const std::string& fp) : filepath(fp) {} void readProperties() { struct stat fileStat; if (stat(filepath.c_str(), &fileStat) == 0) { std::cout << "File Name: " << filepath.substr(filepath.find_last_of("/\\") + 1) << std::endl; std::cout << "File Size: " << fileStat.st_size << std::endl; std::cout << "Creation Time: " << std::ctime(&fileStat.st_ctime); std::cout << "Modification Time: " << std::ctime(&fileStat.st_mtime); std::cout << "Access Time: " << std::ctime(&fileStat.st_atime); std::cout << "Owner UID: " << fileStat.st_uid << std::endl; std::cout << "Group GID: " << fileStat.st_gid << std::endl; std::cout << "Permissions: " << std::oct << (fileStat.st_mode & 0777) << std::endl; std::cout << "Inode Number: " << fileStat.st_ino << std::endl; } else { std::cerr << "Error retrieving properties." << std::endl; } } std::string readContent() { std::ifstream file(filepath); if (file) { std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); return content; } return ""; } void writeContent(const std::string& content) { std::ofstream file(filepath); if (file) { file << content; } } }; // Example usage: // int main() { // DOFileHandler handler("example.do"); // handler.readProperties(); // std::string content = handler.readContent(); // handler.writeContent(content + "\n// New comment"); // return 0; // } // ===== end task-145 .DO ===== // ===== task-146 .DOC [C++] ===== #include #include #include #include #include class DocPropertyHandler { private: std::string filepath; std::vector data; std::map> properties; bool checkMagic() { unsigned char magic[8] = {0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1}; for (int i = 0; i < 8; ++i) if (data[i] != magic[i]) return false; return true; } void parseProperties() { // Simplified parser: read bytes, unpack structures. // Stub for full implementation. } public: DocPropertyHandler(const std::string& fp) : filepath(fp) { std::ifstream file(filepath, std::ios::binary); data = std::vector((std::istreambuf_iterator(file)), std::istreambuf_iterator()); if (!checkMagic()) { throw std::runtime_error("Not a valid .DOC file"); } parseProperties(); } void printProperties() { for (const auto& cat : properties) { std::cout << cat.first << " Properties:" << std::endl; for (const auto& prop : cat.second) { std::cout << " " << prop.first << ": " << prop.second << std::endl; } } } void write(const std::string& newFilepath, const std::map>& modified) { // Stub: Modify data vector, write to file. std::ofstream out(newFilepath, std::ios::binary); out.write(reinterpret_cast(data.data()), data.size()); } }; // Example usage: // int main() { // DocPropertyHandler handler("sample.doc"); // handler.printProperties(); // handler.write("modified.doc", {}); // return 0; // } // ===== end task-146 .DOC ===== // ===== task-147 .DOCM [C++] ===== #include #include #include #include "miniz.h" // Assume miniz for ZIP #include "tinyxml2.h" // Assume tinyxml2 for XML class DocmHandler { private: std::string filepath; mz_zip_archive zip; std::map coreProps; std::map extProps; public: DocmHandler(const std::string& fp) : filepath(fp) { memset(&zip, 0, sizeof(zip)); } ~DocmHandler() { close(); } bool open() { return mz_zip_reader_init_file(&zip, filepath.c_str(), 0); } void readProperties() { size_t coreSize; void* coreData = mz_zip_reader_extract_file_to_heap(&zip, "docProps/core.xml", &coreSize, 0); size_t extSize; void* extData = mz_zip_reader_extract_file_to_heap(&zip, "docProps/app.xml", &extSize, 0); tinyxml2::XMLDocument coreDoc; coreDoc.Parse(static_cast(coreData), coreSize); tinyxml2::XMLDocument extDoc; extDoc.Parse(static_cast(extData), extSize); for (tinyxml2::XMLElement* elem = coreDoc.FirstChildElement()->FirstChildElement(); elem; elem = elem->NextSiblingElement()) { coreProps[elem->Name()] = elem->GetText() ? elem->GetText() : ""; } for (tinyxml2::XMLElement* elem = extDoc.FirstChildElement()->FirstChildElement(); elem; elem = elem->NextSiblingElement()) { extProps[elem->Name()] = elem->GetText() ? elem->GetText() : ""; } free(coreData); free(extData); } void printProperties() { std::cout << "Core Properties:" << std::endl; for (const auto& prop : coreProps) { std::cout << prop.first << ": " << prop.second << std::endl; } std::cout << "\nExtended Properties:" << std::endl; for (const auto& prop : extProps) { std::cout << prop.first << ": " << prop.second << std::endl; } } void writeProperties(const std::map& newCore, const std::map& newExt, const std::string& outputPath) { mz_zip_archive outZip; memset(&outZip, 0, sizeof(outZip)); mz_zip_writer_init_file(&outZip, outputPath.c_str(), 0); for (mz_uint i = 0; i < mz_zip_reader_get_num_files(&zip); ++i) { mz_zip_archive_file_stat stat; mz_zip_reader_file_stat(&zip, i, &stat); size_t size; void* data = mz_zip_reader_extract_to_heap(&zip, i, &size, 0); if (std::string(stat.m_filename) == "docProps/core.xml") { tinyxml2::XMLDocument doc; doc.Parse(static_cast(data), size); for (const auto& kv : newCore) { tinyxml2::XMLElement* elem = doc.FirstChildElement()->FirstChildElement(kv.first.c_str()); if (elem) elem->SetText(kv.second.c_str()); } tinyxml2::XMLPrinter printer; doc.Print(&printer); free(data); data = strdup(printer.CStr()); size = printer.CStrSize() - 1; } else if (std::string(stat.m_filename) == "docProps/app.xml") { tinyxml2::XMLDocument doc; doc.Parse(static_cast(data), size); for (const auto& kv : newExt) { tinyxml2::XMLElement* elem = doc.FirstChildElement()->FirstChildElement(kv.first.c_str()); if (elem) elem->SetText(kv.second.c_str()); } tinyxml2::XMLPrinter printer; doc.Print(&printer); free(data); data = strdup(printer.CStr()); size = printer.CStrSize() - 1; } mz_zip_writer_add_mem(&outZip, stat.m_filename, data, size, MZ_DEFAULT_COMPRESSION); free(data); } mz_zip_writer_finalize_archive(&outZip); mz_zip_writer_end(&outZip); } void close() { mz_zip_reader_end(&zip); } }; // Example usage: // int main() { // DocmHandler handler("example.docm"); // if (handler.open()) { // handler.readProperties(); // handler.printProperties(); // std::map newCore = {{"title", "New Title"}}; // std::map newExt = {{"Pages", "10"}}; // handler.writeProperties(newCore, newExt, "modified.docm"); // } // return 0; // } // ===== end task-147 .DOCM ===== // ===== task-148 .DOCX [C++] ===== #include #include #include #include #include #include #include class DocxProperties { private: std::string filepath; std::map properties; void readProperties() { zip_t* z = zip_open(filepath.c_str(), ZIP_RDONLY, nullptr); if (!z) { throw std::runtime_error("Failed to open ZIP."); } zip_file_t* f = zip_fopen(z, "docProps/core.xml", 0); if (!f) { zip_close(z); throw std::runtime_error("No core.xml found."); } zip_stat_t sb; zip_stat(z, "docProps/core.xml", 0, &sb); std::vector buffer(sb.size); zip_fread(f, buffer.data(), sb.size); zip_fclose(f); zip_close(z); tinyxml2::XMLDocument doc; doc.Parse(buffer.data(), sb.size); tinyxml2::XMLElement* root = doc.FirstChildElement("cp:coreProperties"); if (root) { const char* ns[] = {"cp", "dc", "dcterms"}; std::string tags[] = {"category", "contentStatus", "contentType", "created", "creator", "description", "identifier", "keywords", "language", "lastModifiedBy", "lastPrinted", "modified", "revision", "subject", "title", "version"}; for (const auto& tag : tags) { tinyxml2::XMLElement* elem = nullptr; for (const auto& prefix : ns) { std::string qualified = std::string(prefix) + ":" + tag; elem = root->FirstChildElement(qualified.c_str()); if (elem) break; } if (elem && elem->GetText()) { properties[tag] = elem->GetText(); } } } } public: DocxProperties(const std::string& filepath) : filepath(filepath) { readProperties(); } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void setProperty(const std::string& key, const std::string& value) { if (properties.find(key) != properties.end()) { properties[key] = value; } else { throw std::invalid_argument("Invalid property: " + key); } } void writeProperties(const std::string& outputPath) { zip_t* zIn = zip_open(filepath.c_str(), ZIP_RDONLY, nullptr); if (!zIn) { throw std::runtime_error("Failed to open input ZIP."); } zip_t* zOut = zip_open(outputPath.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); if (!zOut) { zip_close(zIn); throw std::runtime_error("Failed to create output ZIP."); } int numEntries = zip_get_num_entries(zIn, 0); for (int i = 0; i < numEntries; ++i) { const char* name = zip_get_name(zIn, i, 0); if (std::string(name) == "docProps/core.xml") { tinyxml2::XMLDocument doc; tinyxml2::XMLElement* root = doc.NewElement("cp:coreProperties"); root->SetAttribute("xmlns:cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); root->SetAttribute("xmlns:dc", "http://purl.org/dc/elements/1.1/"); root->SetAttribute("xmlns:dcterms", "http://purl.org/dc/terms/"); root->SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); doc.InsertFirstChild(root); for (const auto& pair : properties) { const std::string& key = pair.first; const std::string& value = pair.second; tinyxml2::XMLElement* elem; if (key == "created" || key == "modified") { elem = doc.NewElement(("dcterms:" + key).c_str()); elem->SetAttribute("xsi:type", "dcterms:W3CDTF"); } else if (key == "creator" || key == "description" || key == "identifier" || key == "keywords" || key == "language") { elem = doc.NewElement(("dc:" + key).c_str()); } else { elem = doc.NewElement(("cp:" + key).c_str()); } elem->SetText(value.c_str()); root->InsertEndChild(elem); } tinyxml2::XMLPrinter printer; doc.Print(&printer); std::string xmlStr = "\n" + std::string(printer.CStr()); zip_source_t* src = zip_source_buffer(zOut, xmlStr.c_str(), xmlStr.size(), 0); if (zip_file_add(zOut, name, src, ZIP_FL_OVERWRITE | ZIP_FL_ENC_UTF_8) < 0) { zip_source_free(src); throw std::runtime_error("Failed to add core.xml."); } } else { zip_source_t* src = zip_source_zip(zOut, zIn, i, 0, 0, -1); if (zip_file_add(zOut, name, src, ZIP_FL_ENC_GUESS) < 0) { zip_source_free(src); throw std::runtime_error("Failed to copy file."); } } } zip_close(zOut); zip_close(zIn); } }; // ===== end task-148 .DOCX ===== // ===== task-149 .DOT [C++] ===== #include #include #include #include #include class DotFile { private: std::string content; std::map properties; public: DotFile(const std::string& filename) { std::ifstream file(filename); if (file.is_open()) { std::string line; while (std::getline(file, line)) { content += line + "\n"; } file.close(); decode(); } } void decode() { std::regex regex(R"((\w+)\s*=\s*(".*?"|[^;,\s\]]+))"); std::sregex_iterator iter(content.begin(), content.end(), regex); std::sregex_iterator end; for (; iter != end; ++iter) { std::string key = iter->str(1); std::string value = iter->str(2); value.erase(std::remove(value.begin(), value.end(), '"'), value.end()); properties[key] = value; } } std::map read() { return properties; } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void setProperty(const std::string& key, const std::string& value) { if (properties.find(key) == properties.end()) { content += "\n" + key + " = \"" + value + "\";"; } else { std::regex replace_regex(key + R"(\s*=\s*(".*?"|[^;]+))"); content = std::regex_replace(content, replace_regex, key + " = \"" + value + "\""); } properties[key] = value; } void write(const std::string& filename) { std::ofstream file(filename); if (file.is_open()) { file << content; file.close(); } } }; // ===== end task-149 .DOT ===== // ===== task-150 .DOTX [C++] ===== #include #include #include #include #include class DotxPropertyHandler { private: std::string filepath; std::map properties; public: DotxPropertyHandler(const std::string& fp) : filepath(fp) { readProperties(); } void readProperties() { zip_t* z = zip_open(filepath.c_str(), 0, nullptr); if (z) { zip_file_t* coreFile = zip_fopen(z, "docProps/core.xml", 0); if (coreFile) { // Read buffer, load into tinyxml2::XMLDocument tinyxml2::XMLDocument doc; // doc.Parse(buffer); // properties["Title"] = doc.FirstChildElement("cp:coreProperties")->FirstChildElement("dc:title")->GetText(); // Add others... zip_fclose(coreFile); } // Similar for app and custom... zip_close(z); } } void printProperties() { for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } void writeProperties(const std::map& newProps, const std::string& outputPath) { // Open zip, extract, modify XML with tinyxml2, add back to new zip archive. // Details omitted. } }; // Usage in main: DotxPropertyHandler handler("example.dotx"); handler.printProperties(); // ===== end task-150 .DOTX ===== // ===== task-152 .DPX [C++] ===== #include #include #include #include #include #include // For endian conversion if needed class DPXFile { private: std::string filepath; std::map properties; bool bigEndian = true; std::vector headerData; std::ifstream file; public: DPXFile(const std::string& fp) : filepath(fp) { file.open(filepath, std::ios::binary); if (!file) throw std::runtime_error("Cannot open file"); headerData.resize(2304); file.read(headerData.data(), 2304); if (file.gcount() < 2304) throw std::runtime_error("Invalid DPX file"); uint32_t magic; memcpy(&magic, headerData.data(), 4); if (magic == 0x53445058) bigEndian = true; else if (magic == 0x58504453) bigEndian = false; else throw std::runtime_error("Invalid magic number"); parseHeader(); file.close(); } void parseHeader() { // Helper functions auto getU32 = [&](size_t off) -> uint32_t { uint32_t val; memcpy(&val, headerData.data() + off, 4); return bigEndian ? be32toh(val) : le32toh(val); }; auto getU16 = [&](size_t off) -> uint16_t { uint16_t val; memcpy(&val, headerData.data() + off, 2); return bigEndian ? be16toh(val) : le16toh(val); }; auto getU8 = [&](size_t off) -> uint8_t { return static_cast(headerData[off]); }; auto getR32 = [&](size_t off) -> float { uint32_t val = getU32(off); float f; memcpy(&f, &val, 4); return f; }; auto getStr = [&](size_t off, size_t len) -> std::string { std::string str(headerData.begin() + off, headerData.begin() + off + len); str = str.substr(0, str.find('\0')); return str; }; properties["Magic number"] = getStr(0, 4); properties["Offset to image data"] = std::to_string(getU32(4)); properties["Version"] = getStr(8, 8); properties["File size"] = std::to_string(getU32(16)); properties["Ditto key"] = std::to_string(getU32(20)); properties["Generic header length"] = std::to_string(getU32(24)); properties["Industry header length"] = std::to_string(getU32(28)); properties["User header length"] = std::to_string(getU32(32)); properties["File name"] = getStr(36, 100); properties["Creation date/time"] = getStr(136, 24); properties["Creator"] = getStr(160, 100); properties["Project"] = getStr(260, 200); properties["Copyright"] = getStr(460, 200); properties["Encryption key"] = std::to_string(getU32(660)); properties["Image orientation"] = std::to_string(getU16(768)); uint16_t numElem = getU16(770); properties["Number of image elements"] = std::to_string(numElem); properties["Pixels per line"] = std::to_string(getU32(772)); properties["Lines per image element"] = std::to_string(getU32(776)); for (uint16_t i = 0; i < numElem; ++i) { size_t off = 780 + i * 72; std::string prefix = "Image Element " + std::to_string(i + 1) + " "; properties[prefix + "Data sign"] = std::to_string(getU32(off)); properties[prefix + "Reference low data code"] = std::to_string(getU32(off + 4)); properties[prefix + "Reference low quantity"] = std::to_string(getR32(off + 8)); properties[prefix + "Reference high data code"] = std::to_string(getU32(off + 12)); properties[prefix + "Reference high quantity"] = std::to_string(getR32(off + 16)); properties[prefix + "Descriptor"] = std::to_string(getU8(off + 20)); properties[prefix + "Transfer characteristic"] = std::to_string(getU8(off + 21)); properties[prefix + "Colorimetric specification"] = std::to_string(getU8(off + 22)); properties[prefix + "Bit depth"] = std::to_string(getU8(off + 23)); properties[prefix + "Packing"] = std::to_string(getU16(off + 24)); properties[prefix + "Encoding"] = std::to_string(getU16(off + 26)); properties[prefix + "Data offset"] = std::to_string(getU32(off + 28)); properties[prefix + "End-of-line padding"] = std::to_string(getU32(off + 32)); properties[prefix + "End-of-image padding"] = std::to_string(getU32(off + 36)); properties[prefix + "Description"] = getStr(off + 40, 32); } properties["X offset"] = std::to_string(getU32(1600)); properties["Y offset"] = std::to_string(getU32(1604)); properties["X center"] = std::to_string(getR32(1608)); properties["Y center"] = std::to_string(getR32(1612)); properties["X original size"] = std::to_string(getU32(1616)); properties["Y original size"] = std::to_string(getU32(1620)); properties["Source image filename"] = getStr(1624, 100); properties["Source image date/time"] = getStr(1724, 24); properties["Input device name"] = getStr(1748, 32); properties["Input device serial number"] = getStr(1780, 32); properties["Border validity XL"] = std::to_string(getU16(1812)); properties["Border validity XR"] = std::to_string(getU16(1814)); properties["Border validity YT"] = std::to_string(getU16(1816)); properties["Border validity YB"] = std::to_string(getU16(1818)); properties["Aspect ratio horizontal"] = std::to_string(getU32(1820)); properties["Aspect ratio vertical"] = std::to_string(getU32(1824)); properties["X scanned size"] = std::to_string(getR32(1828)); properties["Y scanned size"] = std::to_string(getR32(1832)); properties["Film manufacturer ID"] = std::to_string(getU16(1920)); properties["Film type"] = std::to_string(getU16(1922)); properties["Perfs offset"] = std::to_string(getU16(1924)); properties["Prefix"] = std::to_string(getU32(1926)); properties["Count"] = std::to_string(getU32(1932)); properties["Format"] = getStr(1936, 32); properties["Frame position"] = std::to_string(getU32(1968)); properties["Sequence length"] = std::to_string(getU32(1972)); properties["Held count"] = std::to_string(getU32(1976)); properties["Frame rate"] = std::to_string(getR32(1980)); properties["Shutter angle"] = std::to_string(getR32(1984)); properties["Frame identification"] = getStr(1988, 32); properties["Slate info"] = getStr(2020, 100); properties["Time code"] = std::to_string(getU32(2176)); properties["User bits"] = std::to_string(getU32(2180)); properties["Interlace"] = std::to_string(getU8(2184)); properties["Field number"] = std::to_string(getU8(2185)); properties["Video signal"] = std::to_string(getU8(2186)); properties["Zero"] = std::to_string(getU8(2187)); properties["Horizontal sample rate"] = std::to_string(getR32(2188)); properties["Vertical sample rate"] = std::to_string(getR32(2192)); properties["Temporal frame rate"] = std::to_string(getR32(2196)); properties["Time offset"] = std::to_string(getR32(2200)); properties["Gamma"] = std::to_string(getR32(2204)); properties["Black level"] = std::to_string(getR32(2208)); properties["Black gain"] = std::to_string(getR32(2212)); properties["Breakpoint"] = std::to_string(getR32(2216)); properties["White level"] = std::to_string(getR32(2220)); properties["Integration times"] = std::to_string(getR32(2224)); } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& outputPath) { std::ofstream out(outputPath, std::ios::binary); out.write(headerData.data(), headerData.size()); // To write full file std::ifstream orig(filepath, std::ios::binary); orig.seekg(getU32(4), std::ios::beg); char buf[1024]; while (orig.read(buf, 1024)) { out.write(buf, orig.gcount()); } out.close(); } private: uint32_t getU32(size_t off) { uint32_t val; memcpy(&val, headerData.data() + off, 4); return bigEndian ? be32toh(val) : le32toh(val); } }; // Usage: DPXFile dpx("example.dpx"); dpx.printProperties(); dpx.write("output.dpx"); // ===== end task-152 .DPX ===== // ===== task-153 .DRC [C++] ===== #include #include #include #include #include class DRCFile { private: std::string filepath; std::string magic; uint8_t major_version; uint8_t minor_version; std::string encoder_type; std::string encoder_method; uint16_t flags; bool has_metadata; // Add other properties... public: DRCFile(const std::string& fp = "") : filepath(fp) { if (!fp.empty()) decode(); } uint32_t read_var_ui32(std::ifstream& ifs) { uint32_t value = 0; int shift = 0; while (true) { uint8_t byte; ifs.read(reinterpret_cast(&byte), 1); value |= (byte & 0x7F) << shift; if ((byte & 0x80) == 0) break; shift += 7; } return value; } void decode() { std::ifstream ifs(filepath, std::ios::binary); if (!ifs) return; char mag[6]; ifs.read(mag, 5); mag[5] = '\0'; magic = mag; if (magic != "DRACO") { std::cerr << "Invalid DRC file" << std::endl; return; } ifs.read(reinterpret_cast(&major_version), 1); ifs.read(reinterpret_cast(&minor_version), 1); uint8_t enc_type; ifs.read(reinterpret_cast(&enc_type), 1); encoder_type = (enc_type == 0) ? "POINT_CLOUD" : "TRIANGULAR_MESH"; uint8_t enc_method; ifs.read(reinterpret_cast(&enc_method), 1); encoder_method = (enc_method == 0) ? "MESH_SEQUENTIAL_ENCODING" : "MESH_EDGEBREAKER_ENCODING"; ifs.read(reinterpret_cast(&flags), 2); has_metadata = (flags & 32768) != 0; // Metadata, etc. parsing (similar logic) } void print_properties() { std::cout << "Magic: " << magic << std::endl; std::cout << "Major Version: " << static_cast(major_version) << std::endl; std::cout << "Minor Version: " << static_cast(minor_version) << std::endl; std::cout << "Encoder Type: " << encoder_type << std::endl; std::cout << "Encoder Method: " << encoder_method << std::endl; std::cout << "Flags: " << flags << std::endl; std::cout << "Has Metadata: " << (has_metadata ? "Yes" : "No") << std::endl; // Print others... } void write(const std::string& output_path) { std::ofstream ofs(output_path, std::ios::binary); ofs.write("DRACO", 5); ofs.write(reinterpret_cast(&major_version), 1); ofs.write(reinterpret_cast(&minor_version), 1); uint8_t enc_type = (encoder_type == "POINT_CLOUD") ? 0 : 1; ofs.write(reinterpret_cast(&enc_type), 1); uint8_t enc_method = (encoder_method == "MESH_SEQUENTIAL_ENCODING") ? 0 : 1; ofs.write(reinterpret_cast(&enc_method), 1); ofs.write(reinterpret_cast(&flags), 2); // Add more } }; int main(int argc, char** argv) { if (argc > 1) { DRCFile drc(argv[1]); drc.print_properties(); } return 0; } // ===== end task-153 .DRC ===== // ===== task-154 .DSC [C++] ===== #include #include #include #include #include class DscFile { private: std::map properties; public: DscFile(const std::string& filepath = "") { if (!filepath.empty()) { read(filepath); } } void read(const std::string& filepath) { properties.clear(); std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Failed to open " << filepath << std::endl; return; } std::string line; std::string currentKey; std::string value; while (std::getline(file, line)) { std::string trimmed = line; trimmed.erase(0, trimmed.find_first_not_of(" \t")); if (trimmed.find("-----BEGIN PGP") == 0) { // Skip signature break; } std::regex keyRegex("^([A-Za-z-]+):"); std::smatch match; if (std::regex_search(trimmed, match, keyRegex) && match.position() == 0) { if (!currentKey.empty()) { properties[currentKey] = value; } currentKey = match[1].str(); value = trimmed.substr(match[0].length()); value.erase(0, value.find_first_not_of(" \t")); } else if (!currentKey.empty() && !trimmed.empty()) { value += "\n" + trimmed; } } if (!currentKey.empty()) { properties[currentKey] = value; } file.close(); std::cout << "Read " << properties.size() << " properties from " << filepath << std::endl; } void printProperties() const { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& filepath) const { std::ofstream file(filepath); if (!file.is_open()) { std::cerr << "Failed to write to " << filepath << std::endl; return; } for (const auto& pair : properties) { file << pair.first << ": " << pair.second << "\n"; } file.close(); std::cout << "Wrote properties to " << filepath << std::endl; } }; // Example usage: // int main() { // DscFile dsc("example.dsc"); // dsc.printProperties(); // dsc.write("output.dsc"); // return 0; // } // ===== end task-154 .DSC ===== // ===== task-155 .DTA [C] ===== #include #include #include #include #include typedef struct { char *release; char *byteorder; bool is_big_endian; uint16_t K; uint64_t N; char *label; char *timestamp; uint64_t map[14]; // Other properties... uint8_t *data; size_t data_len; size_t pos; } DtaFile; DtaFile* dta_new() { DtaFile* dta = malloc(sizeof(DtaFile)); memset(dta, 0, sizeof(DtaFile)); dta->byteorder = strdup("LSF"); return dta; } void dta_free(DtaFile* dta) { free(dta->release); free(dta->byteorder); free(dta->label); free(dta->timestamp); free(dta->data); free(dta); } bool find_tag(DtaFile* dta, const char* tag) { size_t tag_len = strlen(tag); while (dta->pos < dta->data_len - tag_len + 1) { if (memcmp(dta->data + dta->pos, tag, tag_len) == 0) { dta->pos += tag_len; return true; } dta->pos++; } return false; } char* read_string(DtaFile* dta, size_t len) { char* str = malloc(len + 1); memcpy(str, dta->data + dta->pos, len); str[len] = '\0'; char* null_pos = memchr(str, '\0', len); if (null_pos) *null_pos = '\0'; dta->pos += len; return str; } uint64_t read_uint(DtaFile* dta, int bytes) { uint64_t val = 0; if (dta->is_big_endian) { for (int i = 0; i < bytes; i++) { val = (val << 8) | dta->data[dta->pos + i]; } } else { for (int i = bytes - 1; i >= 0; i--) { val = (val << 8) | dta->data[dta->pos + i]; } } dta->pos += bytes; return val; } void parse_header(DtaFile* dta) { find_tag(dta, "
"); find_tag(dta, ""); dta->release = read_string(dta, 3); find_tag(dta, ""); find_tag(dta, ""); free(dta->byteorder); dta->byteorder = read_string(dta, 3); dta->is_big_endian = strcmp(dta->byteorder, "MSF") == 0; find_tag(dta, ""); find_tag(dta, ""); dta->K = (uint16_t) read_uint(dta, 2); find_tag(dta, ""); find_tag(dta, ""); dta->N = read_uint(dta, 8); find_tag(dta, ""); find_tag(dta, ""); find_tag(dta, ""); uint8_t ts_len = (uint8_t) read_uint(dta, 1); dta->timestamp = ts_len ? read_string(dta, ts_len) : strdup(""); find_tag(dta, ""); find_tag(dta, "
"); } void parse_map(DtaFile* dta) { find_tag(dta, ""); for (int i = 0; i < 14; i++) { dta->map[i] = read_uint(dta, 8); } find_tag(dta, ""); } void dta_load(DtaFile* dta, const char* filename) { FILE* f = fopen(filename, "rb"); fseek(f, 0, SEEK_END); dta->data_len = ftell(f); fseek(f, 0, SEEK_SET); dta->data = malloc(dta->data_len); fread(dta->data, 1, dta->data_len, f); fclose(f); dta->pos = 0; parse_header(dta); parse_map(dta); // Add other parses. } void dta_print_properties(DtaFile* dta) { printf("Release: %s\n", dta->release); printf("Byte Order: %s\n", dta->byteorder); printf("Number of Variables (K): %u\n", dta->K); printf("Number of Observations (N): %lu\n", dta->N); printf("Dataset Label: %s\n", dta->label); printf("Timestamp: %s\n", dta->timestamp); printf("Map Offsets: "); for (int i = 0; i < 14; i++) printf("%lu ", dta->map[i]); printf("\n"); // Add others. } void dta_save(DtaFile* dta, const char* filename) { FILE* f = fopen(filename, "wb"); fwrite(dta->data, 1, dta->data_len, f); fclose(f); // Placeholder. } // Example: int main() { DtaFile* dta = dta_new(); dta_load(dta, "example.dta"); dta_print_properties(dta); dta_free(dta); } // ===== end task-155 .DTA ===== // ===== task-156 .DTD [C++] ===== #include #include #include #include #include #include class DTDHandler { private: std::string filepath; std::string text; std::map> properties; std::vector find_matches(const std::string& regex_str, int flags = std::regex::icase) { std::vector matches; std::regex rx(regex_str, flags | std::regex::ECMAScript); auto begin = std::sregex_iterator(text.begin(), text.end(), rx); auto end = std::sregex_iterator(); for (std::sregex_iterator i = begin; i != end; ++i) { matches.push_back(i->str()); } return matches; } public: DTDHandler(const std::string& fp) : filepath(fp) { if (filepath.substr(filepath.find_last_of(".") + 1) != "dtd") { throw std::invalid_argument("File must be a .DTD file"); } } void read_and_decode() { std::ifstream file(filepath); if (!file) { throw std::runtime_error("Failed to open file"); } std::string line; while (std::getline(file, line)) { text += line + "\n"; } file.close(); extract_properties(); print_properties(); } void extract_properties() { properties["text_declarations"] = find_matches(R"(<\?xml\s+version="[^"]*"\s*(encoding="[^"]*")?\s*\?>)"); properties["element_declarations"] = find_matches(R"(]+>)"); properties["attribute_declarations"] = find_matches(R"(]+>)"); properties["entity_declarations"] = find_matches(R"(]+>)"); properties["notation_declarations"] = find_matches(R"(]+>)"); auto pis = find_matches(R"(<\?[^?]+\?>)"); std::vector filtered_pis; for (const auto& pi : pis) { if (!std::regex_match(pi, std::regex(R"(xml)", std::regex::icase))) { filtered_pis.push_back(pi); } } properties["processing_instructions"] = filtered_pis; properties["comments"] = find_matches(R"()"); properties["conditional_sections"] = find_matches(R"()"); properties["parameter_entity_references"] = find_matches(R"(%[^;]+;)", 0); } void print_properties() { for (const auto& [key, values] : properties) { std::string title = key; std::replace(title.begin(), title.end(), '_', ' '); title[0] = std::toupper(title[0]); std::cout << title << ":" << std::endl; for (const auto& value : values) { std::cout << value << std::endl; } std::cout << std::endl; } } void write(const std::string& new_filepath = "", const std::string& modified_text = "") { std::string path = new_filepath.empty() ? filepath : new_filepath; std::string content = modified_text.empty() ? text : modified_text; std::ofstream file(path); if (!file) { throw std::runtime_error("Failed to write file"); } file << content; file.close(); std::cout << "Written to " << path << std::endl; } }; // Example usage: // int main() { // try { // DTDHandler handler("example.dtd"); // handler.read_and_decode(); // handler.write("modified.dtd", "# Modified DTD"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-156 .DTD ===== // ===== task-157 .DVC [C++] ===== #include #include #include #include // Requires libyaml: apt install libyaml-dev or similar class DVCFileHandler { private: std::string filepath; yaml_document_t document; public: DVCFileHandler(const std::string& fp) : filepath(fp) {} ~DVCFileHandler() { yaml_document_delete(&document); } bool read() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "File " << filepath << " not found." << std::endl; return false; } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); yaml_parser_t parser; yaml_parser_initialize(&parser); yaml_parser_set_input_string(&parser, reinterpret_cast(content.c_str()), content.size()); if (!yaml_parser_load(&parser, &document)) { std::cerr << "Error parsing YAML." << std::endl; yaml_parser_delete(&parser); return false; } yaml_parser_delete(&parser); return true; } bool write(const std::string& yamlString) { std::ofstream file(filepath); if (!file.is_open()) { std::cerr << "Cannot open file for writing." << std::endl; return false; } file << yamlString; return true; } void printProperties() { if (document.nodes.start == document.nodes.top) { std::cout << "No data loaded. Call read() first." << std::endl; return; } yaml_node_t* root = yaml_document_get_root_node(&document); if (root->type == YAML_MAPPING_NODE) { dump(root, ""); } else { std::cout << "Invalid root node type." << std::endl; } } private: void dump(yaml_node_t* node, const std::string& prefix) { if (node->type == YAML_SCALAR_NODE) { std::cout << prefix << reinterpret_cast(node->data.scalar.value) << std::endl; } else if (node->type == YAML_MAPPING_NODE) { for (yaml_node_pair_t* pair = node->data.mapping.pairs.start; pair < node->data.mapping.pairs.top; ++pair) { yaml_node_t* key = yaml_document_get_node(&document, pair->key); yaml_node_t* value = yaml_document_get_node(&document, pair->value); std::cout << prefix << reinterpret_cast(key->data.scalar.value) << ": " << std::endl; dump(value, prefix + " "); } } else if (node->type == YAML_SEQUENCE_NODE) { int i = 0; for (yaml_node_item_t* item = node->data.sequence.items.start; item < node->data.sequence.items.top; ++item) { yaml_node_t* value = yaml_document_get_node(&document, *item); std::cout << prefix << "[" << i++ << "]:" << std::endl; dump(value, prefix + " "); } } } }; // Example usage: // int main() { // DVCFileHandler handler("example.dvc"); // if (handler.read()) { // handler.printProperties(); // } // // handler.write("outs:\n - path: new.xml\n md5: newhash\n"); // return 0; // } // ===== end task-157 .DVC ===== // ===== task-158 .DWF [C++] ===== #include #include #include #include #include class DwfHandler { private: std::string version = "00.30"; std::map properties; public: void read(const std::string& filename) { std::ifstream file(filename); std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); // Extract version std::regex versionRegex(R"(^\(DWF V(\d{2}\.\d{2})\))"); std::smatch versionMatch; if (std::regex_search(content, versionMatch, versionRegex)) { version = versionMatch[1]; } // Extract properties std::regex opcodeRegex(R"(\((Author|Background|Bounds|Clip|Color|ColorMap|Comment|Created|Creator|Description|DrawingInfo|Layer|LineCap|LineJoin|LinePattern|LineWeight|Modified|Projection|Scale|SourceCreated|SourceFilename|SourceModified|URL|View)(.*?)\))"); std::sregex_iterator iter(content.begin(), content.end(), opcodeRegex); std::sregex_iterator end; for (; iter != end; ++iter) { std::string token = (*iter)[1]; std::string operands = (*iter)[2]; // Trim operands operands.erase(0, operands.find_first_not_of(" \t\n\r\f\v")); operands.erase(operands.find_last_not_of(" \t\n\r\f\v") + 1); properties[token] = operands; } printProperties(); } void printProperties() const { std::cout << "Version: " << version << std::endl; for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& filename, const std::map& newProperties) { for (const auto& pair : newProperties) { properties[pair.first] = pair.second; } std::ofstream file(filename); file << "(DWF V" << version << ")\n"; for (const auto& pair : properties) { file << "(" << pair.first << " " << pair.second << ")\n"; } file << "(EndOfDWF)\n"; file.close(); } }; // Example usage: // int main() { // DwfHandler handler; // handler.read("sample.dwf"); // std::map props = {{"Author", "John Doe"}}; // handler.write("output.dwf", props); // return 0; // } // ===== end task-158 .DWF ===== // ===== task-159 .DWG [C] ===== #include #include #include #include #include typedef struct { char version[7]; uint8_t maintenance_version; uint32_t preview_address; uint16_t code_page; uint32_t security_flags; uint32_t summary_address; char title[256]; // Assuming max lengths char subject[256]; // Add similar for other strings time_t creation_time; time_t modified_time; } DWGProperties; typedef struct { const char* filepath; uint8_t* data; size_t size; DWGProperties properties; } DWGParser; void read_dwg(DWGParser* parser) { FILE* f = fopen(parser->filepath, "rb"); if (!f) return; fseek(f, 0, SEEK_END); parser->size = ftell(f); fseek(f, 0, SEEK_SET); parser->data = malloc(parser->size); fread(parser->data, 1, parser->size, f); fclose(f); decode_dwg(parser); } void decode_dwg(DWGParser* parser) { memcpy(parser->properties.version, parser->data, 6); parser->properties.version[6] = '\0'; parser->properties.maintenance_version = parser->data[6]; memcpy(&parser->properties.preview_address, &parser->data[0x0D], 4); // Little-endian assumed memcpy(&parser->properties.code_page, &parser->data[0x13], 2); memcpy(&parser->properties.security_flags, &parser->data[0x15], 4); memcpy(&parser->properties.summary_address, &parser->data[0x19], 4); uint32_t offset = parser->properties.summary_address; if (offset > 0) { uint32_t title_len; memcpy(&title_len, &parser->data[offset + 0x04], 4); memcpy(parser->properties.title, &parser->data[offset + 0x08], title_len); parser->properties.title[title_len] = '\0'; offset += 0x08 + title_len; uint32_t subject_len; memcpy(&subject_len, &parser->data[offset], 4); memcpy(parser->properties.subject, &parser->data[offset + 0x04], subject_len); parser->properties.subject[subject_len] = '\0'; // Similar for others uint64_t creation_ms; memcpy(&creation_ms, &parser->data[offset + 0x100], 8); parser->properties.creation_time = creation_ms / 1000; uint64_t modified_ms; memcpy(&modified_ms, &parser->data[offset + 0x108], 8); parser->properties.modified_time = modified_ms / 1000; } } void print_properties(const DWGParser* parser) { printf("Version: %s\n", parser->properties.version); printf("Maintenance Version: %u\n", parser->properties.maintenance_version); printf("Preview Address: %u\n", parser->properties.preview_address); printf("Code Page: %u\n", parser->properties.code_page); printf("Security Flags: %u\n", parser->properties.security_flags); printf("Summary Address: %u\n", parser->properties.summary_address); printf("Title: %s\n", parser->properties.title); printf("Subject: %s\n", parser->properties.subject); // Print others similarly printf("Creation Time: %s", ctime(&parser->properties.creation_time)); printf("Modified Time: %s", ctime(&parser->properties.modified_time)); } void write_dwg(const DWGParser* parser, const char* new_filepath) { FILE* f = fopen(new_filepath ? new_filepath : parser->filepath, "wb"); if (!f) return; fwrite(parser->data, 1, parser->size, f); fclose(f); // Writes original; modify data for changes } void free_dwg(DWGParser* parser) { free(parser->data); } // Usage example: // int main() { // DWGParser parser = {.filepath = "sample.dwg"}; // read_dwg(&parser); // print_properties(&parser); // write_dwg(&parser, "modified.dwg"); // free_dwg(&parser); // return 0; // } // ===== end task-159 .DWG ===== // ===== task-160 .DX [C++] ===== #include #include #include #include #include class DXFileHandler { private: std::string filepath; std::map properties; public: DXFileHandler(const std::string& fp) : filepath(fp) { read(); } void read() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file: " << filepath << std::endl; return; } std::string line, currentKey; std::stringstream valueStream; while (std::getline(file, line)) { std::string trimmed = line; trimmed.erase(0, trimmed.find_first_not_of(" \t")); trimmed.erase(trimmed.find_last_not_of(" \t") + 1); if (trimmed.rfind("##", 0) == 0) { if (!currentKey.empty()) { properties[currentKey] = valueStream.str(); valueStream.str(""); } size_t eqPos = trimmed.find('='); currentKey = (eqPos != std::string::npos) ? trimmed.substr(0, eqPos) : trimmed; currentKey.erase(currentKey.find_last_not_of(" \t") + 1); std::string value = (eqPos != std::string::npos) ? trimmed.substr(eqPos + 1) : ""; value.erase(0, value.find_first_not_of(" \t")); valueStream << value; } else if (!currentKey.empty()) { valueStream << "\n" << trimmed; } } if (!currentKey.empty()) { properties[currentKey] = valueStream.str(); } file.close(); } void printProperties() const { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& newFilepath = "") const { std::string outPath = newFilepath.empty() ? filepath : newFilepath; std::ofstream file(outPath); if (!file.is_open()) { std::cerr << "Error writing file: " << outPath << std::endl; return; } for (const auto& pair : properties) { file << pair.first << "=" << pair.second << "\n"; } file.close(); } }; // Example usage: // int main() { // DXFileHandler handler("sample.dx"); // handler.printProperties(); // handler.write("output.dx"); // return 0; // } // ===== end task-160 .DX ===== // ===== task-162 .E [C++] ===== #include #include #include #include #include class EFileParser { private: std::string filepath; std::vector lines; std::string precision = "Unknown"; std::vector sections; public: EFileParser(std::string fp) : filepath(fp) {} void openAndRead() { std::ifstream file(filepath); if (file.is_open()) { std::string line; while (std::getline(file, line)) { lines.push_back(line); } file.close(); decode(); } else { std::cout << "Unable to open file" << std::endl; } } void decode() { for (const auto& line : lines) { if (line.find("EXP") == 0) { std::istringstream iss(line); std::string token; std::vector parts; while (iss >> token) { parts.push_back(token); } if (parts.size() > 2) { precision = (parts[2] == "2") ? "Single" : "Double"; } } else if (std::regex_match(line, std::regex("^\\s*[A-Z]{3}\\s+[23]\\s*$"))) { sections.push_back(line); } } } void printProperties() { std::cout << "Properties of .E file:" << std::endl; std::cout << "File path: " << filepath << std::endl; std::cout << "Number of lines: " << lines.size() << std::endl; std::cout << "Precision: " << precision << std::endl; std::cout << "Sections found: "; for (size_t i = 0; i < sections.size(); ++i) { std::cout << sections[i]; if (i < sections.size() - 1) std::cout << ", "; } std::cout << std::endl; } void write(std::string newFilepath) { std::ofstream file(newFilepath); if (file.is_open()) { file << "EXP 0" << std::endl; file << "ARC 2" << std::endl; file << "EOS" << std::endl; file.close(); std::cout << "Basic .E file written to " << newFilepath << std::endl; } else { std::cout << "Unable to write file" << std::endl; } } }; // Example usage: // int main() { // EFileParser parser("example.e00"); // parser.openAndRead(); // parser.printProperties(); // parser.write("new.e00"); // return 0; // } // ===== end task-162 .E ===== // ===== task-163 .E00 [C++] ===== #include #include #include #include #include #include class E00Handler { private: std::string filepath; std::map properties; // Simplified to string for print std::vector lines; public: E00Handler(const std::string& fp) : filepath(fp) {} void openAndDecode() { std::ifstream file(filepath); std::string line; while (std::getline(file, line)) { lines.push_back(line); } file.close(); decodeProperties(); } void decodeProperties() { // Note: Simplified parsing; full implementation would use more structures properties["compressionStatus"] = "Uncompressed"; properties["precisionLevel"] = "Unknown"; properties["coverageName"] = ""; // Add more as strings for simplicity std::string currentSection; for (size_t i = 0; i < lines.size(); ++i) { std::string line = lines[i]; // Trim line (simple trim) line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); if (line.rfind("EXP", 0) == 0) { std::istringstream iss(line); std::string token; iss >> token >> token; properties["compressionStatus"] = (token == "0") ? "Uncompressed" : "Compressed"; iss >> token; properties["coverageName"] = token; } else if (line.rfind("ARC", 0) == 0 || line.rfind("GRD", 0) == 0 || line.rfind("TIN", 0) == 0) { currentSection = line.substr(0, 3); std::istringstream iss(line); std::string token; iss >> token >> token; properties["precisionLevel"] = (token == "2") ? "Single" : "Double"; } else if (line.rfind("BND", 0) == 0) { ++i; properties["boundingBox"] = lines[i]; // As string } else if (line.rfind("TOL", 0) == 0) { ++i; properties["toleranceValues"] = lines[i]; } else if (line.rfind("PRJ", 0) == 0) { std::string proj; ++i; while (lines[i].find("EOP") == std::string::npos) { proj += lines[i] + "\n"; ++i; } properties["projectionDefinition"] = proj; } // Add similar for other sections as needed; abbreviated for brevity // Feature counts and others can be added similarly } } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void writeFile(const std::string& outputPath) { std::ofstream out(outputPath); for (const auto& line : lines) { out << line << std::endl; } out.close(); } }; // Example usage: // int main() { // E00Handler handler("example.e00"); // handler.openAndDecode(); // handler.printProperties(); // handler.writeFile("output.e00"); // return 0; // } // ===== end task-163 .E00 ===== // ===== task-164 .E2D [C++] ===== #include #include #include #include #include "tinyxml2.h" // Assume TinyXML2 library is available using namespace tinyxml2; class E2DHandler { private: std::string filepath; XMLDocument doc; public: E2DHandler(const std::string& fp) : filepath(fp) {} bool read() { return doc.LoadFile(filepath.c_str()) == XML_SUCCESS; } void printProperties() { if (doc.Error()) { std::cout << "File not read. Call read() first." << std::endl; return; } auto properties = extractProperties(); for (const auto& section : properties) { std::cout << section.first << ":" << std::endl; const auto& props = section.second; if (props.empty()) continue; // Handle map or vector (simplified; assume map for now) for (const auto& prop : props) { std::cout << " " << prop.first << ": " << prop.second << std::endl; } } } std::map> extractProperties() { std::map> props; XMLElement* model = doc.FirstChildElement("state")->FirstChildElement("model"); if (model) { auto& modelProps = props["Model Parameters"]; const char* keys[] = {"timestep", "measurement_interval", "viewupdate_interval", "sunny", "sun_angle", "solar_power", "solar_ray_count", "solar_ray_speed", "photon_emission_interval", "minimum_temperature", "maximum_temperature", "z_heat_diffusivity", "z_heat_diffusivity_only_for_fluid", "background_conductivity", "background_density", "background_specific_heat", "background_temperature", "background_viscosity", "thermal_expansion_coefficient", "gravitational_acceleration", "thermophoretic_coefficient", "particle_feeder", "particle_feeder_interval"}; for (const char* key : keys) { XMLElement* el = model->FirstChildElement(key); if (el) modelProps[key] = el->GetText() ? el->GetText() : ""; } } XMLElement* boundary = doc.FirstChildElement("state")->FirstChildElement("boundary"); if (boundary) { auto& boundProps = props["Boundary Settings"]; XMLElement* thermal = boundary->FirstChildElement("thermal_boundary"); if (thermal) boundProps["thermal_boundary"] = thermal->GetText() ? thermal->GetText() : ""; XMLElement* fluid = boundary->FirstChildElement("fluid_boundary"); if (fluid) boundProps["fluid_boundary"] = fluid->GetText() ? fluid->GetText() : ""; boundProps["upper"] = boundary->Attribute("upper") ? boundary->Attribute("upper") : ""; boundProps["lower"] = boundary->Attribute("lower") ? boundary->Attribute("lower") : ""; boundProps["left"] = boundary->Attribute("left") ? boundary->Attribute("left") : ""; boundProps["right"] = boundary->Attribute("right") ? boundary->Attribute("right") : ""; } // Structure extraction (simplified; use vector for list) // Extend for other sections return props; } void write(const std::string& newFilepath = "") { if (doc.Error()) { XMLElement* root = doc.NewElement("state"); doc.InsertFirstChild(root); XMLElement* model = doc.NewElement("model"); root->InsertEndChild(model); XMLElement* timestep = doc.NewElement("timestep"); timestep->SetText("0.1"); model->InsertEndChild(timestep); } doc.SaveFile((newFilepath.empty() ? filepath : newFilepath).c_str()); } }; // Usage example: // int main() { // E2DHandler handler("example.e2d"); // if (handler.read()) { // handler.printProperties(); // handler.write("new.e2d"); // } // return 0; // } // ===== end task-164 .E2D ===== // ===== task-165 .E57 [C] ===== #include #include #include #include typedef struct { char fileSignature[8]; uint32_t majorVersion; uint32_t minorVersion; uint64_t filePhysicalLength; uint64_t xmlPhysicalOffset; uint64_t xmlLogicalLength; uint64_t pageSize; } E57Properties; void readE57(const char* filepath, E57Properties* props) { FILE* f = fopen(filepath, "rb"); if (!f) { perror("Failed to open file"); return; } fread(props, sizeof(E57Properties), 1, f); fclose(f); } void printProperties(const E57Properties* props) { printf("File Signature: %.8s\n", props->fileSignature); printf("Major Version: %u\n", props->majorVersion); printf("Minor Version: %u\n", props->minorVersion); printf("File Physical Length: %llu\n", (unsigned long long)props->filePhysicalLength); printf("XML Physical Offset: %llu\n", (unsigned long long)props->xmlPhysicalOffset); printf("XML Logical Length: %llu\n", (unsigned long long)props->xmlLogicalLength); printf("Page Size: %llu\n", (unsigned long long)props->pageSize); } void writeE57(const char* outputPath, const char* xmlContent) { size_t xmlLogicalLen = strlen(xmlContent); size_t numPages = (xmlLogicalLen + 1019) / 1020; uint64_t xmlPhysicalLen = numPages * 1024ULL; uint64_t filePhysicalLen = 48ULL + xmlPhysicalLen; E57Properties header = {0}; memcpy(header.fileSignature, "ASTME57\0", 8); header.majorVersion = 1; header.minorVersion = 0; header.filePhysicalLength = filePhysicalLen; header.xmlPhysicalOffset = 48ULL; header.xmlLogicalLength = xmlLogicalLen; header.pageSize = 1024ULL; FILE* f = fopen(outputPath, "wb"); if (!f) { perror("Failed to create file"); return; } fwrite(&header, sizeof(E57Properties), 1, f); size_t offset = 0; while (offset < xmlLogicalLen) { size_t len = (xmlLogicalLen - offset < 1020) ? (xmlLogicalLen - offset) : 1020; fwrite(xmlContent + offset, 1, len, f); for (size_t i = len; i < 1020; ++i) fputc(0, f); uint32_t crc = 0; // Placeholder CRC fwrite(&crc, sizeof(uint32_t), 1, f); offset += 1020; } fclose(f); } // ===== end task-165 .E57 ===== // ===== task-166 .EBD [C] ===== #include #include #include #define MAX_LINE 256 #define MAX_SECTIONS 20 #define MAX_PINS 1000 typedef struct { char *key; char *value; } KeyValue; typedef struct { KeyValue sections[MAX_SECTIONS]; int section_count; char *pin_list[MAX_PINS]; int pin_count; // For path descriptions, use a simple string map simulation char *path_keys[MAX_PINS]; char *path_values[MAX_PINS]; int path_count; char *ref_map[MAX_PINS]; int ref_count; } EBDProperties; void init_EBDProperties(EBDProperties *props) { props->section_count = 0; props->pin_count = 0; props->path_count = 0; props->ref_count = 0; } void open_and_decode(EBDProperties *props, const char *filepath) { FILE *fp = fopen(filepath, "r"); if (!fp) return; char line[MAX_LINE]; char *current_section = NULL; char *current_path_pin = NULL; while (fgets(line, MAX_LINE, fp)) { line[strcspn(line, "\n")] = 0; // Trim newline char *trimmed = line; while (*trimmed == ' ') trimmed++; if (trimmed[0] == '[' && trimmed[strlen(trimmed)-1] == ']') { free(current_section); current_section = strdup(trimmed + 1); current_section[strlen(current_section)-1] = 0; props->sections[props->section_count].key = strdup(current_section); props->sections[props->section_count].value = strdup(""); props->section_count++; } else if (current_section) { if (strcmp(current_section, "Path Description") == 0) { if (strncmp(trimmed, "Pin", 3) == 0) { char *pin = trimmed + 4; props->path_keys[props->path_count] = strdup(pin); props->path_values[props->path_count] = strdup(""); current_path_pin = props->path_keys[props->path_count]; props->path_count++; } else if (strlen(trimmed) > 0) { char *new_val = malloc(strlen(props->path_values[props->path_count-1]) + strlen(trimmed) + 2); sprintf(new_val, "%s%s\n", props->path_values[props->path_count-1], trimmed); free(props->path_values[props->path_count-1]); props->path_values[props->path_count-1] = new_val; } } else if (strcmp(current_section, "Pin List") == 0) { if (strlen(trimmed) > 0 && trimmed[0] != '|') { props->pin_list[props->pin_count++] = strdup(trimmed); } } else if (strcmp(current_section, "Reference Designator Map") == 0) { if (strlen(trimmed) > 0 && trimmed[0] != '|') { props->ref_map[props->ref_count++] = strdup(trimmed); } } else { char *new_val = malloc(strlen(props->sections[props->section_count-1].value) + strlen(trimmed) + 2); sprintf(new_val, "%s%s\n", props->sections[props->section_count-1].value, trimmed); free(props->sections[props->section_count-1].value); props->sections[props->section_count-1].value = new_val; } } } fclose(fp); free(current_section); } void print_properties(EBDProperties *props) { for (int i = 0; i < props->section_count; i++) { printf("[%s] %s\n", props->sections[i].key, props->sections[i].value); } printf("[Pin List]\n"); for (int i = 0; i < props->pin_count; i++) { printf("%s\n", props->pin_list[i]); } printf("[Path Descriptions]\n"); for (int i = 0; i < props->path_count; i++) { printf("Pin %s\n%s", props->path_keys[i], props->path_values[i]); } printf("[Reference Designator Map]\n"); for (int i = 0; i < props->ref_count; i++) { printf("%s\n", props->ref_map[i]); } } void write(EBDProperties *props, const char *filepath) { FILE *fp = fopen(filepath, "w"); if (!fp) return; for (int i = 0; i < props->section_count; i++) { fprintf(fp, "[%s] %s\n", props->sections[i].key, props->sections[i].value); } fprintf(fp, "[Pin List]\n"); for (int i = 0; i < props->pin_count; i++) { fprintf(fp, "%s\n", props->pin_list[i]); } fprintf(fp, "[Path Description]\n"); for (int i = 0; i < props->path_count; i++) { fprintf(fp, "Pin %s\n%s", props->path_keys[i], props->path_values[i]); } fprintf(fp, "[Reference Designator Map]\n"); for (int i = 0; i < props->ref_count; i++) { fprintf(fp, "%s\n", props->ref_map[i]); } fprintf(fp, "[End]\n"); fclose(fp); } // Example usage: // int main() { // EBDProperties props; // init_EBDProperties(&props); // open_and_decode(&props, "example.ebd"); // print_properties(&props); // write(&props, "output.ebd"); // // Free memory... // return 0; // } // ===== end task-166 .EBD ===== // ===== task-167 .EC [C] ===== #include #include #include #include #include typedef struct { uint8_t blockType; uint16_t magic; uint16_t version; } Header; typedef struct { char* id; uint64_t start; uint64_t dump; } SessionInfo; typedef struct { uint64_t classId; char* name; uint8_t* probesPacked; uint32_t probesLength; } ExecutionData; typedef struct { Header header; SessionInfo* sessions; size_t sessionCount; ExecutionData* executions; size_t executionCount; } ECFile; uint32_t readVarInt(FILE* f) { uint32_t value = 0; int shift = 0; while (1) { uint8_t byte; fread(&byte, 1, 1, f); value |= (byte & 0x7F) << shift; if ((byte & 0x80) == 0) break; shift += 7; } return value; } char* readUTF(FILE* f) { uint16_t length; fread(&length, 2, 1, f); length = be16toh(length); char* str = malloc(length + 1); fread(str, 1, length, f); str[length] = '\0'; return str; } void readECFile(ECFile* ec, const char* filepath) { FILE* f = fopen(filepath, "rb"); if (!f) return; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); fread(&ec->header.blockType, 1, 1, f); fread(&ec->header.magic, 2, 1, f); ec->header.magic = be16toh(ec->header.magic); fread(&ec->header.version, 2, 1, f); ec->header.version = be16toh(ec->header.version); ec->sessionCount = 0; ec->executionCount = 0; ec->sessions = NULL; ec->executions = NULL; while (ftell(f) < size) { uint8_t block; fread(&block, 1, 1, f); if (block == 0x10) { ec->sessions = realloc(ec->sessions, sizeof(SessionInfo) * (ec->sessionCount + 1)); SessionInfo* session = &ec->sessions[ec->sessionCount++]; session->id = readUTF(f); fread(&session->start, 8, 1, f); session->start = be64toh(session->start); fread(&session->dump, 8, 1, f); session->dump = be64toh(session->dump); } else if (block == 0x11) { ec->executions = realloc(ec->executions, sizeof(ExecutionData) * (ec->executionCount + 1)); ExecutionData* exec = &ec->executions[ec->executionCount++]; fread(&exec->classId, 8, 1, f); exec->classId = be64toh(exec->classId); exec->name = readUTF(f); exec->probesLength = readVarInt(f); size_t byteLength = (exec->probesLength + 7) / 8; exec->probesPacked = malloc(byteLength); fread(exec->probesPacked, 1, byteLength, f); } else { break; } } fclose(f); } void printProperties(const ECFile* ec) { printf("Header:\n"); printf(" Block Type: 0x%02x\n", ec->header.blockType); printf(" Magic: 0x%04x\n", ec->header.magic); printf(" Version: 0x%04x\n", ec->header.version); for (size_t i = 0; i < ec->sessionCount; i++) { const SessionInfo* session = &ec->sessions[i]; printf("Session Info %zu:\n", i); printf(" ID: %s\n", session->id); printf(" Start: %lu\n", session->start); printf(" Dump: %lu\n", session->dump); } for (size_t i = 0; i < ec->executionCount; i++) { const ExecutionData* exec = &ec->executions[i]; printf("Execution Data %zu:\n", i); printf(" Class ID: %lu\n", exec->classId); printf(" Class Name: %s\n", exec->name); printf(" Probes (length %u): ", exec->probesLength); for (uint32_t j = 0; j < exec->probesLength; j++) { uint8_t byte = exec->probesPacked[j / 8]; printf("%d ", (byte & (1 << (j % 8))) != 0); } printf("\n"); } } void writeECFile(const ECFile* ec, const char* filepath) { FILE* f = fopen(filepath, "wb"); if (!f) return; fwrite(&ec->header.blockType, 1, 1, f); uint16_t beMagic = htobe16(ec->header.magic); fwrite(&beMagic, 2, 1, f); uint16_t beVersion = htobe16(ec->header.version); fwrite(&beVersion, 2, 1, f); for (size_t i = 0; i < ec->sessionCount; i++) { const SessionInfo* session = &ec->sessions[i]; uint8_t block = 0x10; fwrite(&block, 1, 1, f); uint16_t length = strlen(session->id); uint16_t beLength = htobe16(length); fwrite(&beLength, 2, 1, f); fwrite(session->id, 1, length, f); uint64_t beStart = htobe64(session->start); fwrite(&beStart, 8, 1, f); uint64_t beDump = htobe64(session->dump); fwrite(&beDump, 8, 1, f); } for (size_t i = 0; i < ec->executionCount; i++) { const ExecutionData* exec = &ec->executions[i]; uint8_t block = 0x11; fwrite(&block, 1, 1, f); uint64_t beClassId = htobe64(exec->classId); fwrite(&beClassId, 8, 1, f); uint16_t length = strlen(exec->name); uint16_t beLength = htobe16(length); fwrite(&beLength, 2, 1, f); fwrite(exec->name, 1, length, f); // Write varint uint32_t probLength = exec->probesLength; while (1) { uint8_t byte = probLength & 0x7F; probLength >>= 7; if (probLength) byte |= 0x80; fwrite(&byte, 1, 1, f); if (!probLength) break; } // Write packed bytes size_t byteLength = (exec->probesLength + 7) / 8; fwrite(exec->probesPacked, 1, byteLength, f); } fclose(f); } int main(int argc, char** argv) { ECFile ec; readECFile(&ec, "coverage.ec"); printProperties(&ec); writeECFile(&ec, "new_coverage.ec"); // Free memory for (size_t i = 0; i < ec.sessionCount; i++) { free(ec.sessions[i].id); } free(ec.sessions); for (size_t i = 0; i < ec.executionCount; i++) { free(ec.executions[i].name); free(ec.executions[i].probesPacked); } free(ec.executions); return 0; } // ===== end task-167 .EC ===== // ===== task-168 .ECC [C] ===== #include #include #include #include typedef struct { char cookie[12]; char method[4]; uint32_t methodFlags; uint8_t mediumFP[16]; uint8_t mediumSum[16]; uint8_t eccSum[16]; uint64_t sectors; int32_t dataBytes; int32_t eccBytes; int32_t creatorVersion; int32_t neededVersion; int32_t fpSector; uint32_t selfCRC; uint8_t crcSum[16]; int32_t inLast; uint64_t sectorsPerLayer; uint64_t sectorsAddedByECC; } ECCProperties; typedef struct { char* filename; ECCProperties props; uint8_t* data; size_t size; } ECCFile; ECCFile* eccfile_create(const char* filename) { ECCFile* ecc = malloc(sizeof(ECCFile)); ecc->filename = strdup(filename); ecc->data = NULL; ecc->size = 0; return ecc; } void eccfile_read(ECCFile* ecc) { FILE* f = fopen(ecc->filename, "rb"); if (!f) return; fseek(f, 0, SEEK_END); ecc->size = ftell(f); fseek(f, 0, SEEK_SET); ecc->data = malloc(ecc->size); fread(ecc->data, 1, ecc->size, f); fclose(f); eccfile_decode(ecc); } void eccfile_decode(ECCFile* ecc) { if (ecc->size < 4096) return; memcpy(ecc->props.cookie, ecc->data + 0, 12); memcpy(ecc->props.method, ecc->data + 12, 4); memcpy(&ecc->props.methodFlags, ecc->data + 16, 4); memcpy(ecc->props.mediumFP, ecc->data + 20, 16); memcpy(ecc->props.mediumSum, ecc->data + 36, 16); memcpy(ecc->props.eccSum, ecc->data + 52, 16); memcpy(&ecc->props.sectors, ecc->data + 68, 8); memcpy(&ecc->props.dataBytes, ecc->data + 76, 4); memcpy(&ecc->props.eccBytes, ecc->data + 80, 4); memcpy(&ecc->props.creatorVersion, ecc->data + 84, 4); memcpy(&ecc->props.neededVersion, ecc->data + 88, 4); memcpy(&ecc->props.fpSector, ecc->data + 92, 4); memcpy(&ecc->props.selfCRC, ecc->data + 96, 4); memcpy(ecc->props.crcSum, ecc->data + 100, 16); memcpy(&ecc->props.inLast, ecc->data + 116, 4); memcpy(&ecc->props.sectorsPerLayer, ecc->data + 120, 8); memcpy(&ecc->props.sectorsAddedByECC, ecc->data + 128, 8); // Note: Endian assumption little-endian; full decoding omitted } void eccfile_print_properties(ECCFile* ecc) { printf("Cookie: %.12s\n", ecc->props.cookie); printf("Method: %.4s\n", ecc->props.method); printf("Method Flags: %u\n", ecc->props.methodFlags); printf("Medium FP: "); for (int i = 0; i < 16; i++) printf("%02x", ecc->props.mediumFP[i]); printf("\n"); // Similar for other hex fields... printf("Sectors: %lu\n", ecc->props.sectors); printf("Data Bytes: %d\n", ecc->props.dataBytes); printf("ECC Bytes: %d\n", ecc->props.eccBytes); printf("Creator Version: %d\n", ecc->props.creatorVersion); printf("Needed Version: %d\n", ecc->props.neededVersion); printf("FP Sector: %d\n", ecc->props.fpSector); printf("Self CRC: %u\n", ecc->props.selfCRC); // CRC Sum hex... printf("In Last: %d\n", ecc->props.inLast); printf("Sectors Per Layer: %lu\n", ecc->props.sectorsPerLayer); printf("Sectors Added By ECC: %lu\n", ecc->props.sectorsAddedByECC); } void eccfile_write(ECCFile* ecc, const char* newFilename) { if (!ecc->data) { ecc->size = 4096; ecc->data = calloc(1, ecc->size); memcpy(ecc->data, "*dvdisaster*", 12); memcpy(ecc->data + 12, "RS01", 4); // Defaults omitted } FILE* f = fopen(newFilename ? newFilename : ecc->filename, "wb"); if (f) { fwrite(ecc->data, 1, ecc->size, f); fclose(f); } } void eccfile_destroy(ECCFile* ecc) { free(ecc->data); free(ecc->filename); free(ecc); } // Example usage: // int main() { // ECCFile* ecc = eccfile_create("example.ecc"); // eccfile_read(ecc); // eccfile_print_properties(ecc); // eccfile_write(ecc, "new.ecc"); // eccfile_destroy(ecc); // return 0; // } // ===== end task-168 .ECC ===== // ===== task-169 .EDE [C] ===== #include #include #include #include #define BLOCK_SIZE 512 #define TOTAL_BLOCKS 1600 typedef struct { char *filename; uint8_t *disk; } EDEParser; EDEParser* ede_create(const char *filename) { EDEParser *parser = malloc(sizeof(EDEParser)); parser->filename = strdup(filename); parser->disk = NULL; return parser; } void ede_read(EDEParser *parser) { FILE *f = fopen(parser->filename, "rb"); uint8_t header[512]; fread(header, 1, 512, f); uint8_t bitmap[200]; memcpy(bitmap, header, 200); fseek(f, 0, SEEK_END); long data_size = ftell(f) - 512; fseek(f, 512, SEEK_SET); uint8_t *data = malloc(data_size); fread(data, 1, data_size, f); fclose(f); parser->disk = malloc(TOTAL_BLOCKS * BLOCK_SIZE); uint8_t pattern[BLOCK_SIZE]; for (int i = 0; i < BLOCK_SIZE; i += 2) { pattern[i] = 0x6D; pattern[i + 1] = 0xB6; } int data_offset = 0; for (int b = 0; b < TOTAL_BLOCKS; b++) { int byte_offset = b / 8; int bit_offset = b % 8; int is_present = (bitmap[byte_offset] & (1 << bit_offset)) != 0; if (is_present) { memcpy(parser->disk + b * BLOCK_SIZE, data + data_offset, BLOCK_SIZE); data_offset += BLOCK_SIZE; } else { memcpy(parser->disk + b * BLOCK_SIZE, pattern, BLOCK_SIZE); } } free(data); } void ede_print_properties(EDEParser *parser) { // Parse and print similar to Python uint32_t free_blocks = *(uint32_t*)(parser->disk + 2 * BLOCK_SIZE); printf("Free Blocks: %u\n", free_blocks); // Add more } void ede_write(EDEParser *parser, const char *new_filename) { uint8_t bitmap[200] = {0}; uint8_t *data = malloc((TOTAL_BLOCKS * BLOCK_SIZE)); // Max size int data_len = 0; uint8_t pattern[BLOCK_SIZE]; for (int i = 0; i < BLOCK_SIZE; i += 2) { pattern[i] = 0x6D; pattern[i + 1] = 0xB6; } for (int b = 0; b < TOTAL_BLOCKS; b++) { uint8_t *block_data = parser->disk + b * BLOCK_SIZE; int is_pattern = memcmp(block_data, pattern, BLOCK_SIZE) == 0; if (!is_pattern) { memcpy(data + data_len, block_data, BLOCK_SIZE); data_len += BLOCK_SIZE; int byte_offset = b / 8; int bit_offset = b % 8; bitmap[byte_offset] |= (1 << bit_offset); } } uint8_t header[512] = {0}; memcpy(header, bitmap, 200); FILE *f = fopen(new_filename, "wb"); fwrite(header, 1, 512, f); fwrite(data, 1, data_len, f); fclose(f); free(data); } void ede_destroy(EDEParser *parser) { free(parser->disk); free(parser->filename); free(parser); } int main() { EDEParser *parser = ede_create("example.ede"); ede_read(parser); ede_print_properties(parser); ede_write(parser, "modified.ede"); ede_destroy(parser); return 0; } // ===== end task-169 .EDE ===== // ===== task-170 .EDF [C++] ===== #include #include #include #include #include #include class EDFHandler { public: std::string version; std::string patientId; std::string recordingId; std::string startDate; std::string startTime; int headerBytes; std::string reserved; int numDataRecords; double duration; int numSignals; struct Signal { std::string label; std::string transducer; std::string physDim; double physMin; double physMax; int digMin; int digMax; std::string prefiltering; int nrSamples; std::string reservedSignal; }; std::vector signals; EDFHandler(const std::string& filename) { read(filename); } void read(const std::string& filename) { std::ifstream file(filename, std::ios::binary); if (!file) { std::cerr << "Error opening file." << std::endl; return; } char header[256]; file.read(header, 256); char buf[81]; // Temp buffer std::memcpy(buf, header + 0, 8); buf[8] = '\0'; version = std::string(buf); std::memcpy(buf, header + 8, 80); buf[80] = '\0'; patientId = std::string(buf); std::memcpy(buf, header + 88, 80); buf[80] = '\0'; recordingId = std::string(buf); std::memcpy(buf, header + 168, 8); buf[8] = '\0'; startDate = std::string(buf); std::memcpy(buf, header + 176, 8); buf[8] = '\0'; startTime = std::string(buf); std::memcpy(buf, header + 184, 8); buf[8] = '\0'; headerBytes = std::stoi(buf); std::memcpy(buf, header + 192, 44); buf[44] = '\0'; reserved = std::string(buf); std::memcpy(buf, header + 236, 8); buf[8] = '\0'; numDataRecords = std::stoi(buf); std::memcpy(buf, header + 244, 8); buf[8] = '\0'; duration = std::stod(buf); std::memcpy(buf, header + 252, 4); buf[4] = '\0'; numSignals = std::stoi(buf); // Trim spaces version.erase(version.find_last_not_of(' ') + 1); patientId.erase(patientId.find_last_not_of(' ') + 1); // Similarly trim others... char* signalHeader = new char[256 * numSignals]; file.read(signalHeader, 256 * numSignals); int offset = 0; for (int i = 0; i < numSignals; ++i) { Signal sig; std::memcpy(buf, signalHeader + offset, 16); buf[16] = '\0'; sig.label = std::string(buf); offset += 16; std::memcpy(buf, signalHeader + offset, 80); buf[80] = '\0'; sig.transducer = std::string(buf); offset += 80; std::memcpy(buf, signalHeader + offset, 8); buf[8] = '\0'; sig.physDim = std::string(buf); offset += 8; std::memcpy(buf, signalHeader + offset, 8); buf[8] = '\0'; sig.physMin = std::stod(buf); offset += 8; std::memcpy(buf, signalHeader + offset, 8); buf[8] = '\0'; sig.physMax = std::stod(buf); offset += 8; std::memcpy(buf, signalHeader + offset, 8); buf[8] = '\0'; sig.digMin = std::stoi(buf); offset += 8; std::memcpy(buf, signalHeader + offset, 8); buf[8] = '\0'; sig.digMax = std::stoi(buf); offset += 8; std::memcpy(buf, signalHeader + offset, 80); buf[80] = '\0'; sig.prefiltering = std::string(buf); offset += 80; std::memcpy(buf, signalHeader + offset, 8); buf[8] = '\0'; sig.nrSamples = std::stoi(buf); offset += 8; std::memcpy(buf, signalHeader + offset, 32); buf[32] = '\0'; sig.reservedSignal = std::string(buf); offset += 32; // Trim sig.label.erase(sig.label.find_last_not_of(' ') + 1); // Similarly for others... signals.push_back(sig); } delete[] signalHeader; } void printProperties() { std::cout << "Version: " << version << std::endl; std::cout << "Patient ID: " << patientId << std::endl; std::cout << "Recording ID: " << recordingId << std::endl; std::cout << "Start Date: " << startDate << std::endl; std::cout << "Start Time: " << startTime << std::endl; std::cout << "Header Bytes: " << headerBytes << std::endl; std::cout << "Reserved: " << reserved << std::endl; std::cout << "Num Data Records: " << numDataRecords << std::endl; std::cout << "Duration: " << duration << std::endl; std::cout << "Num Signals: " << numSignals << std::endl; for (size_t i = 0; i < signals.size(); ++i) { std::cout << "\nSignal " << (i + 1) << ":" << std::endl; std::cout << " Label: " << signals[i].label << std::endl; std::cout << " Transducer: " << signals[i].transducer << std::endl; std::cout << " Physical Dimension: " << signals[i].physDim << std::endl; std::cout << " Physical Min: " << signals[i].physMin << std::endl; std::cout << " Physical Max: " << signals[i].physMax << std::endl; std::cout << " Digital Min: " << signals[i].digMin << std::endl; std::cout << " Digital Max: " << signals[i].digMax << std::endl; std::cout << " Prefiltering: " << signals[i].prefiltering << std::endl; std::cout << " Num Samples: " << signals[i].nrSamples << std::endl; std::cout << " Reserved: " << signals[i].reservedSignal << std::endl; } } void write(const std::string& filename, const char* dataRecords = "", size_t dataSize = 0) { std::ofstream file(filename, std::ios::binary); if (!file) { std::cerr << "Error opening file for writing." << std::endl; return; } char header[256]; std::memset(header, ' ', 256); std::sprintf(header + 0, "%-8s", version.c_str()); std::sprintf(header + 8, "%-80s", patientId.c_str()); std::sprintf(header + 88, "%-80s", recordingId.c_str()); std::sprintf(header + 168, "%-8s", startDate.c_str()); std::sprintf(header + 176, "%-8s", startTime.c_str()); std::sprintf(header + 184, "%-8d", headerBytes); std::sprintf(header + 192, "%-44s", reserved.c_str()); std::sprintf(header + 236, "%-8d", numDataRecords); std::sprintf(header + 244, "%-8.1f", duration); std::sprintf(header + 252, "%-4d", numSignals); file.write(header, 256); for (const auto& sig : signals) { char sigHeader[256]; std::memset(sigHeader, ' ', 256); std::sprintf(sigHeader + 0, "%-16s", sig.label.c_str()); std::sprintf(sigHeader + 16, "%-80s", sig.transducer.c_str()); std::sprintf(sigHeader + 96, "%-8s", sig.physDim.c_str()); std::sprintf(sigHeader + 104, "%-8.1f", sig.physMin); std::sprintf(sigHeader + 112, "%-8.1f", sig.physMax); std::sprintf(sigHeader + 120, "%-8d", sig.digMin); std::sprintf(sigHeader + 128, "%-8d", sig.digMax); std::sprintf(sigHeader + 136, "%-80s", sig.prefiltering.c_str()); std::sprintf(sigHeader + 216, "%-8d", sig.nrSamples); std::sprintf(sigHeader + 224, "%-32s", sig.reservedSignal.c_str()); file.write(sigHeader, 256); } file.write(dataRecords, dataSize); } }; // Example usage: // int main() { // EDFHandler edf("example.edf"); // edf.printProperties(); // edf.write("output.edf"); // return 0; // } // ===== end task-170 .EDF ===== // ===== task-171 .EFI [C] ===== #include #include #include #include typedef struct { char *filename; uint8_t *data; size_t size; // Add property structs, e.g. struct { uint16_t e_magic; // ... int32_t e_lfanew; } dos_header; // Add other structs... } EfiParser; EfiParser* efi_parser_new(const char *filename) { EfiParser *parser = malloc(sizeof(EfiParser)); FILE *f = fopen(filename, "rb"); fseek(f, 0, SEEK_END); parser->size = ftell(f); fseek(f, 0, SEEK_SET); parser->data = malloc(parser->size); fread(parser->data, 1, parser->size, f); fclose(f); // Parse DOS memcpy(&parser->dos_header.e_magic, parser->data + 0, 2); // Add offsets... memcpy(&parser->dos_header.e_lfanew, parser->data + 60, 4); // Parse others similarly return parser; } void efi_parser_print_properties(EfiParser *parser) { printf("DOS Header:\n"); printf(" e_magic: 0x%04x\n", parser->dos_header.e_magic); // Print all... } void efi_parser_write(EfiParser *parser, const char *output_filename) { FILE *f = fopen(output_filename, "wb"); fwrite(parser->data, 1, parser->size, f); fclose(f); } void efi_parser_free(EfiParser *parser) { free(parser->data); free(parser); } // Usage: EfiParser *p = efi_parser_new("example.efi"); efi_parser_print_properties(p); efi_parser_write(p, "copy.efi"); efi_parser_free(p); // ===== end task-171 .EFI ===== // ===== task-173 .EL [C] ===== #include #include #include #include #define HEADER_SIZE 52 typedef struct { uint8_t e_ident[16]; uint16_t e_type; uint16_t e_machine; uint32_t e_version; uint32_t e_entry; uint32_t e_phoff; uint32_t e_shoff; uint32_t e_flags; uint16_t e_ehsize; uint16_t e_phentsize; uint16_t e_phnum; uint16_t e_shentsize; uint16_t e_shnum; uint16_t e_shstrndx; } ElfHeader; typedef struct { char* filepath; ElfHeader header; } ElfFile; ElfFile* elf_create(const char* filepath) { ElfFile* elf = malloc(sizeof(ElfFile)); elf->filepath = strdup(filepath); return elf; } void elf_read(ElfFile* elf) { FILE* f = fopen(elf->filepath, "rb"); if (!f) { perror("Open failed"); exit(1); } uint8_t buf[HEADER_SIZE]; if (fread(buf, 1, HEADER_SIZE, f) != HEADER_SIZE) { fprintf(stderr, "Read failed\n"); fclose(f); exit(1); } fclose(f); if (memcmp(buf, "\x7fELF", 4) != 0) { fprintf(stderr, "Not ELF\n"); exit(1); } memcpy(elf->header.e_ident, buf, 16); memcpy(&elf->header.e_type, buf + 16, sizeof(elf->header) - 16); } void elf_print_properties(ElfFile* elf) { printf("Magic: \\x7F ELF\n"); printf("Class: %u\n", elf->header.e_ident[4]); printf("Data: %u\n", elf->header.e_ident[5]); printf("Version: %u\n", elf->header.e_ident[6]); printf("OS/ABI: %u\n", elf->header.e_ident[7]); printf("ABI Version: %u\n", elf->header.e_ident[8]); printf("Type: %u\n", elf->header.e_type); printf("Machine: %u\n", elf->header.e_machine); printf("Version: %u\n", elf->header.e_version); printf("Entry point: 0x%x\n", elf->header.e_entry); printf("Program header offset: %u\n", elf->header.e_phoff); printf("Section header offset: %u\n", elf->header.e_shoff); printf("Flags: 0x%x\n", elf->header.e_flags); printf("Header size: %u\n", elf->header.e_ehsize); printf("Program header entry size: %u\n", elf->header.e_phentsize); printf("Program header count: %u\n", elf->header.e_phnum); printf("Section header entry size: %u\n", elf->header.e_shentsize); printf("Section header count: %u\n", elf->header.e_shnum); printf("String table index: %u\n", elf->header.e_shstrndx); } void elf_write(ElfFile* elf, const char* new_filepath) { char* path = new_filepath ? strdup(new_filepath) : strcat(strdup(elf->filepath), ".copy"); FILE* fin = fopen(elf->filepath, "rb"); FILE* fout = fopen(path, "wb"); if (!fin || !fout) { perror("File operation failed"); exit(1); } uint8_t buf[1024]; size_t len; while ((len = fread(buf, 1, sizeof(buf), fin)) > 0) { fwrite(buf, 1, len, fout); } fclose(fin); fclose(fout); printf("Written to %s\n", path); free(path); } void elf_destroy(ElfFile* elf) { free(elf->filepath); free(elf); } // Example usage: // int main() { // ElfFile* elf = elf_create("example.el"); // elf_read(elf); // elf_print_properties(elf); // elf_write(elf, NULL); // elf_destroy(elf); // return 0; // } // ===== end task-173 .EL ===== // ===== task-174 .ELC [C] ===== #include #include #include #define MAX_LINE 256 #define MAX_POSITIONS 1024 typedef struct { char referenceLabel[64]; char unitPosition[64]; int numberPositions; double positions[MAX_POSITIONS][3]; char labels[MAX_POSITIONS][64]; } ELCFile; void readELC(ELCFile *elc, const char *filename) { FILE *fp = fopen(filename, "r"); if (!fp) { perror("Failed to open file"); return; } char line[MAX_LINE]; char section[64] = ""; elc->numberPositions = 0; int posIndex = 0; int labelIndex = 0; while (fgets(line, MAX_LINE, fp)) { char *trimmed = strtok(line, "\n"); if (trimmed[0] == '#') continue; if (strstr(trimmed, "ReferenceLabel")) { sscanf(trimmed, "ReferenceLabel %s", elc->referenceLabel); } else if (strstr(trimmed, "UnitPosition")) { sscanf(trimmed, "UnitPosition %s", elc->unitPosition); } else if (strstr(trimmed, "NumberPositions")) { sscanf(trimmed, "NumberPositions= %d", &elc->numberPositions); } else if (strcmp(trimmed, "Positions") == 0) { strcpy(section, "positions"); } else if (strcmp(trimmed, "Labels") == 0) { strcpy(section, "labels"); } else if (strcmp(section, "positions") == 0 && trimmed[0] != '\0') { sscanf(trimmed, "%lf %lf %lf", &elc->positions[posIndex][0], &elc->positions[posIndex][1], &elc->positions[posIndex][2]); posIndex++; } else if (strcmp(section, "labels") == 0 && trimmed[0] != '\0') { strcpy(elc->labels[labelIndex], trimmed); labelIndex++; } } fclose(fp); } void printProperties(ELCFile *elc) { printf("ReferenceLabel: %s\n", elc->referenceLabel); printf("UnitPosition: %s\n", elc->unitPosition); printf("NumberPositions: %d\n", elc->numberPositions); printf("Positions:\n"); for (int i = 0; i < elc->numberPositions; i++) { printf("%f %f %f\n", elc->positions[i][0], elc->positions[i][1], elc->positions[i][2]); } printf("Labels:\n"); for (int i = 0; i < elc->numberPositions; i++) { printf("%s\n", elc->labels[i]); } } void writeELC(ELCFile *elc, const char *filename) { FILE *fp = fopen(filename, "w"); if (!fp) { perror("Failed to open file"); return; } fprintf(fp, "# ASA electrode file\n"); fprintf(fp, "ReferenceLabel %s\n", elc->referenceLabel); fprintf(fp, "UnitPosition %s\n", elc->unitPosition); fprintf(fp, "NumberPositions= %d\n", elc->numberPositions); fprintf(fp, "Positions\n"); for (int i = 0; i < elc->numberPositions; i++) { fprintf(fp, "%f %f %f\n", elc->positions[i][0], elc->positions[i][1], elc->positions[i][2]); } fprintf(fp, "Labels\n"); for (int i = 0; i < elc->numberPositions; i++) { fprintf(fp, "%s\n", elc->labels[i]); } fclose(fp); } int main(int argc, char *argv[]) { if (argc > 1) { ELCFile elc; readELC(&elc, argv[1]); printProperties(&elc); } return 0; } // ===== end task-174 .ELC ===== // ===== task-175 .ELF [C] ===== #include #include #include #include #include #include typedef struct { uint8_t ei_class; uint8_t ei_data; uint8_t ei_version; uint8_t ei_osabi; uint8_t ei_abiversion; uint16_t e_type; uint16_t e_machine; uint32_t e_version; uint64_t e_entry; // Use 64-bit for both, cast for 32 uint64_t e_phoff; uint64_t e_shoff; uint32_t e_flags; uint16_t e_ehsize; uint16_t e_phentsize; uint16_t e_phnum; uint16_t e_shentsize; uint16_t e_shnum; uint16_t e_shstrndx; int is_64bit; int little_endian; size_t header_size; } ElfProperties; void read_header(const char* filename, ElfProperties* props) { FILE* f = fopen(filename, "rb"); if (!f) { perror("fopen"); exit(1); } uint8_t e_ident[16]; fread(e_ident, 1, 16, f); if (e_ident[0] != 0x7F || e_ident[1] != 'E' || e_ident[2] != 'L' || e_ident[3] != 'F') { fprintf(stderr, "Invalid ELF magic\n"); exit(1); } props->ei_class = e_ident[4]; props->ei_data = e_ident[5]; props->is_64bit = props->ei_class == 2; props->little_endian = props->ei_data == 1; props->header_size = props->is_64bit ? 64 : 52; // For simplicity, assume host little-endian; no swap needed if matches // In production, add byte swaps if host != file endian fread(&props->e_type, 2, 1, f); fread(&props->e_machine, 2, 1, f); fread(&props->e_version, 4, 1, f); if (props->is_64bit) { fread(&props->e_entry, 8, 1, f); fread(&props->e_phoff, 8, 1, f); fread(&props->e_shoff, 8, 1, f); } else { uint32_t temp; fread(&temp, 4, 1, f); props->e_entry = temp; fread(&temp, 4, 1, f); props->e_phoff = temp; fread(&temp, 4, 1, f); props->e_shoff = temp; } fread(&props->e_flags, 4, 1, f); fread(&props->e_ehsize, 2, 1, f); fread(&props->e_phentsize, 2, 1, f); fread(&props->e_phnum, 2, 1, f); fread(&props->e_shentsize, 2, 1, f); fread(&props->e_shnum, 2, 1, f); fread(&props->e_shstrndx, 2, 1, f); props->ei_version = e_ident[6]; props->ei_osabi = e_ident[7]; props->ei_abiversion = e_ident[8]; fclose(f); } void print_properties(ElfProperties* props) { printf("EI_CLASS: %u\n", props->ei_class); printf("EI_DATA: %u\n", props->ei_data); printf("EI_VERSION: %u\n", props->ei_version); printf("EI_OSABI: %u\n", props->ei_osabi); printf("EI_ABIVERSION: %u\n", props->ei_abiversion); printf("e_type: %u\n", props->e_type); printf("e_machine: %u\n", props->e_machine); printf("e_version: %u\n", props->e_version); printf("e_entry: %llu\n", (unsigned long long)props->e_entry); printf("e_phoff: %llu\n", (unsigned long long)props->e_phoff); printf("e_shoff: %llu\n", (unsigned long long)props->e_shoff); printf("e_flags: %u\n", props->e_flags); printf("e_ehsize: %u\n", props->e_ehsize); printf("e_phentsize: %u\n", props->e_phentsize); printf("e_phnum: %u\n", props->e_phnum); printf("e_shentsize: %u\n", props->e_shentsize); printf("e_shnum: %u\n", props->e_shnum); printf("e_shstrndx: %u\n", props->e_shstrndx); } void write_header(const char* filename, const char* output_filename, ElfProperties* props, int modify_entry) { // Example modification: set e_entry if flag set if (modify_entry) { props->e_entry = 0x1234; } FILE* in = fopen(filename, "rb"); FILE* out = fopen(output_filename, "wb"); if (!in || !out) { perror("fopen"); exit(1); } // Write e_ident uint8_t e_ident[16] = {0x7F, 'E', 'L', 'F', props->ei_class, props->ei_data, props->ei_version, props->ei_osabi, props->ei_abiversion, 0,0,0,0,0,0,0}; fwrite(e_ident, 1, 16, out); fwrite(&props->e_type, 2, 1, out); fwrite(&props->e_machine, 2, 1, out); fwrite(&props->e_version, 4, 1, out); if (props->is_64bit) { fwrite(&props->e_entry, 8, 1, out); fwrite(&props->e_phoff, 8, 1, out); fwrite(&props->e_shoff, 8, 1, out); } else { uint32_t temp = (uint32_t)props->e_entry; fwrite(&temp, 4, 1, out); temp = (uint32_t)props->e_phoff; fwrite(&temp, 4, 1, out); temp = (uint32_t)props->e_shoff; fwrite(&temp, 4, 1, out); } fwrite(&props->e_flags, 4, 1, out); fwrite(&props->e_ehsize, 2, 1, out); fwrite(&props->e_phentsize, 2, 1, out); fwrite(&props->e_phnum, 2, 1, out); fwrite(&props->e_shentsize, 2, 1, out); fwrite(&props->e_shnum, 2, 1, out); fwrite(&props->e_shstrndx, 2, 1, out); // Copy rest of file fseek(in, props->header_size, SEEK_SET); uint8_t buf[4096]; size_t len; while ((len = fread(buf, 1, sizeof(buf), in)) > 0) { fwrite(buf, 1, len, out); } fclose(in); fclose(out); } // Example usage: // int main(int argc, char** argv) { // ElfProperties props; // read_header("example.elf", &props); // print_properties(&props); // write_header("example.elf", "modified.elf", &props, 1); // Modify e_entry // return 0; // } // ===== end task-175 .ELF ===== // ===== task-176 .EMAIL [C++] ===== #include #include #include #include #include class EmailFileHandler { private: std::string filepath; std::map headers; std::string body; public: EmailFileHandler(const std::string& filepath) : filepath(filepath) {} void readAndDecode() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file" << std::endl; return; } std::string line; std::string currentKey; bool inHeaders = true; while (std::getline(file, line)) { if (inHeaders) { if (line.empty() || line == "\r") { inHeaders = false; continue; } size_t colonPos = line.find(':'); if (colonPos != std::string::npos && colonPos > 0) { if (!currentKey.empty()) { headers[currentKey] = trim(valueStream.str()); } currentKey = trim(line.substr(0, colonPos)); valueStream.str(line.substr(colonPos + 1)); } else if (!currentKey.empty() && (line[0] == ' ' || line[0] == '\t')) { valueStream << " " << trim(line); } } else { body += line + "\n"; } } if (!currentKey.empty()) { headers[currentKey] = trim(valueStream.str()); } body = trim(body); file.close(); // Basic decoding (no advanced MIME handling) } private: std::string trim(const std::string& str) { size_t first = str.find_first_not_of(" \t"); if (first == std::string::npos) return ""; size_t last = str.find_last_not_of(" \t"); return str.substr(first, (last - first + 1)); } std::ostringstream valueStream; public: void printProperties() { std::cout << "Properties (Headers):" << std::endl; for (const auto& pair : headers) { std::cout << pair.first << ": " << pair.second << std::endl; } std::cout << "\nBody:" << std::endl; std::cout << body << std::endl; } void write(const std::string& outputFilepath, const std::map& modifications) { if (headers.empty()) { readAndDecode(); } for (const auto& mod : modifications) { headers[mod.first] = mod.second; } std::ofstream file(outputFilepath); if (!file.is_open()) { std::cerr << "Error writing file" << std::endl; return; } for (const auto& pair : headers) { file << pair.first << ": " << pair.second << "\n"; } file << "\n" << body; file.close(); } }; // Example usage: // int main() { // EmailFileHandler handler("sample.eml"); // handler.readAndDecode(); // handler.printProperties(); // std::map mods = {{"Subject", "New Subject"}}; // handler.write("modified.eml", mods); // return 0; // } // ===== end task-176 .EMAIL ===== // ===== task-177 .EMAKER [C] ===== #include #include #include #include #include typedef struct { char* filepath; char* content; } EMakerFileHandler; void init(EMakerFileHandler* handler, const char* filepath) { handler->filepath = strdup(filepath); handler->content = NULL; } void read_and_decode(EMakerFileHandler* handler) { FILE* file = fopen(handler->filepath, "r"); if (!file) { perror("Error opening file"); return; } fseek(file, 0, SEEK_END); long size = ftell(file); fseek(file, 0, SEEK_SET); handler->content = malloc(size + 1); fread(handler->content, 1, size, file); handler->content[size] = '\0'; fclose(file); char* maker_name = "Unknown"; char* def_pos = strstr(handler->content, "def "); if (def_pos) { def_pos += 4; while (*def_pos == ' ') def_pos++; char buffer[256]; sscanf(def_pos, "%255s", buffer); maker_name = buffer; } struct stat st; stat(handler->filepath, &st); char mod_time[64]; strftime(mod_time, sizeof(mod_time), "%Y-%m-%d %H:%M:%S", localtime(&st.st_mtime)); int is_utf8 = 0; for (char* c = handler->content; *c; c++) { if ((unsigned char)*c > 127) { is_utf8 = 1; break; } } printf("File Extension: .emaker\n"); printf("MIME Type: text/plain\n"); printf("File Signature: None (text file)\n"); printf("Encoding: %s\n", is_utf8 ? "UTF-8" : "ASCII"); printf("Structure: E language source code\n"); printf("Size: %ld bytes\n", size); printf("Last Modified: %s\n", mod_time); printf("Security Properties: Executes with no initial authority in E\n"); printf("Content Type: E source code (maker)\n"); printf("Defined Maker: %s\n", maker_name); printf("Full Content:\n%s\n", handler->content); } void write_file(EMakerFileHandler* handler, const char* new_content, const char* new_filepath) { const char* path = new_filepath ? new_filepath : handler->filepath; FILE* file = fopen(path, "w"); if (!file) { perror("Error writing file"); return; } fprintf(file, "%s", new_content); fclose(file); printf("Written to %s\n", path); } void destroy(EMakerFileHandler* handler) { free(handler->filepath); free(handler->content); } // Example usage: // int main() { // EMakerFileHandler handler; // init(&handler, "example.emaker"); // read_and_decode(&handler); // write_file(&handler, "new content", "new.emaker"); // destroy(&handler); // return 0; // } // ===== end task-177 .EMAKER ===== // ===== task-178 .EMAKER [C] ===== #include #include #include #include typedef struct { int32_t bounds[4]; // left, top, right, bottom int32_t frame[4]; uint32_t recordSignature; uint32_t version; uint32_t bytes; uint32_t records; uint16_t handles; uint16_t reserved; uint32_t nDescription; uint32_t offDescription; uint32_t nPalEntries; uint32_t device[2]; // width, height uint32_t millimeters[2]; uint32_t cbPixelFormat; uint32_t offPixelFormat; uint32_t bOpenGL; uint32_t micrometersX; uint32_t micrometersY; int hasExtension1; int hasExtension2; } EmfProperties; void read_decode(const char* filename, EmfProperties* props) { FILE* f = fopen(filename, "rb"); if (!f) return; uint32_t type, size; fread(&type, sizeof(uint32_t), 1, f); fread(&size, sizeof(uint32_t), 1, f); if (type != 1) { fclose(f); return; } fread(props->bounds, sizeof(int32_t), 4, f); fread(props->frame, sizeof(int32_t), 4, f); fread(&props->recordSignature, sizeof(uint32_t), 1, f); fread(&props->version, sizeof(uint32_t), 1, f); fread(&props->bytes, sizeof(uint32_t), 1, f); fread(&props->records, sizeof(uint32_t), 1, f); fread(&props->handles, sizeof(uint16_t), 1, f); fread(&props->reserved, sizeof(uint16_t), 1, f); fread(&props->nDescription, sizeof(uint32_t), 1, f); fread(&props->offDescription, sizeof(uint32_t), 1, f); fread(&props->nPalEntries, sizeof(uint32_t), 1, f); fread(props->device, sizeof(uint32_t), 2, f); fread(props->millimeters, sizeof(uint32_t), 2, f); props->hasExtension1 = (size >= 100); if (props->hasExtension1) { fread(&props->cbPixelFormat, sizeof(uint32_t), 1, f); fread(&props->offPixelFormat, sizeof(uint32_t), 1, f); fread(&props->bOpenGL, sizeof(uint32_t), 1, f); } props->hasExtension2 = (size >= 108); if (props->hasExtension2) { fread(&props->micrometersX, sizeof(uint32_t), 1, f); fread(&props->micrometersY, sizeof(uint32_t), 1, f); } fclose(f); } void print_properties(const EmfProperties* props) { printf("Bounds: [%d, %d, %d, %d]\n", props->bounds[0], props->bounds[1], props->bounds[2], props->bounds[3]); printf("Frame: [%d, %d, %d, %d]\n", props->frame[0], props->frame[1], props->frame[2], props->frame[3]); printf("RecordSignature: %u\n", props->recordSignature); printf("Version: %u\n", props->version); printf("Bytes: %u\n", props->bytes); printf("Records: %u\n", props->records); printf("Handles: %u\n", props->handles); printf("Reserved: %u\n", props->reserved); printf("nDescription: %u\n", props->nDescription); printf("offDescription: %u\n", props->offDescription); printf("nPalEntries: %u\n", props->nPalEntries); printf("Device: [%u, %u]\n", props->device[0], props->device[1]); printf("Millimeters: [%u, %u]\n", props->millimeters[0], props->millimeters[1]); if (props->hasExtension1) { printf("cbPixelFormat: %u\n", props->cbPixelFormat); printf("offPixelFormat: %u\n", props->offPixelFormat); printf("bOpenGL: %u\n", props->bOpenGL); } if (props->hasExtension2) { printf("MicrometersX: %u\n", props->micrometersX); printf("MicrometersY: %u\n", props->micrometersY); } } void write_emf(const char* output_filename) { FILE* f = fopen(output_filename, "wb"); if (!f) return; uint32_t type = 1, size = 88; fwrite(&type, sizeof(uint32_t), 1, f); fwrite(&size, sizeof(uint32_t), 1, f); int32_t bounds[4] = {0, 0, 100, 100}; fwrite(bounds, sizeof(int32_t), 4, f); int32_t frame[4] = {0, 0, 1000, 1000}; fwrite(frame, sizeof(int32_t), 4, f); uint32_t sig = 0x464D4520; fwrite(&sig, sizeof(uint32_t), 1, f); uint32_t ver = 0x00010000; fwrite(&ver, sizeof(uint32_t), 1, f); uint32_t bytes = 100; fwrite(&bytes, sizeof(uint32_t), 1, f); uint32_t recs = 2; fwrite(&recs, sizeof(uint32_t), 1, f); uint16_t handles = 0; fwrite(&handles, sizeof(uint16_t), 1, f); uint16_t res = 0; fwrite(&res, sizeof(uint16_t), 1, f); uint32_t ndesc = 0; fwrite(&ndesc, sizeof(uint32_t), 1, f); uint32_t offdesc = 0; fwrite(&offdesc, sizeof(uint32_t), 1, f); uint32_t npal = 0; fwrite(&npal, sizeof(uint32_t), 1, f); uint32_t dev[2] = {800, 600}; fwrite(dev, sizeof(uint32_t), 2, f); uint32_t mm[2] = {210, 297}; fwrite(mm, sizeof(uint32_t), 2, f); // EOF uint32_t eof_type = 14, eof_size = 20; fwrite(&eof_type, sizeof(uint32_t), 1, f); fwrite(&eof_size, sizeof(uint32_t), 1, f); uint32_t zero = 0; fwrite(&zero, sizeof(uint32_t), 1, f); fwrite(&zero, sizeof(uint32_t), 1, f); uint16_t zero16 = 0; fwrite(&zero16, sizeof(uint16_t), 1, f); fwrite(&zero16, sizeof(uint16_t), 1, f); fclose(f); } // Example usage: // int main() { // EmfProperties props = {0}; // read_decode("input.emf", &props); // print_properties(&props); // write_emf("output.emf"); // return 0; // } // ===== end task-178 .EMAKER ===== // ===== task-179 .EML [C++] ===== #include #include #include #include #include #include #include class EMLHandler { private: std::string filepath; std::map headers; std::string body; void parse(const std::string& content) { std::vector lines; std::string line; for (char c : content) { if (c == '\n') { lines.push_back(line); line.clear(); } else { line += c; } } if (!line.empty()) lines.push_back(line); bool headerMode = true; std::string currentHeader; size_t i = 0; while (i < lines.size()) { line = lines[i]; if (headerMode) { if (line.empty()) { headerMode = false; ++i; continue; } if (std::isspace(line[0])) { if (!currentHeader.empty()) { headers[currentHeader] += " " + line.substr(1); } } else { size_t colonPos = line.find(':'); if (colonPos != std::string::npos) { currentHeader = line.substr(0, colonPos); // Trim spaces currentHeader.erase(0, currentHeader.find_first_not_of(" \t")); currentHeader.erase(currentHeader.find_last_not_of(" \t") + 1); std::string value = line.substr(colonPos + 1); value.erase(0, value.find_first_not_of(" \t")); headers[currentHeader] = value; } } } else { body += line + "\n"; } ++i; } auto it = headers.find("Content-Type"); std::string contentType = (it != headers.end()) ? it->second : ""; if (contentType.find("multipart/") != std::string::npos) { body = "Multipart body detected (full parsing omitted)."; } else { it = headers.find("Content-Transfer-Encoding"); std::string transferEncoding = (it != headers.end()) ? it->second : ""; std::transform(transferEncoding.begin(), transferEncoding.end(), transferEncoding.begin(), ::tolower); if (transferEncoding == "base64") { // Simple base64 decode (implement if needed; omitted for brevity) body = "Base64 decoded body (implementation omitted)."; } else if (transferEncoding == "quoted-printable") { body = decodeQuotedPrintable(body); } } } std::string decodeQuotedPrintable(const std::string& text) { std::string result; for (size_t i = 0; i < text.size(); ++i) { if (text[i] == '=' && i + 2 < text.size() && isxdigit(text[i+1]) && isxdigit(text[i+2])) { char hex[3] = {text[i+1], text[i+2], '\0'}; result += static_cast(strtol(hex, nullptr, 16)); i += 2; } else if (text[i] == '=' && (text[i+1] == '\r' || text[i+1] == '\n')) { ++i; } else { result += text[i]; } } return result; } public: EMLHandler(const std::string& fp) : filepath(fp) { std::ifstream file(filepath); if (!file) { throw std::runtime_error("Failed to open file"); } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); parse(content); } void decodeAndPrintProperties(const std::vector& propertiesList) { std::cout << "Properties for " << filepath << ":" << std::endl; for (const auto& prop : propertiesList) { auto it = headers.find(prop); if (it != headers.end()) { std::cout << prop << ": " << it->second << std::endl; } } std::cout << "\nBody: " << body.substr(0, 500) << "... (truncated)" << std::endl; } void write(const std::string& newFilepath, const std::map& changes) { for (const auto& change : changes) { headers[change.first] = change.second; } std::ofstream file(newFilepath); if (!file) { throw std::runtime_error("Failed to write file"); } for (const auto& header : headers) { file << header.first << ": " << header.second << "\n"; } file << "\n" << body; } }; int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "Usage: ./program path/to/file.eml" << std::endl; return 1; } std::vector propertiesList = { "Accept-Language", "Also-Control", /* ... full list omitted for brevity ... */ "Xref" }; try { EMLHandler handler(argv[1]); handler.decodeAndPrintProperties(propertiesList); // Example: std::map changes = {{"Subject", "Modified Subject"}}; // handler.write("output.eml", changes); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } return 0; } // ===== end task-179 .EML ===== // ===== task-180 .EMZ [C++] ===== #include #include #include #include #include #include class EMZParser { private: std::vector data; uint8_t id1, id2, cm, flg, xfl, os; uint32_t mtime; std::vector extra; std::string name; std::string comment; uint16_t hcrc; bool has_hcrc; size_t compressed_size; uint32_t crc32; uint32_t isize; public: EMZParser(const std::string& filename) { std::ifstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Failed to open file"); } data.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); parse(); } void parse() { size_t pos = 0; id1 = data[pos++]; id2 = data[pos++]; cm = data[pos++]; flg = data[pos++]; mtime = *reinterpret_cast(&data[pos]); pos += 4; xfl = data[pos++]; os = data[pos++]; if (flg & 4) { // FEXTRA uint16_t xlen = *reinterpret_cast(&data[pos]); pos += 2; extra.assign(data.begin() + pos, data.begin() + pos + xlen); pos += xlen; } if (flg & 8) { // FNAME size_t start = pos; while (data[pos] != 0) pos++; name.assign(reinterpret_cast(&data[start]), pos - start); pos++; } if (flg & 16) { // FCOMMENT size_t start = pos; while (data[pos] != 0) pos++; comment.assign(reinterpret_cast(&data[start]), pos - start); pos++; } has_hcrc = false; if (flg & 2) { // FHCRC hcrc = *reinterpret_cast(&data[pos]); pos += 2; has_hcrc = true; } compressed_size = data.size() - pos - 8; pos = data.size() - 8; crc32 = *reinterpret_cast(&data[pos]); pos += 4; isize = *reinterpret_cast(&data[pos]); } void printProperties() const { std::cout << "ID1: 0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(2) << static_cast(id1) << std::dec << std::nouppercase << std::endl; std::cout << "ID2: 0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(2) << static_cast(id2) << std::dec << std::nouppercase << std::endl; std::cout << "CM: 0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(2) << static_cast(cm) << std::dec << std::nouppercase << std::endl; std::cout << "FLG: 0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(2) << static_cast(flg) << std::dec << std::nouppercase << std::endl; std::cout << "MTIME: " << mtime << std::endl; std::cout << "XFL: 0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(2) << static_cast(xfl) << std::dec << std::nouppercase << std::endl; std::cout << "OS: 0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(2) << static_cast(os) << std::dec << std::nouppercase << std::endl; if (!extra.empty()) { std::cout << "Extra: "; for (auto b : extra) std::cout << std::hex << std::uppercase << std::setfill('0') << std::setw(2) << static_cast(b) << " "; std::cout << std::dec << std::nouppercase << std::endl; } if (!name.empty()) std::cout << "Name: " << name << std::endl; if (!comment.empty()) std::cout << "Comment: " << comment << std::endl; if (has_hcrc) std::cout << "HCRC: 0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(4) << hcrc << std::dec << std::nouppercase << std::endl; std::cout << "Compressed data size: " << compressed_size << " bytes" << std::endl; std::cout << "CRC32: 0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(8) << crc32 << std::dec << std::nouppercase << std::endl; std::cout << "ISIZE: " << isize << std::endl; } void write(const std::string& filename) const { std::ofstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Failed to write file"); } file.write(reinterpret_cast(data.data()), data.size()); } }; // Example usage: // int main() { // try { // EMZParser parser("example.emz"); // parser.printProperties(); // parser.write("output.emz"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-180 .EMZ ===== // ===== task-181 .EOT [C++] ===== #include #include #include #include #include #include class EOTHandler { private: std::string filepath; struct Properties { uint32_t EOTSize; uint32_t FontDataSize; uint32_t Version; uint32_t Flags; uint8_t FontPANOSE[10]; uint8_t Charset; uint8_t Italic; uint32_t Weight; uint16_t fsType; uint16_t MagicNumber; uint32_t UnicodeRange1; uint32_t UnicodeRange2; uint32_t UnicodeRange3; uint32_t UnicodeRange4; uint32_t CodePageRange1; uint32_t CodePageRange2; uint32_t CheckSumAdjustment; uint32_t Reserved1; uint32_t Reserved2; uint32_t Reserved3; uint32_t Reserved4; uint16_t Padding1; uint16_t FamilyNameSize; std::wstring FamilyName; uint16_t Padding2; uint16_t StyleNameSize; std::wstring StyleName; uint16_t Padding3; uint16_t VersionNameSize; std::wstring VersionName; uint16_t Padding4; uint16_t FullNameSize; std::wstring FullName; uint16_t RootStringSize; std::wstring RootString; uint32_t RootStringCheckSum; uint32_t EUDCCodePage; uint16_t Padding5; uint16_t SignatureSize; std::vector Signature; uint32_t EUDCFlags; uint32_t EUDCFontSize; std::vector EUDCFontData; std::vector FontData; } props; public: EOTHandler(const std::string& fp) : filepath(fp) { readFile(); } void readFile() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); std::vector buffer(size); file.read(buffer.data(), size); char* data = buffer.data(); size_t offset = 0; std::memcpy(&props.EOTSize, data + offset, 4); offset += 4; std::memcpy(&props.FontDataSize, data + offset, 4); offset += 4; std::memcpy(&props.Version, data + offset, 4); offset += 4; std::memcpy(&props.Flags, data + offset, 4); offset += 4; std::memcpy(props.FontPANOSE, data + offset, 10); offset += 10; std::memcpy(&props.Charset, data + offset, 1); offset += 1; std::memcpy(&props.Italic, data + offset, 1); offset += 1; std::memcpy(&props.Weight, data + offset, 4); offset += 4; std::memcpy(&props.fsType, data + offset, 2); offset += 2; std::memcpy(&props.MagicNumber, data + offset, 2); offset += 2; std::memcpy(&props.UnicodeRange1, data + offset, 4); offset += 4; std::memcpy(&props.UnicodeRange2, data + offset, 4); offset += 4; std::memcpy(&props.UnicodeRange3, data + offset, 4); offset += 4; std::memcpy(&props.UnicodeRange4, data + offset, 4); offset += 4; std::memcpy(&props.CodePageRange1, data + offset, 4); offset += 4; std::memcpy(&props.CodePageRange2, data + offset, 4); offset += 4; std::memcpy(&props.CheckSumAdjustment, data + offset, 4); offset += 4; std::memcpy(&props.Reserved1, data + offset, 4); offset += 4; std::memcpy(&props.Reserved2, data + offset, 4); offset += 4; std::memcpy(&props.Reserved3, data + offset, 4); offset += 4; std::memcpy(&props.Reserved4, data + offset, 4); offset += 4; std::memcpy(&props.Padding1, data + offset, 2); offset += 2; std::memcpy(&props.FamilyNameSize, data + offset, 2); offset += 2; props.FamilyName = std::wstring(reinterpret_cast(data + offset), props.FamilyNameSize / 2); offset += props.FamilyNameSize; std::memcpy(&props.Padding2, data + offset, 2); offset += 2; std::memcpy(&props.StyleNameSize, data + offset, 2); offset += 2; props.StyleName = std::wstring(reinterpret_cast(data + offset), props.StyleNameSize / 2); offset += props.StyleNameSize; std::memcpy(&props.Padding3, data + offset, 2); offset += 2; std::memcpy(&props.VersionNameSize, data + offset, 2); offset += 2; props.VersionName = std::wstring(reinterpret_cast(data + offset), props.VersionNameSize / 2); offset += props.VersionNameSize; std::memcpy(&props.Padding4, data + offset, 2); offset += 2; std::memcpy(&props.FullNameSize, data + offset, 2); offset += 2; props.FullName = std::wstring(reinterpret_cast(data + offset), props.FullNameSize / 2); offset += props.FullNameSize; if (props.Version >= 0x00020001) { std::memcpy(&props.RootStringSize, data + offset, 2); offset += 2; props.RootString = std::wstring(reinterpret_cast(data + offset), props.RootStringSize / 2); offset += props.RootStringSize; if (props.Version == 0x00020002) { std::memcpy(&props.RootStringCheckSum, data + offset, 4); offset += 4; std::memcpy(&props.EUDCCodePage, data + offset, 4); offset += 4; std::memcpy(&props.Padding5, data + offset, 2); offset += 2; std::memcpy(&props.SignatureSize, data + offset, 2); offset += 2; props.Signature.assign(data + offset, data + offset + props.SignatureSize); offset += props.SignatureSize; std::memcpy(&props.EUDCFlags, data + offset, 4); offset += 4; std::memcpy(&props.EUDCFontSize, data + offset, 4); offset += 4; props.EUDCFontData.assign(data + offset, data + offset + props.EUDCFontSize); offset += props.EUDCFontSize; } } props.FontData.assign(data + offset, data + offset + props.FontDataSize); } void printProperties() { std::cout << "EOTSize: " << props.EOTSize << std::endl; std::cout << "FontDataSize: " << props.FontDataSize << std::endl; std::cout << "Version: " << props.Version << std::endl; std::cout << "Flags: " << props.Flags << std::endl; std::cout << "FontPANOSE: "; for (int i = 0; i < 10; i++) std::cout << (int)props.FontPANOSE[i] << " "; std::cout << std::endl; std::cout << "Charset: " << (int)props.Charset << std::endl; std::cout << "Italic: " << (int)props.Italic << std::endl; std::cout << "Weight: " << props.Weight << std::endl; std::cout << "fsType: " << props.fsType << std::endl; std::cout << "MagicNumber: " << props.MagicNumber << std::endl; std::cout << "UnicodeRange1: " << props.UnicodeRange1 << std::endl; std::cout << "UnicodeRange2: " << props.UnicodeRange2 << std::endl; std::cout << "UnicodeRange3: " << props.UnicodeRange3 << std::endl; std::cout << "UnicodeRange4: " << props.UnicodeRange4 << std::endl; std::cout << "CodePageRange1: " << props.CodePageRange1 << std::endl; std::cout << "CodePageRange2: " << props.CodePageRange2 << std::endl; std::cout << "CheckSumAdjustment: " << props.CheckSumAdjustment << std::endl; std::cout << "Reserved1: " << props.Reserved1 << std::endl; std::cout << "Reserved2: " << props.Reserved2 << std::endl; std::cout << "Reserved3: " << props.Reserved3 << std::endl; std::cout << "Reserved4: " << props.Reserved4 << std::endl; std::cout << "Padding1: " << props.Padding1 << std::endl; std::cout << "FamilyNameSize: " << props.FamilyNameSize << std::endl; std::wcout << L"FamilyName: " << props.FamilyName << std::endl; std::cout << "Padding2: " << props.Padding2 << std::endl; std::cout << "StyleNameSize: " << props.StyleNameSize << std::endl; std::wcout << L"StyleName: " << props.StyleName << std::endl; std::cout << "Padding3: " << props.Padding3 << std::endl; std::cout << "VersionNameSize: " << props.VersionNameSize << std::endl; std::wcout << L"VersionName: " << props.VersionName << std::endl; std::cout << "Padding4: " << props.Padding4 << std::endl; std::cout << "FullNameSize: " << props.FullNameSize << std::endl; std::wcout << L"FullName: " << props.FullName << std::endl; if (props.Version >= 0x00020001) { std::cout << "RootStringSize: " << props.RootStringSize << std::endl; std::wcout << L"RootString: " << props.RootString << std::endl; if (props.Version == 0x00020002) { std::cout << "RootStringCheckSum: " << props.RootStringCheckSum << std::endl; std::cout << "EUDCCodePage: " << props.EUDCCodePage << std::endl; std::cout << "Padding5: " << props.Padding5 << std::endl; std::cout << "SignatureSize: " << props.SignatureSize << std::endl; std::cout << "Signature: "; for (auto b : props.Signature) std::cout << (int)b << " "; std::cout << std::endl; std::cout << "EUDCFlags: " << props.EUDCFlags << std::endl; std::cout << "EUDCFontSize: " << props.EUDCFontSize << std::endl; std::cout << "EUDCFontData size: " << props.EUDCFontData.size() << std::endl; // Truncated } } std::cout << "FontData size: " << props.FontData.size() << std::endl; // Truncated } void writeFile(const std::string& outputPath) { std::ofstream file(outputPath, std::ios::binary); file.write(reinterpret_cast(&props.EOTSize), 4); file.write(reinterpret_cast(&props.FontDataSize), 4); file.write(reinterpret_cast(&props.Version), 4); file.write(reinterpret_cast(&props.Flags), 4); file.write(reinterpret_cast(props.FontPANOSE), 10); file.write(reinterpret_cast(&props.Charset), 1); file.write(reinterpret_cast(&props.Italic), 1); file.write(reinterpret_cast(&props.Weight), 4); file.write(reinterpret_cast(&props.fsType), 2); file.write(reinterpret_cast(&props.MagicNumber), 2); file.write(reinterpret_cast(&props.UnicodeRange1), 4); file.write(reinterpret_cast(&props.UnicodeRange2), 4); file.write(reinterpret_cast(&props.UnicodeRange3), 4); file.write(reinterpret_cast(&props.UnicodeRange4), 4); file.write(reinterpret_cast(&props.CodePageRange1), 4); file.write(reinterpret_cast(&props.CodePageRange2), 4); file.write(reinterpret_cast(&props.CheckSumAdjustment), 4); file.write(reinterpret_cast(&props.Reserved1), 4); file.write(reinterpret_cast(&props.Reserved2), 4); file.write(reinterpret_cast(&props.Reserved3), 4); file.write(reinterpret_cast(&props.Reserved4), 4); file.write(reinterpret_cast(&props.Padding1), 2); file.write(reinterpret_cast(&props.FamilyNameSize), 2); file.write(reinterpret_cast(props.FamilyName.data()), props.FamilyNameSize); file.write(reinterpret_cast(&props.Padding2), 2); file.write(reinterpret_cast(&props.StyleNameSize), 2); file.write(reinterpret_cast(props.StyleName.data()), props.StyleNameSize); file.write(reinterpret_cast(&props.Padding3), 2); file.write(reinterpret_cast(&props.VersionNameSize), 2); file.write(reinterpret_cast(props.VersionName.data()), props.VersionNameSize); file.write(reinterpret_cast(&props.Padding4), 2); file.write(reinterpret_cast(&props.FullNameSize), 2); file.write(reinterpret_cast(props.FullName.data()), props.FullNameSize); if (props.Version >= 0x00020001) { file.write(reinterpret_cast(&props.RootStringSize), 2); file.write(reinterpret_cast(props.RootString.data()), props.RootStringSize); if (props.Version == 0x00020002) { file.write(reinterpret_cast(&props.RootStringCheckSum), 4); file.write(reinterpret_cast(&props.EUDCCodePage), 4); file.write(reinterpret_cast(&props.Padding5), 2); file.write(reinterpret_cast(&props.SignatureSize), 2); file.write(reinterpret_cast(props.Signature.data()), props.SignatureSize); file.write(reinterpret_cast(&props.EUDCFlags), 4); file.write(reinterpret_cast(&props.EUDCFontSize), 4); file.write(reinterpret_cast(props.EUDCFontData.data()), props.EUDCFontSize); } } file.write(reinterpret_cast(props.FontData.data()), props.FontDataSize); } }; // Example usage: // int main() { // EOTHandler handler("example.eot"); // handler.printProperties(); // handler.writeFile("output.eot"); // return 0; // } // ===== end task-181 .EOT ===== // ===== task-182 .EP [C++] ===== #include #include #include #include #include #include "tinyxml2.h" // Assume tinyxml2.h is included for XML parsing using namespace tinyxml2; class EPFileHandler { private: std::string filepath; XMLDocument doc; public: EPFileHandler(const std::string& fp) : filepath(fp) {} bool open() { return doc.LoadFile(filepath.c_str()) == XML_SUCCESS; } std::map readDocumentProperties(XMLElement* propsEl) { std::map props; if (propsEl) { for (XMLElement* prop = propsEl->FirstChildElement("Property"); prop; prop = prop->NextSiblingElement("Property")) { const char* name = prop->Attribute("name"); if (name) { props[name] = prop->GetText() ? prop->GetText() : ""; } } } return props; } void printProperties() { if (doc.Error()) { std::cerr << "Error loading file" << std::endl; return; } XMLElement* root = doc.RootElement(); if (!root) return; std::cout << "Properties of .EP file:" << std::endl; std::cout << "XML Version: 1.0" << std::endl; // Assumed std::cout << "Encoding: UTF-8" << std::endl; // Assumed std::cout << "Namespace: " << (root->Attribute("xmlns") ? root->Attribute("xmlns") : "http://www.evolus.vn/Namespace/Pencil") << std::endl; auto docProps = readDocumentProperties(root->FirstChildElement("Properties")); std::cout << "Document Properties:" << std::endl; if (docProps.empty()) { std::cout << " None" << std::endl; } else { for (const auto& kv : docProps) { std::cout << " - " << kv.first << ": " << kv.second << std::endl; } } int numPages = 0; std::vector> pages; for (XMLElement* page = root->FirstChildElement("Pages")->FirstChildElement("Page"); page; page = page->NextSiblingElement("Page")) { numPages++; std::map pageInfo; pageInfo["id"] = page->Attribute("id") ? page->Attribute("id") : "N/A"; pageInfo["name"] = "N/A"; pageInfo["width"] = "N/A"; pageInfo["height"] = "N/A"; pageInfo["backgroundColor"] = "N/A"; pageInfo["scale"] = "N/A"; pageInfo["note"] = "N/A"; auto pageProps = readDocumentProperties(page->FirstChildElement("Properties")); for (const auto& kv : pageProps) { if (pageInfo.count(kv.first)) { pageInfo[kv.first] = kv.second; } } pages.push_back(pageInfo); } std::cout << "Number of Pages: " << numPages << std::endl; for (size_t i = 0; i < pages.size(); ++i) { auto& page = pages[i]; std::cout << "\nPage " << (i + 1) << ":" << std::endl; std::cout << " ID: " << page["id"] << std::endl; std::cout << " Name: " << page["name"] << std::endl; std::cout << " Width: " << page["width"] << std::endl; std::cout << " Height: " << page["height"] << std::endl; std::cout << " Background Color: " << page["backgroundColor"] << std::endl; std::cout << " Scale: " << page["scale"] << std::endl; std::cout << " Note: " << page["note"] << std::endl; } } bool write(const std::vector>& newPages) { // Basic write: Update page names XMLElement* pagesEl = doc.RootElement()->FirstChildElement("Pages"); if (!pagesEl) return false; int index = 0; for (XMLElement* page = pagesEl->FirstChildElement("Page"); page; page = page->NextSiblingElement("Page")) { if (index >= newPages.size()) break; XMLElement* propsEl = page->FirstChildElement("Properties"); if (propsEl) { for (XMLElement* prop = propsEl->FirstChildElement("Property"); prop; prop = prop->NextSiblingElement("Property")) { if (std::string(prop->Attribute("name")) == "name") { prop->SetText(newPages[index]["name"].c_str()); } } } index++; } return doc.SaveFile(filepath.c_str()) == XML_SUCCESS; } }; // Example usage: // int main() { // EPFileHandler handler("example.ep"); // if (handler.open()) { // handler.printProperties(); // std::vector> newPages = {{{"name", "New Name"}}}; // handler.write(newPages); // } // return 0; // } // ===== end task-182 .EP ===== // ===== task-183 .EPA [C++] ===== #include #include #include #include #include class EpaFile { private: int version; std::vector fileData; uint8_t width8, height8; // For v1 uint16_t width16, height16; // For v2 std::vector cmap, bitmap, logo, data, palData; char magic[5], palMagic[5]; public: EpaFile() : version(0) { magic[4] = '\0'; palMagic[4] = '\0'; } bool open(const std::string& filename) { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) return false; std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); fileData.resize(size); file.read(reinterpret_cast(fileData.data()), size); return true; } void read() { if (fileData.size() < 4) return; strncpy(magic, reinterpret_cast(fileData.data()), 4); if (strcmp(magic, "AWBM") == 0) { version = 2; width16 = *reinterpret_cast(fileData.data() + 4); height16 = *reinterpret_cast(fileData.data() + 6); size_t offset = 8; // Assume 4-bit size_t dataLength = (width16 + (7 - width16 % 8)) * height16 / 2; data.assign(fileData.begin() + offset, fileData.begin() + offset + dataLength); offset += dataLength; strncpy(palMagic, reinterpret_cast(fileData.data() + offset), 4); offset += 4; size_t palSize = 48; palData.assign(fileData.begin() + offset, fileData.begin() + offset + palSize); } else { version = 1; width8 = fileData[0]; height8 = fileData[1]; size_t offset = 2; size_t cmapLength = width8 * height8; cmap.assign(fileData.begin() + offset, fileData.begin() + offset + cmapLength); offset += cmapLength; size_t bitmapLength = width8 * height8 * 14; bitmap.assign(fileData.begin() + offset, fileData.begin() + offset + bitmapLength); offset += bitmapLength; logo.assign(fileData.begin() + offset, fileData.begin() + offset + 70); } } void write(const std::string& filename) { std::ofstream file(filename, std::ios::binary); if (!file) return; if (version == 2) { file.write(magic, 4); file.write(reinterpret_cast(&width16), 2); file.write(reinterpret_cast(&height16), 2); file.write(reinterpret_cast(data.data()), data.size()); file.write(palMagic, 4); file.write(reinterpret_cast(palData.data()), palData.size()); } else if (version == 1) { file.write(reinterpret_cast(&width8), 1); file.write(reinterpret_cast(&height8), 1); file.write(reinterpret_cast(cmap.data()), cmap.size()); file.write(reinterpret_cast(bitmap.data()), bitmap.size()); file.write(reinterpret_cast(logo.data()), logo.size()); } } void printProperties() { std::cout << "Version: " << version << std::endl; if (version == 2) { std::cout << "Magic: " << magic << std::endl; std::cout << "Width: " << width16 << std::endl; std::cout << "Height: " << height16 << std::endl; std::cout << "Data: (binary data, length " << data.size() << ")" << std::endl; std::cout << "PalMagic: " << palMagic << std::endl; std::cout << "PalData: (binary data, length " << palData.size() << ")" << std::endl; } else { std::cout << "Width: " << static_cast(width8) << std::endl; std::cout << "Height: " << static_cast(height8) << std::endl; std::cout << "CMap: (binary data, length " << cmap.size() << ")" << std::endl; std::cout << "Bitmap: (binary data, length " << bitmap.size() << ")" << std::endl; std::cout << "Logo: (binary data, length " << logo.size() << ")" << std::endl; } } }; // Example usage: // EpaFile epa; // epa.open("example.epa"); // epa.read(); // epa.printProperties(); // epa.write("output.epa"); // ===== end task-183 .EPA ===== // ===== task-184 .EPS [C++] ===== #include #include #include #include #include #include #include class EPSHandler { private: std::string filepath; std::map properties; std::vector content; bool has_binary_header = false; std::map binary_header; void read_and_decode() { std::ifstream file(filepath, std::ios::binary); if (!file) { std::cerr << "Failed to open file." << std::endl; return; } content.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); // Check binary header if (content.size() >= 30 && std::memcmp(&content[0], "\xC5\xD0\xD3\xC6", 4) == 0) { has_binary_header = true; uint32_t magic = *reinterpret_cast(&content[0]); uint32_t ps_offset = *reinterpret_cast(&content[4]); uint32_t ps_length = *reinterpret_cast(&content[8]); uint32_t mf_offset = *reinterpret_cast(&content[12]); uint32_t mf_length = *reinterpret_cast(&content[16]); uint32_t tiff_offset = *reinterpret_cast(&content[20]); uint32_t tiff_length = *reinterpret_cast(&content[24]); uint16_t checksum = *reinterpret_cast(&content[28]); binary_header["magic"] = magic; binary_header["ps_offset"] = ps_offset; binary_header["ps_length"] = ps_length; binary_header["mf_offset"] = mf_offset; binary_header["mf_length"] = mf_length; binary_header["tiff_offset"] = tiff_offset; binary_header["tiff_length"] = tiff_length; binary_header["checksum"] = checksum; std::string ascii_content(content.begin() + ps_offset, content.begin() + ps_offset + ps_length); parse_dsc(ascii_content); } else { std::string ascii_content(content.begin(), content.end()); parse_dsc(ascii_content); } } void parse_dsc(const std::string& ascii_content) { properties["has_binary_header"] = has_binary_header ? "Yes" : "No"; if (has_binary_header) { properties["magic"] = "0xC5D0D3C6"; properties["ps_offset"] = std::to_string(binary_header["ps_offset"]); properties["ps_length"] = std::to_string(binary_header["ps_length"]); properties["mf_offset"] = std::to_string(binary_header["mf_offset"]); properties["mf_length"] = std::to_string(binary_header["mf_length"]); properties["tiff_offset"] = std::to_string(binary_header["tiff_offset"]); properties["tiff_length"] = std::to_string(binary_header["tiff_length"]); properties["checksum"] = std::to_string(binary_header["checksum"]); } properties["version"] = ""; properties["title"] = ""; properties["creator"] = ""; properties["creation_date"] = ""; properties["bounding_box"] = ""; properties["language_level"] = ""; properties["extensions"] = ""; properties["document_needed_resources"] = ""; properties["preview_type"] = "None"; size_t pos = 0; std::string line; while ((pos = ascii_content.find('\n', pos)) != std::string::npos || pos < ascii_content.size()) { line = ascii_content.substr(0, pos); if (line.rfind("%!PS-Adobe-3.0 EPSF-3.0", 0) == 0) { properties["version"] = line; } else if (line.rfind("%%Title:", 0) == 0) { properties["title"] = line.substr(8); } else if (line.rfind("%%Creator:", 0) == 0) { properties["creator"] = line.substr(10); } else if (line.rfind("%%CreationDate:", 0) == 0) { properties["creation_date"] = line.substr(15); } else if (line.rfind("%%BoundingBox:", 0) == 0) { properties["bounding_box"] = line.substr(14); } else if (line.rfind("%%LanguageLevel:", 0) == 0) { properties["language_level"] = line.substr(16); } else if (line.rfind("%%Extensions:", 0) == 0) { properties["extensions"] = line.substr(13); } else if (line.rfind("%%DocumentNeededResources:", 0) == 0) { properties["document_needed_resources"] = line.substr(26); } else if (line.rfind("%%BeginPreview", 0) == 0) { properties["preview_type"] = "EPSI"; } if (pos == std::string::npos) break; ascii_content = ascii_content.substr(pos + 1); pos = 0; } if (has_binary_header) { if (binary_header["mf_length"] > 0) properties["preview_type"] = "Metafile"; else if (binary_header["tiff_length"] > 0) properties["preview_type"] = "TIFF"; } } public: EPSHandler(const std::string& fp) : filepath(fp) { read_and_decode(); } void print_properties() const { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& new_filepath, const std::map& modify_props = {}) { std::vector new_content = content; if (!modify_props.empty()) { // Simple modify in ASCII uint32_t ascii_start = has_binary_header ? binary_header["ps_offset"] : 0; uint32_t ascii_length = has_binary_header ? binary_header["ps_length"] : content.size(); std::string ascii(new_content.begin() + ascii_start, new_content.begin() + ascii_start + ascii_length); for (const auto& mod : modify_props) { if (mod.first == "title") { size_t pos = ascii.find("%%Title:"); if (pos != std::string::npos) { size_t end = ascii.find('\n', pos); ascii.replace(pos, end - pos, "%%Title: " + mod.second); } } // Add similar for others... } new_content.erase(new_content.begin() + ascii_start, new_content.begin() + ascii_start + ascii_length); new_content.insert(new_content.begin() + ascii_start, ascii.begin(), ascii.end()); } std::ofstream out(new_filepath, std::ios::binary); out.write(reinterpret_cast(new_content.data()), new_content.size()); } }; // Example usage: // int main() { // EPSHandler handler("example.eps"); // handler.print_properties(); // std::map mods = {{"title", "New Title"}}; // handler.write("modified.eps", mods); // return 0; // } // ===== end task-184 .EPS ===== // ===== task-185 .EPUB [C++] ===== #include #include #include #include #include #include #include #include // Assume tinyxml2 for XML parsing class EpubHandler { public: std::string filepath; std::map properties; // Simplified to strings for console print EpubHandler(const std::string& fp) : filepath(fp) {} void readProperties() { unzFile uf = unzOpen(filepath.c_str()); if (!uf) throw std::runtime_error("Cannot open file"); unz_global_info gi; unzGetGlobalInfo(uf, &gi); // Check first file unzGoToFirstFile(uf); char filename[256]; unz_file_info file_info; unzGetCurrentFileInfo(uf, &file_info, filename, sizeof(filename), NULL, 0, NULL, 0); if (std::string(filename) != "mimetype") throw std::runtime_error("mimetype not first file"); unzOpenCurrentFile(uf); std::string mimeContent(file_info.uncompressed_size, '\0'); unzReadCurrentFile(uf, &mimeContent[0], file_info.uncompressed_size); unzCloseCurrentFile(uf); mimeContent = mimeContent.substr(0, mimeContent.find_last_not_of(" \t\n\r\f\v") + 1); // Trim properties["file_extension"] = ".epub"; properties["mime_type"] = mimeContent; properties["container_format"] = "ZIP"; properties["mimetype_file_exists"] = "true"; properties["mimetype_file_content"] = mimeContent; properties["mimetype_file_compression"] = (file_info.compression_method == 0 ? "uncompressed" : "compressed"); properties["mimetype_file_extra_fields"] = (file_info.extrafield_size > 0 ? "true" : "false"); if (properties["mime_type"] != "application/epub+zip") throw std::runtime_error("Invalid MIME type"); // Find container.xml if (unzLocateFile(uf, "META-INF/container.xml", 0) != UNZ_OK) throw std::runtime_error("Missing container.xml"); unzGetCurrentFileInfo(uf, &file_info, NULL, 0, NULL, 0, NULL, 0); unzOpenCurrentFile(uf); std::string containerContent(file_info.uncompressed_size, '\0'); unzReadCurrentFile(uf, &containerContent[0], file_info.uncompressed_size); unzCloseCurrentFile(uf); tinyxml2::XMLDocument doc; doc.Parse(containerContent.c_str()); tinyxml2::XMLElement* root = doc.FirstChildElement("container"); properties["container_version"] = root ? root->Attribute("version") : ""; // Rootfiles (simplified to count or list as string) std::string rootfilesStr; tinyxml2::XMLElement* rf = root ? root->FirstChildElement("rootfiles")->FirstChildElement("rootfile") : nullptr; while (rf) { rootfilesStr += std::string(rf->Attribute("full-path")) + " (" + rf->Attribute("media-type") + "); "; rf = rf->NextSiblingElement("rootfile"); } properties["rootfiles"] = rootfilesStr; properties["signatures_xml"] = (unzLocateFile(uf, "META-INF/signatures.xml", 0) == UNZ_OK ? "true" : "false"); properties["encryption_xml"] = (unzLocateFile(uf, "META-INF/encryption.xml", 0) == UNZ_OK ? "true" : "false"); properties["metadata_xml"] = (unzLocateFile(uf, "META-INF/metadata.xml", 0) == UNZ_OK ? "true" : "false"); properties["rights_xml"] = (unzLocateFile(uf, "META-INF/rights.xml", 0) == UNZ_OK ? "true" : "false"); properties["manifest_xml"] = (unzLocateFile(uf, "META-INF/manifest.xml", 0) == UNZ_OK ? "true" : "false"); unzClose(uf); } void printProperties() { for (const auto& kv : properties) { std::cout << kv.first << ": " << kv.second << std::endl; } } void writeProperties(const std::map& newProps, const std::string& outputPath) { // Simplified: copy file, update mimetype and container.xml std::ifstream in(filepath, std::ios::binary); std::ofstream out(outputPath, std::ios::binary); out << in.rdbuf(); // Copy original // For actual write, would need to unzip, modify, rezip - complex, omitted for brevity // Use zipOpen, add mimetype first, add container, copy others // ... } }; // Example usage: // int main() { // try { // EpubHandler handler("example.epub"); // handler.readProperties(); // handler.printProperties(); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-185 .EPUB ===== // ===== task-186 .ERL [C++] ===== #include #include #include class ERLFile { private: std::string filepath; std::vector magic; std::vector logData; public: ERLFile(const std::string& fp) : filepath(fp), magic(4) {} void readAndDecode() { std::ifstream file(filepath, std::ios::binary); if (file) { file.read(reinterpret_cast(magic.data()), 4); logData = std::vector((std::istreambuf_iterator(file)), std::istreambuf_iterator()); } } void printProperties() { if (magic[0] == 0x00 && magic[1] == 0xFC && magic[2] == 0xCC && magic[3] == 0x00) { std::cout << "Magic number: 00 FC CC 00" << std::endl; std::cout << "Log data size: " << logData.size() << " bytes" << std::endl; } else { std::cout << "Invalid .ERL file format." << std::endl; } } void write(const std::string& newFilepath, const std::vector& newLogData = {}) { std::ofstream file(newFilepath, std::ios::binary); if (file) { unsigned char header[] = {0x00, 0xFC, 0xCC, 0x00}; file.write(reinterpret_cast(header), 4); file.write(reinterpret_cast(newLogData.data()), newLogData.size()); } } }; // Example usage: // int main() { // ERLFile erl("example.erl"); // erl.readAndDecode(); // erl.printProperties(); // std::vector sampleData = {'S', 'a', 'm', 'p', 'l', 'e'}; // erl.write("new.erl", sampleData); // return 0; // } // ===== end task-186 .ERL ===== // ===== task-187 .ES6 [C] ===== #include #include #include typedef struct { char *filepath; char *content; } ES6FileHandler; ES6FileHandler* create_es6_handler(const char *filepath) { ES6FileHandler *handler = (ES6FileHandler*)malloc(sizeof(ES6FileHandler)); handler->filepath = strdup(filepath); handler->content = NULL; return handler; } void open_and_read(ES6FileHandler *handler) { FILE *file = fopen(handler->filepath, "r"); if (file == NULL) { perror("Error opening file"); return; } fseek(file, 0, SEEK_END); long size = ftell(file); fseek(file, 0, SEEK_SET); handler->content = (char*)malloc(size + 1); fread(handler->content, 1, size, file); handler->content[size] = '\0'; fclose(file); printf("File read successfully (as text).\n"); } void decode(ES6FileHandler *handler) { // Placeholder: no decoding needed for text printf("No binary decoding required for text-based file.\n"); } void write_file(ES6FileHandler *handler, const char *new_content) { FILE *file = fopen(handler->filepath, "w"); if (file == NULL) { perror("Error opening file"); return; } fprintf(file, "%s", new_content); fclose(file); printf("File written successfully.\n"); } void print_properties(ES6FileHandler *handler) { const char *properties[] = { "Arrow functions", "Classes", "Enhanced object literals", "Template literals", "Destructuring assignment", "Default parameters", "Rest and spread operators", "Let and const declarations", "Iterators and for...of loops", "Generators", "Modules (import/export)", "Promises", "Symbols", "Map, Set, WeakMap, WeakSet", "Proxies", "Reflect API", "Tail call optimization", "New Math, Number, String, Array, and Object APIs", "Binary and octal literals", NULL }; printf("ES6 Properties/Features:\n"); for (int i = 0; properties[i] != NULL; i++) { printf("- %s\n", properties[i]); } } void destroy_es6_handler(ES6FileHandler *handler) { free(handler->filepath); free(handler->content); free(handler); } // Example usage: // int main() { // ES6FileHandler *handler = create_es6_handler("example.es6"); // open_and_read(handler); // decode(handler); // print_properties(handler); // write_file(handler, "new content"); // destroy_es6_handler(handler); // return 0; // } // ===== end task-187 .ES6 ===== // ===== task-188 .ESCPCB [C] ===== #include #include #include typedef struct { char* filepath; unsigned char* data; size_t size; } EscPcbHandler; void init(EscPcbHandler* handler, const char* filepath) { handler->filepath = strdup(filepath); handler->data = NULL; handler->size = 0; } void open_file(EscPcbHandler* handler) { if (strstr(handler->filepath, ".escpcb") == NULL && strstr(handler->filepath, ".ESCPCB") == NULL) { fprintf(stderr, "Invalid file extension. Must be .escpcb\n"); exit(1); } FILE* f = fopen(handler->filepath, "rb"); if (!f) { perror("Failed to open file"); exit(1); } fseek(f, 0, SEEK_END); handler->size = ftell(f); fseek(f, 0, SEEK_SET); handler->data = malloc(handler->size); fread(handler->data, 1, handler->size, f); fclose(f); printf("File opened: %s\n", handler->filepath); printf("File size: %zu bytes\n", handler->size); } void decode_and_print(EscPcbHandler* handler) { if (!handler->data) { fprintf(stderr, "File not opened\n"); exit(1); } printf("Hex Dump (first 1024 bytes):\n"); for (size_t i = 0; i < handler->size && i < 1024; i++) { printf("%02X ", handler->data[i]); if ((i + 1) % 16 == 0) printf("\n"); } printf("\nDecoded Properties: Unavailable (Proprietary format - no public specs)\n"); // Placeholder for decoding } void write_file(EscPcbHandler* handler, const char* output_path) { if (!handler->data) { fprintf(stderr, "No data to write\n"); exit(1); } FILE* f = fopen(output_path, "wb"); if (!f) { perror("Failed to write file"); exit(1); } fwrite(handler->data, 1, handler->size, f); fclose(f); printf("File written to: %s\n", output_path); } void cleanup(EscPcbHandler* handler) { free(handler->data); free(handler->filepath); } // Example usage: // int main() { // EscPcbHandler handler; // init(&handler, "example.escpcb"); // open_file(&handler); // decode_and_print(&handler); // write_file(&handler, "output.escpcb"); // cleanup(&handler); // return 0; // } // ===== end task-188 .ESCPCB ===== // ===== task-189 .ESCSCH [C] ===== #include #include #include typedef struct { char* filepath; uint8_t* data; size_t size; } ESCSCHHandler; ESCSCHHandler* create_handler(const char* filepath) { ESCSCHHandler* h = malloc(sizeof(ESCSCHHandler)); h->filepath = (char*)filepath; return h; } void read(ESCSCHHandler* h) { FILE* f = fopen(h->filepath, "rb"); if (!f) { perror("Error opening file"); return; } fseek(f, 0, SEEK_END); h->size = ftell(f); fseek(f, 0, SEEK_SET); h->data = malloc(h->size); fread(h->data, 1, h->size, f); fclose(f); // Hypothetical decoding (little-endian assumed) char magic[5] = {0}; snprintf(magic, 5, "%c%c%c%c", h->data[0], h->data[1], h->data[2], h->data[3]); uint32_t version = *(uint32_t*)(h->data + 4); uint32_t component_count = *(uint32_t*)(h->data + 8); printf("File Extension: .escsch\n"); printf("Magic: %s\n", magic); printf("Version: %u\n", version); printf("Component Count: %u\n", component_count); } void write(ESCSCHHandler* h) { FILE* f = fopen(h->filepath, "wb"); if (!f) { perror("Error opening file"); return; } uint8_t buffer[12] = {'E', 'S', 'C', 'S', 1, 0, 0, 0, 0, 0, 0, 0}; // Dummy data (LE) fwrite(buffer, 1, 12, f); fclose(f); printf("File written (hypothetical; no real specs available).\n"); } void destroy_handler(ESCSCHHandler* h) { free(h->data); free(h); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } ESCSCHHandler* handler = create_handler(argv[1]); read(handler); destroy_handler(handler); return 0; } // ===== end task-189 .ESCSCH ===== // ===== task-190 .ESD [C] ===== #include #include #include #include #include // Requires libxml2 for XML parsing typedef struct { uint64_t offset; uint64_t original_size; uint64_t size_flags; } ResourceEntry; typedef struct { char signature[8]; uint32_t header_size; uint32_t version; uint32_t flags; uint32_t compression_chunk_size; uint8_t guid[16]; uint16_t part_number; uint16_t total_parts; uint32_t image_count; ResourceEntry lookup_table; ResourceEntry xml_data; ResourceEntry boot_metadata; uint32_t boot_index; ResourceEntry integrity_table; } ESDHeader; typedef struct ESDFile { const char* filepath; ESDHeader header; // XML props would be parsed and stored in arrays/structs } ESDFile; void read_resource_entry(FILE* f, ResourceEntry* entry) { fread(&entry->offset, 8, 1, f); fread(&entry->original_size, 8, 1, f); fread(&entry->size_flags, 8, 1, f); } int open_and_decode(ESDFile* esd) { FILE* f = fopen(esd->filepath, "rb"); if (!f) return -1; fread(esd->header.signature, 8, 1, f); fread(&esd->header.header_size, 4, 1, f); fread(&esd->header.version, 4, 1, f); fread(&esd->header.flags, 4, 1, f); fread(&esd->header.compression_chunk_size, 4, 1, f); fread(esd->header.guid, 16, 1, f); fread(&esd->header.part_number, 2, 1, f); fread(&esd->header.total_parts, 2, 1, f); fread(&esd->header.image_count, 4, 1, f); read_resource_entry(f, &esd->header.lookup_table); read_resource_entry(f, &esd->header.xml_data); read_resource_entry(f, &esd->header.boot_metadata); fread(&esd->header.boot_index, 4, 1, f); read_resource_entry(f, &esd->header.integrity_table); // Read XML fseek(f, esd->header.xml_data.offset, SEEK_SET); uint64_t xml_size = esd->header.xml_data.size_flags & 0x7FFFFFFFFFFFFFFFULL; char* xml_buffer = malloc(xml_size + 2); // For null-termination fread(xml_buffer, xml_size, 1, f); xml_buffer[xml_size] = 0; xml_buffer[xml_size + 1] = 0; // UTF-16 null // Parse XML with libxml2 xmlDocPtr doc = xmlReadMemory(xml_buffer, xml_size, NULL, "UTF-16LE", 0); if (doc) { xmlNodePtr root = xmlDocGetRootElement(doc); // Traverse and print IMAGE nodes (implement printing logic) xmlFreeDoc(doc); } free(xml_buffer); fclose(f); return 0; } void print_properties(ESDFile* esd) { printf("Signature: %.8s\n", esd->header.signature); // ... (print all header fields) // Print XML props (from parsed doc) } int write_modified(ESDFile* esd, const char* new_filepath) { FILE* f_in = fopen(esd->filepath, "rb"); FILE* f_out = fopen(new_filepath, "wb"); if (!f_in || !f_out) return -1; char buf[4096]; size_t read; while ((read = fread(buf, 1, 4096, f_in)) > 0) { fwrite(buf, 1, read, f_out); } fclose(f_in); fclose(f_out); return 0; } // Usage: ESDFile esd = {"example.esd"}; open_and_decode(&esd); print_properties(&esd); write_modified(&esd, "modified.esd"); // ===== end task-190 .ESD ===== // ===== task-191 .ESF [C++] ===== #include #include #include #include #include #include class ESFHandler { private: std::string filepath; std::vector data; uint32_t magic; uint32_t zeros; uint32_t timestamp; uint32_t footerOffset; public: ESFHandler(const std::string& fp) : filepath(fp), zeros(0), timestamp(0) {} void read() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(reinterpret_cast(data.data()), size); decode(); } private: void decode() { size_t offset = 0; magic = *reinterpret_cast(&data[offset]); offset += 4; if (magic != 0xABCD) { zeros = *reinterpret_cast(&data[offset]); offset += 4; timestamp = *reinterpret_cast(&data[offset]); offset += 4; } footerOffset = *reinterpret_cast(&data[offset]); offset += 4; // Simplified node parsing std::cout << "Sample nodes:" << std::endl; for (int i = 0; i < 5 && offset < footerOffset; ++i) { uint8_t type = data[offset++]; uint16_t nameIndex = *reinterpret_cast(&data[offset]); offset += 2; uint8_t version = data[offset++]; std::string dataStr = ""; if (type == 0x01) { dataStr = (data[offset++] != 0) ? "true" : "false"; } else if (type == 0x04) { int32_t val = *reinterpret_cast(&data[offset]); offset += 4; dataStr = std::to_string(val); } else if (type == 0x0A) { float val = *reinterpret_cast(&data[offset]); offset += 4; dataStr = std::to_string(val); } else if (type == 0x0F) { uint16_t len = *reinterpret_cast(&data[offset]); offset += 2; dataStr = std::string(&data[offset], &data[offset] + len); offset += len; } std::cout << "Type: 0x" << std::hex << static_cast(type) << ", NameIndex: " << nameIndex << ", Version: " << static_cast(version) << ", Data: " << dataStr << std::endl; } } public: void printProperties() { std::cout << "Magic: 0x" << std::hex << magic << std::endl; std::cout << "Zeros: " << std::dec << zeros << std::endl; std::cout << "Timestamp: " << timestamp << std::endl; std::cout << "Footer Offset: " << footerOffset << std::endl; } void write(const std::string& newFilepath) { std::ofstream file(newFilepath, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); } }; // Example usage: // int main() { // ESFHandler handler("path/to/file.esf"); // handler.read(); // handler.printProperties(); // handler.write("new.esf"); // return 0; // } // ===== end task-191 .ESF ===== // ===== task-192 .ETL [C] ===== #include #include #include #include typedef struct { uint32_t bufferSize; uint32_t savedOffset; uint32_t currentOffset; int32_t referenceCount; int64_t timeStamp; uint32_t sequenceNumber; uint32_t clockType; int64_t frequency; uint16_t loggerId; uint8_t processorIndex; uint8_t alignment; // Padding uint32_t state; uint32_t offset; uint16_t bufferFlag; uint16_t bufferType; int64_t referenceTimeTime; int64_t referenceTimeFreq; } BufferHeader; typedef struct { BufferHeader* buffers; size_t numBuffers; } ETLFile; ETLFile* etl_open(const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); ETLFile* etl = malloc(sizeof(ETLFile)); etl->buffers = NULL; etl->numBuffers = 0; size_t position = 0; while (position < size) { if (size - position < 0x48) break; BufferHeader header; memcpy(&header, data + position, 0x48); if (header.bufferSize <= 0x48 || position + header.bufferSize > size) break; etl->buffers = realloc(etl->buffers, sizeof(BufferHeader) * (etl->numBuffers + 1)); etl->buffers[etl->numBuffers] = header; etl->numBuffers++; position += header.bufferSize; } free(data); return etl; } void etl_print_properties(ETLFile* etl) { for (size_t idx = 0; idx < etl->numBuffers; idx++) { BufferHeader* buf = &etl->buffers[idx]; printf("Buffer %zu:\n", idx + 1); printf(" BufferSize: %u\n", buf->bufferSize); printf(" SavedOffset: %u\n", buf->savedOffset); printf(" CurrentOffset: %u\n", buf->currentOffset); printf(" ReferenceCount: %d\n", buf->referenceCount); printf(" TimeStamp: %lld\n", (long long)buf->timeStamp); printf(" SequenceNumber: %u\n", buf->sequenceNumber); printf(" ClockType: %u\n", buf->clockType); printf(" Frequency: %lld\n", (long long)buf->frequency); printf(" LoggerId: %hu\n", buf->loggerId); printf(" ProcessorIndex: %u\n", buf->processorIndex); printf(" State: %u\n", buf->state); printf(" Offset: %u\n", buf->offset); printf(" BufferFlag: %hu\n", buf->bufferFlag); printf(" BufferType: %hu\n", buf->bufferType); printf(" ReferenceTime.Time: %lld\n", (long long)buf->referenceTimeTime); printf(" ReferenceTime.Freq: %lld\n", (long long)buf->referenceTimeFreq); printf("\n"); } } void etl_write(ETLFile* etl, const char* newFilename) { FILE* f = fopen(newFilename, "wb"); if (!f) return; for (size_t idx = 0; idx < etl->numBuffers; idx++) { BufferHeader* buf = &etl->buffers[idx]; fwrite(buf, 1, 0x48, f); // Pad with zeros for event data size_t padSize = buf->bufferSize - 0x48; uint8_t* pad = calloc(padSize, 1); fwrite(pad, 1, padSize, f); free(pad); } fclose(f); } void etl_close(ETLFile* etl) { free(etl->buffers); free(etl); } // Example usage: // int main() { // ETLFile* etl = etl_open("sample.etl"); // etl_print_properties(etl); // etl_write(etl, "new.etl"); // etl_close(etl); // return 0; // } // ===== end task-192 .ETL ===== // ===== task-193 .EU4 [C++] ===== #include #include #include #include #include #include class EU4FileHandler { private: std::string filepath; std::string content; bool isZip; std::vector properties = { "date", "save_game", "player", "displayed_country_name", "savegame_version", "dlc_enabled", "mod_enabled", "multi_player", "not_observer", "campaign_id", "campaign_length", "speed", "current_age", "map_area_data", "trade", "production_leader_tag", "tradegoods_total_produced", "change_price", "id", "dynasty", "rebel_faction", "great_powers", "empire", "active_trade_league", "catholic", "fired_events", "pending_events", "provinces", "countries", "active_advisors", "diplomacy", "active_war", "previous_war", "income_statistics", "nation_size_statistics", "score_statistics", "inflation_statistics", "expanded_dip_action_groups", "achievement_ok", "unit", "trade_company_manager", "tech_level_dates", "idea_dates", "ai" }; public: EU4FileHandler(const std::string& fp) : filepath(fp), content(""), isZip(false) {} void read() { std::ifstream file(filepath, std::ios::binary); std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); if (data.size() > 1 && data[0] == 'P' && data[1] == 'K') { // ZIP isZip = true; zip *z = zip_open(filepath.c_str(), 0, nullptr); if (z) { zip_file *zf = zip_fopen(z, "gamestate", 0); if (zf) { zip_stat_t stat; zip_stat(z, "gamestate", 0, &stat); content.resize(stat.size); zip_fread(zf, &content[0], stat.size); zip_fclose(zf); } zip_close(z); } } else { content = std::string(data.begin(), data.end()); } if (!content.empty() && content.substr(0, 6) != "EU4txt") { std::cout << "Unsupported binary format." << std::endl; content = ""; } } void printProperties() { if (content.empty()) { std::cout << "No content loaded." << std::endl; return; } for (const auto& prop : properties) { std::regex regex("^" + prop + "=(.*?(?=\\n\\w+=|$))", std::regex::multiline | std::regex::dotall); std::smatch match; if (std::regex_search(content, match, regex)) { std::cout << prop << "=" << match[1].str() << std::endl << std::endl; } else { std::cout << prop << ": Not found" << std::endl; } } } void write(const std::string& newDate = "1444.11.11") { // Example: update 'date' if (content.empty()) { std::cout << "No content to write." << std::endl; return; } std::regex dateRegex("date=\\d{4}\\.\\d{1,2}\\.\\d{1,2}"); content = std::regex_replace(content, dateRegex, "date=" + newDate, std::regex_constants::format_first_only); std::string outputPath = filepath + ".modified.eu4"; if (isZip) { zip *z = zip_open(outputPath.c_str(), ZIP_CREATE, nullptr); if (z) { zip_source *src = zip_source_buffer(z, content.c_str(), content.size(), 0); zip_file_add(z, "gamestate", src, ZIP_FL_OVERWRITE); zip_close(z); } } else { std::ofstream out(outputPath); out << content; } std::cout << "File written to " << outputPath << std::endl; } }; // Example usage: // int main() { // EU4FileHandler handler("example.eu4"); // handler.read(); // handler.printProperties(); // handler.write("1500.1.1"); // return 0; // } // ===== end task-193 .EU4 ===== // ===== task-194 .EVT [C] ===== #include #include #include #include struct EvtProperties { uint32_t header_size; char signature[5]; // 4 bytes + null terminator uint32_t major_version; uint32_t minor_version; uint32_t start_offset; uint32_t end_offset; uint32_t current_record_number; uint32_t oldest_record_number; uint32_t max_size; uint32_t flags; uint32_t retention; uint32_t end_header_size; }; void read_evt(const char* filename, struct EvtProperties* props) { FILE* f = fopen(filename, "rb"); if (!f) { perror("Error opening file"); exit(1); } uint8_t header[48]; fread(header, 1, 48, f); fclose(f); props->header_size = *(uint32_t*)(header + 0); strncpy(props->signature, (char*)(header + 4), 4); props->signature[4] = '\0'; props->major_version = *(uint32_t*)(header + 8); props->minor_version = *(uint32_t*)(header + 12); props->start_offset = *(uint32_t*)(header + 16); props->end_offset = *(uint32_t*)(header + 20); props->current_record_number = *(uint32_t*)(header + 24); props->oldest_record_number = *(uint32_t*)(header + 28); props->max_size = *(uint32_t*)(header + 32); props->flags = *(uint32_t*)(header + 36); props->retention = *(uint32_t*)(header + 40); props->end_header_size = *(uint32_t*)(header + 44); } void print_properties(const struct EvtProperties* props) { printf("Header Size: %u\n", props->header_size); printf("Signature: %s\n", props->signature); printf("Major Version: %u\n", props->major_version); printf("Minor Version: %u\n", props->minor_version); printf("Start Offset: %u\n", props->start_offset); printf("End Offset: %u\n", props->end_offset); printf("Current Record Number: %u\n", props->current_record_number); printf("Oldest Record Number: %u\n", props->oldest_record_number); printf("Max Size: %u\n", props->max_size); printf("Flags: %u\n", props->flags); printf("Retention: %u\n", props->retention); printf("End Header Size: %u\n", props->end_header_size); printf("Flags Details:\n"); printf(" - Dirty: %d\n", (props->flags & 1) != 0); printf(" - Wrap: %d\n", (props->flags & 2) != 0); printf(" - Log Full: %d\n", (props->flags & 4) != 0); printf(" - Archive: %d\n", (props->flags & 8) != 0); } void write_evt(const char* new_filename, const struct EvtProperties* props) { FILE* f = fopen(new_filename, "wb"); if (!f) { perror("Error opening file for writing"); exit(1); } uint8_t header[48] = {0}; *(uint32_t*)(header + 0) = props->header_size; strncpy((char*)(header + 4), props->signature, 4); *(uint32_t*)(header + 8) = props->major_version; *(uint32_t*)(header + 12) = props->minor_version; *(uint32_t*)(header + 16) = props->start_offset; *(uint32_t*)(header + 20) = props->end_offset; *(uint32_t*)(header + 24) = props->current_record_number; *(uint32_t*)(header + 28) = props->oldest_record_number; *(uint32_t*)(header + 32) = props->max_size; *(uint32_t*)(header + 36) = props->flags; *(uint32_t*)(header + 40) = props->retention; *(uint32_t*)(header + 44) = props->end_header_size; fwrite(header, 1, 48, f); fclose(f); // Note: This writes only the header; full implementation would append records. } // Example usage: // int main() { // struct EvtProperties props; // read_evt("sample.evt", &props); // print_properties(&props); // write_evt("new.evt", &props); // return 0; // } // ===== end task-194 .EVT ===== // ===== task-195 .EVTX [C] ===== #include #include #include #include typedef struct { char *filepath; uint8_t *data; size_t size; // Properties char file_magic[9]; uint64_t first_chunk_num; uint64_t next_record_num; uint32_t header_size; uint16_t minor_version; uint16_t major_version; uint16_t header_block_size; uint16_t chunk_count; uint32_t flags; uint32_t file_checksum; char chunk_magic[9]; uint64_t first_rec_log; uint64_t last_rec_log; uint64_t first_rec_file; uint64_t last_rec_file; uint32_t chunk_header_size; uint32_t last_rec_offset; uint32_t next_rec_offset; uint32_t chunk_checksum; } EvtxHandler; void evtx_read(EvtxHandler *handler) { FILE *f = fopen(handler->filepath, "rb"); fseek(f, 0, SEEK_END); handler->size = ftell(f); fseek(f, 0, SEEK_SET); handler->data = malloc(handler->size); fread(handler->data, 1, handler->size, f); fclose(f); evtx_decode_properties(handler); } void evtx_decode_properties(EvtxHandler *handler) { uint8_t *data = handler->data; size_t offset = 0; memcpy(handler->file_magic, data + offset, 8); handler->file_magic[8] = '\0'; offset += 8; memcpy(&handler->first_chunk_num, data + offset, 8); offset += 8; memcpy(&handler->next_record_num, data + offset, 8); offset += 8; memcpy(&handler->header_size, data + offset, 4); offset += 4; memcpy(&handler->minor_version, data + offset, 2); offset += 2; memcpy(&handler->major_version, data + offset, 2); offset += 2; memcpy(&handler->header_block_size, data + offset, 2); offset += 2; memcpy(&handler->chunk_count, data + offset, 2); offset += 86; memcpy(&handler->flags, data + offset, 4); offset += 4; memcpy(&handler->file_checksum, data + offset, 4); offset = 4096; memcpy(handler->chunk_magic, data + offset, 8); handler->chunk_magic[8] = '\0'; offset += 8; memcpy(&handler->first_rec_log, data + offset, 8); offset += 8; memcpy(&handler->last_rec_log, data + offset, 8); offset += 8; memcpy(&handler->first_rec_file, data + offset, 8); offset += 8; memcpy(&handler->last_rec_file, data + offset, 8); offset += 8; memcpy(&handler->chunk_header_size, data + offset, 4); offset += 4; memcpy(&handler->last_rec_offset, data + offset, 4); offset += 4; memcpy(&handler->next_rec_offset, data + offset, 4); offset += 76; memcpy(&handler->chunk_checksum, data + offset, 4); } void evtx_print_properties(EvtxHandler *handler) { printf("File Header Properties:\n"); printf("file_magic: %s\n", handler->file_magic); printf("first_chunk_num: %llu\n", handler->first_chunk_num); printf("next_record_num: %llu\n", handler->next_record_num); printf("header_size: %u\n", handler->header_size); printf("minor_version: %u\n", handler->minor_version); printf("major_version: %u\n", handler->major_version); printf("header_block_size: %u\n", handler->header_block_size); printf("chunk_count: %u\n", handler->chunk_count); printf("flags: %u\n", handler->flags); printf("file_checksum: %u\n", handler->file_checksum); printf("\nChunk Header Properties (First Chunk):\n"); printf("chunk_magic: %s\n", handler->chunk_magic); printf("first_rec_log: %llu\n", handler->first_rec_log); printf("last_rec_log: %llu\n", handler->last_rec_log); printf("first_rec_file: %llu\n", handler->first_rec_file); printf("last_rec_file: %llu\n", handler->last_rec_file); printf("chunk_header_size: %u\n", handler->chunk_header_size); printf("last_rec_offset: %u\n", handler->last_rec_offset); printf("next_rec_offset: %u\n", handler->next_rec_offset); printf("chunk_checksum: %u\n", handler->chunk_checksum); } void evtx_write(EvtxHandler *handler, char *new_filepath, uint32_t new_flags) { if (new_flags != 0) { // 0 means no update memcpy(handler->data + 120, &new_flags, 4); evtx_decode_properties(handler); } FILE *f = fopen(new_filepath, "wb"); fwrite(handler->data, 1, handler->size, f); fclose(f); } void evtx_free(EvtxHandler *handler) { free(handler->data); } // ===== end task-195 .EVTX ===== // ===== task-196 .EX [C] ===== #include #include #include #include #define MAX_LINE 1024 #define MAX_PROPERTIES 100 typedef struct { char *regions[MAX_PROPERTIES]; int region_count; char *groups[MAX_PROPERTIES]; int group_count; char *shapes[MAX_PROPERTIES]; int shape_count; // For fields, nodes, elements: use simplified arrays for demo; in production, use linked lists char *fields[MAX_PROPERTIES]; int field_count; char *nodes[MAX_PROPERTIES]; int node_count; char *elements[MAX_PROPERTIES]; int element_count; } EXProperties; typedef struct { char *filepath; EXProperties properties; } EXFileHandler; void initEXFileHandler(EXFileHandler *handler, char *filepath) { handler->filepath = strdup(filepath); memset(&handler->properties, 0, sizeof(EXProperties)); } void freeEXFileHandler(EXFileHandler *handler) { for (int i = 0; i < handler->properties.region_count; i++) free(handler->properties.regions[i]); for (int i = 0; i < handler->properties.group_count; i++) free(handler->properties.groups[i]); for (int i = 0; i < handler->properties.shape_count; i++) free(handler->properties.shapes[i]); for (int i = 0; i < handler->properties.field_count; i++) free(handler->properties.fields[i]); for (int i = 0; i < handler->properties.node_count; i++) free(handler->properties.nodes[i]); for (int i = 0; i < handler->properties.element_count; i++) free(handler->properties.elements[i]); free(handler->filepath); } void readAndDecode(EXFileHandler *handler) { FILE *file = fopen(handler->filepath, "r"); if (!file) return; char line[MAX_LINE]; char *current_region = NULL; char *current_group = NULL; char state[20] = "idle"; while (fgets(line, MAX_LINE, file)) { char *trimmed = line; while (isspace(*trimmed)) trimmed++; if (*trimmed == '\0' || *trimmed == '!') continue; char *end = trimmed + strlen(trimmed) - 1; while (end > trimmed && isspace(*end)) *end-- = '\0'; if (strstr(trimmed, "Region:") == trimmed) { current_region = strdup(trimmed + 7); handler->properties.regions[handler->properties.region_count++] = current_region; strcpy(state, "region"); } else if (strstr(trimmed, "Group name:") == trimmed) { current_group = strdup(trimmed + 11); handler->properties.groups[handler->properties.group_count++] = current_group; strcpy(state, "group"); } else if (strstr(trimmed, "Shape.") == trimmed) { char *dim_start = strstr(trimmed, "Dimension="); if (dim_start) { char *shape = strdup(dim_start + 10); handler->properties.shapes[handler->properties.shape_count++] = shape; } strcpy(state, "shape"); } else if (strstr(trimmed, "#Fields=") == trimmed) { char *field = strdup(trimmed); handler->properties.fields[handler->properties.field_count++] = field; strcpy(state, "fields"); } else if (strcmp(state, "fields") == 0 && isdigit(*trimmed)) { char *field = strdup(trimmed); handler->properties.fields[handler->properties.field_count++] = field; } else if (strstr(trimmed, "Node:") == trimmed) { char *node = strdup(trimmed); handler->properties.nodes[handler->properties.node_count++] = node; strcpy(state, "node_values"); } else if (strcmp(state, "node_values") == 0) { char *value = strdup(trimmed); handler->properties.nodes[handler->properties.node_count++] = value; } else if (strstr(trimmed, "Element:") == trimmed) { char *elem = strdup(trimmed); handler->properties.elements[handler->properties.element_count++] = elem; strcpy(state, "element"); } } fclose(file); } void printProperties(EXFileHandler *handler) { printf("{\n"); printf(" \"regions\": ["); for (int i = 0; i < handler->properties.region_count; i++) { printf("\"%s\"%s", handler->properties.regions[i], i < handler->properties.region_count - 1 ? ", " : ""); } printf("],\n"); // Similar for groups, shapes, fields, nodes, elements printf(" \"groups\": ["); for (int i = 0; i < handler->properties.group_count; i++) { printf("\"%s\"%s", handler->properties.groups[i], i < handler->properties.group_count - 1 ? ", " : ""); } printf("],\n"); printf(" \"shapes\": ["); for (int i = 0; i < handler->properties.shape_count; i++) { printf("\"%s\"%s", handler->properties.shapes[i], i < handler->properties.shape_count - 1 ? ", " : ""); } printf("],\n"); printf(" \"fields\": ["); for (int i = 0; i < handler->properties.field_count; i++) { printf("\"%s\"%s", handler->properties.fields[i], i < handler->properties.field_count - 1 ? ", " : ""); } printf("],\n"); printf(" \"nodes\": ["); for (int i = 0; i < handler->properties.node_count; i++) { printf("\"%s\"%s", handler->properties.nodes[i], i < handler->properties.node_count - 1 ? ", " : ""); } printf("],\n"); printf(" \"elements\": ["); for (int i = 0; i < handler->properties.element_count; i++) { printf("\"%s\"%s", handler->properties.elements[i], i < handler->properties.element_count - 1 ? ", " : ""); } printf("]\n"); printf("}\n"); } void write(EXFileHandler *handler, char *output_path) { FILE *file = fopen(output_path, "w"); if (!file) return; for (int i = 0; i < handler->properties.region_count; i++) { fprintf(file, "Region: %s\n", handler->properties.regions[i]); } for (int i = 0; i < handler->properties.group_count; i++) { fprintf(file, "Group name: %s\n", handler->properties.groups[i]); } for (int i = 0; i < handler->properties.shape_count; i++) { fprintf(file, "Shape. Dimension=%s\n", handler->properties.shapes[i]); } for (int i = 0; i < handler->properties.field_count; i++) { fprintf(file, "%s\n", handler->properties.fields[i]); } for (int i = 0; i < handler->properties.node_count; i++) { fprintf(file, "%s\n", handler->properties.nodes[i]); } for (int i = 0; i < handler->properties.element_count; i++) { fprintf(file, "%s\n", handler->properties.elements[i]); } fclose(file); } // Example usage: // int main() { // EXFileHandler handler; // initEXFileHandler(&handler, "example.exnode"); // readAndDecode(&handler); // printProperties(&handler); // write(&handler, "output.ex"); // freeEXFileHandler(&handler); // return 0; // } // ===== end task-196 .EX ===== // ===== task-197 .EXE [C++] ===== #include #include #include #include #include struct DosHeader { uint16_t e_magic; // Add all fields... int32_t e_lfanew; }; struct FileHeader { uint16_t Machine; uint16_t NumberOfSections; // Add all... }; struct OptionalHeader { uint16_t Magic; // Add all... }; struct SectionHeader { char Name[8]; uint32_t VirtualSize; // Add all... }; class ExeParser { private: std::string filename; std::vector data; DosHeader dos; uint32_t signature; FileHeader fileHeader; OptionalHeader optHeader; std::vector sections; public: ExeParser(const std::string& fn) : filename(fn) { readAndDecode(); } void readAndDecode() { std::ifstream file(filename, std::ios::binary | std::ios::ate); auto size = file.tellg(); data.resize(size); file.seekg(0); file.read(reinterpret_cast(data.data()), size); // Parse DOS memcpy(&dos, data.data(), sizeof(DosHeader)); // Signature memcpy(&signature, data.data() + dos.e_lfanew, 4); // File Header memcpy(&fileHeader, data.data() + dos.e_lfanew + 4, sizeof(FileHeader)); // Optional Header memcpy(&optHeader, data.data() + dos.e_lfanew + 24, sizeof(OptionalHeader)); // Adjust size // Sections size_t offset = dos.e_lfanew + 24 + fileHeader.SizeOfOptionalHeader; sections.resize(fileHeader.NumberOfSections); memcpy(sections.data(), data.data() + offset, fileHeader.NumberOfSections * sizeof(SectionHeader)); } void printProperties() { std::cout << "DOS Header: e_magic = " << dos.e_magic << std::endl; // Print all... std::cout << "Signature: " << signature << std::endl; std::cout << "File Header: Machine = " << fileHeader.Machine << std::endl; // Print all... for (const auto& sec : sections) { std::cout << "Section: Name = " << std::string(sec.Name, 8) << ", VirtualSize = " << sec.VirtualSize << std::endl; // Print all... } } void write(const std::string& newFilename) { // Example modification: change TimeDateStamp uint32_t* timestamp = reinterpret_cast(data.data() + dos.e_lfanew + 8); *timestamp = 0; // New value std::ofstream out(newFilename.empty() ? filename : newFilename, std::ios::binary); out.write(reinterpret_cast(data.data()), data.size()); } }; // Usage: ExeParser parser("example.exe"); parser.printProperties(); parser.write("modified.exe"); // ===== end task-197 .EXE ===== // ===== task-198 .EXP [C] ===== #include #include #include typedef struct { char *filename; } ExpFile; ExpFile* exp_new(const char *filename) { ExpFile* exp = malloc(sizeof(ExpFile)); exp->filename = strdup(filename); return exp; } void exp_read(ExpFile* exp) { FILE *f = fopen(exp->filename, "rb"); if (!f) return; fseek(f, 0, SEEK_END); long length = ftell(f); fseek(f, 0, SEEK_SET); char *data = malloc(length); fread(data, 1, length, f); fclose(f); exp_parse(exp, data, length); free(data); } void exp_parse(ExpFile* exp, char *data, long length) { int offset = 0; char signature[9] = {0}; strncpy(signature, data + offset, 8); offset += 8; if (strcmp(signature, "!\n") != 0) { printf("Invalid signature\n"); return; } printf("Signature: %s\n", signature); while (offset < length) { char name[17] = {0}; strncpy(name, data + offset, 16); offset += 16; char date[13] = {0}; strncpy(date, data + offset, 12); offset += 12; char userId[7] = {0}; strncpy(userId, data + offset, 6); offset += 6; char groupId[7] = {0}; strncpy(groupId, data + offset, 6); offset += 6; char mode[9] = {0}; strncpy(mode, data + offset, 8); offset += 8; char sizeStr[11] = {0}; strncpy(sizeStr, data + offset, 10); int size = atoi(sizeStr); offset += 10; char endHeader[3] = {0}; strncpy(endHeader, data + offset, 2); offset += 2; printf("Member: %s, Date: %s, UserID: %s, GroupID: %s, Mode: %s, Size: %d\n", name, date, userId, groupId, mode, size); offset += size; if (size % 2 != 0) offset += 1; } } void exp_write(ExpFile* exp, const char *out_filename) { // Implement writing } void exp_print_properties(ExpFile* exp) { exp_read(exp); } void exp_free(ExpFile* exp) { free(exp->filename); free(exp); } // Usage // ExpFile* exp = exp_new("sample.exp"); // exp_print_properties(exp); // exp_free(exp); // ===== end task-198 .EXP ===== // ===== task-199 .EXR [C++] ===== #include #include #include #include #include #include #include class EXRHandler { private: std::vector data; size_t pos = 0; std::map attributes; // Value as string for simplicity uint8_t version; uint32_t flags; size_t headerEndPos; public: EXRHandler(const std::string& filename) { std::ifstream file(filename, std::ios::binary); if (!file) throw std::runtime_error("Cannot open file"); file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(reinterpret_cast(data.data()), size); parseHeader(); } void parseHeader() { uint32_t magic = *reinterpret_cast(&data[pos]); pos += 4; if (magic != 20000630) throw std::runtime_error("Not EXR"); version = data[pos]; pos += 1; flags = *reinterpret_cast(&data[pos]) & 0xFFFFFF; pos += 3; while (true) { std::string name = readNullTermString(); if (name.empty()) break; std::string attrType = readNullTermString(); uint32_t size = *reinterpret_cast(&data[pos]); pos += 4; std::string value = parseValueAsString(attrType, size); attributes[name] = value; pos += size; } headerEndPos = pos; } std::string readNullTermString() { std::string s; while (true) { uint8_t c = data[pos]; pos++; if (c == 0) break; s += static_cast(c); } return s; } std::string parseValueAsString(const std::string& attrType, uint32_t size) { // Basic parsers; return string rep if (attrType == "float") { float val = *reinterpret_cast(&data[pos]); return std::to_string(val); } else if (attrType == "int") { int32_t val = *reinterpret_cast(&data[pos]); return std::to_string(val); } // Add more as in others // Unknown: hex std::string hex; for (uint32_t i = 0; i < size; ++i) { char buf[3]; std::sprintf(buf, "%02x ", data[pos + i]); hex += buf; } return hex; } void printProperties() { for (const auto& kv : attributes) { std::cout << kv.first << ": " << kv.second << std::endl; } } void write(const std::string& filename) { std::ofstream file(filename, std::ios::binary); if (!file) throw std::runtime_error("Cannot write file"); file.write(reinterpret_cast(data.data()), data.size()); } }; // ===== end task-199 .EXR ===== // ===== task-200 .EXS [C++] ===== #include #include #include #include #include class ExsFileHandler { private: std::string filepath; std::map properties; public: ExsFileHandler(const std::string& filepath) : filepath(filepath) {} void openAndDecode() { std::ifstream file(filepath, std::ios::binary); if (!file.is_open()) { std::cout << "File not found." << std::endl; return; } std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); // Hypothetical header read (first 3 bytes) if (data.size() >= 3) { printf("Header bytes: %02X %02X %02X\n", static_cast(data[0]), static_cast(data[1]), static_cast(data[2])); } // TODO: Reverse-engineered parsing properties["instrument_name"] = "Parsed value (placeholder)"; properties["zones"] = "[]"; properties["groups"] = "[]"; // Add other properties } std::map readProperties() { return properties; } void writeProperties(const std::map& newProperties) { // Placeholder for writing std::cout << "Writing not implemented due to lack of specification." << std::endl; } void printProperties() { if (properties.empty()) { std::cout << "No properties decoded." << std::endl; return; } for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } }; int main() { ExsFileHandler handler("example.exs"); handler.openAndDecode(); handler.printProperties(); return 0; } // ===== end task-200 .EXS ===== // ===== task-201 .F [C] ===== #include #include #include #include #include #include #include #define MAX_LINES 10000 #define LINE_LENGTH 73 // 72 + null terminator struct FFileHandler { char* filepath; char** content; int line_count; }; struct FFileHandler* createFFileHandler(const char* filepath) { struct FFileHandler* handler = malloc(sizeof(struct FFileHandler)); handler->filepath = strdup(filepath); handler->content = NULL; handler->line_count = 0; return handler; } void readAndDecode(struct FFileHandler* handler) { FILE* f = fopen(handler->filepath, "r"); if (!f) { perror("Error opening file"); return; } handler->content = malloc(MAX_LINES * sizeof(char*)); char line[LINE_LENGTH]; while (fgets(line, LINE_LENGTH, f) && handler->line_count < MAX_LINES) { handler->content[handler->line_count] = strdup(line); handler->line_count++; } fclose(f); } void printProperties(const struct FFileHandler* handler) { struct stat st; if (stat(handler->filepath, &st) != 0) { perror("stat failed"); return; } struct passwd* pw = getpwuid(st.st_uid); struct group* gr = getgrgid(st.st_gid); printf("File name: %s\n", handler->filepath); printf("File size: %ld bytes\n", (long)st.st_size); printf("Last modified: %s", ctime(&st.st_mtime)); printf("Permissions: %o\n", st.st_mode & 0777); printf("Owner: %s\n", pw ? pw->pw_name : "unknown"); printf("Group: %s\n", gr ? gr->gr_name : "unknown"); for (int i = 0; i < handler->line_count; i++) { char trimmed[73]; strncpy(trimmed, handler->content[i], 72); trimmed[72] = '\0'; char col1 = trimmed[0]; char label_str[6]; strncpy(label_str, trimmed, 5); label_str[5] = '\0'; char* label = strtrim(label_str); // Assume strtrim function to trim spaces if (strlen(label) == 0) label = "none"; char continuation = trimmed[5]; char* statement = strtrim(trimmed + 6); int is_comment = (toupper(col1) == 'C' || col1 == '*' || col1 == '!'); printf("Line %d:\n", i + 1); printf(" Is comment: %d\n", is_comment); printf(" Label: %s\n", label); printf(" Continuation: %c\n", continuation != ' ' ? continuation : "none"); printf(" Statement: %s\n", statement ? statement : ""); } } void write(const struct FFileHandler* handler, const char* new_filepath) { FILE* f = fopen(new_filepath, "w"); if (!f) { perror("Error opening file for write"); return; } for (int i = 0; i < handler->line_count; i++) { fputs(handler->content[i], f); } fclose(f); } void destroyFFileHandler(struct FFileHandler* handler) { for (int i = 0; i < handler->line_count; i++) { free(handler->content[i]); } free(handler->content); free(handler->filepath); free(handler); } // Note: Implement strtrim or use string library for trimming. // Example usage: // int main() { // struct FFileHandler* handler = createFFileHandler("example.F"); // readAndDecode(handler); // printProperties(handler); // write(handler, "new_example.F"); // destroyFFileHandler(handler); // return 0; // } // ===== end task-201 .F ===== // ===== task-203 .F03 [C++] ===== #include #include #include #include #include #include class F03Parser { private: std::string filename; std::map properties; public: F03Parser(const std::string& fn) : filename(fn) { read(); } void read() { std::ifstream file(filename); if (!file) { std::cerr << "Error opening file" << std::endl; return; } std::string line; std::string currentSection; while (std::getline(file, line)) { line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); if (line.find("Flow Title=") == 0) { properties["Flow Title"] = line.substr(11); } else if (line.find("Program Version=") == 0) { properties["Program Version"] = std::stof(line.substr(16)); } else if (line.find("Number of Profiles=") == 0) { properties["Number of Profiles"] = std::stoi(line.substr(19)); } else if (line.find("Profile Names=") == 0) { std::vector names; std::string s = line.substr(14); std::stringstream ss(s); std::string name; while (std::getline(ss, name, ',')) { names.push_back(name); } properties["Profile Names"] = names; } else if (line.find("Boundary for River:") == 0) { auto it = properties.find("Boundary Conditions"); std::vector bcs; if (it != properties.end()) bcs = std::any_cast>(it->second); bcs.push_back(line); properties["Boundary Conditions"] = bcs; } else if (line.find("River Rch & RM=") == 0) { currentSection = line; } else if (line.find("Flow=") == 0) { auto it = properties.find("Flow Data"); std::vector> flows; if (it != properties.end()) flows = std::any_cast>>(it->second); std::map fd; fd["location"] = currentSection; std::vector flowList; std::string s = line.substr(5); std::stringstream ss(s); std::string f; while (std::getline(ss, f, ',')) { flowList.push_back(std::stof(f)); } fd["flows"] = flowList; flows.push_back(fd); properties["Flow Data"] = flows; } else if (line.find("Interpolation Mode=") == 0) { properties["Interpolation Mode"] = std::stoi(line.substr(19)); } else if (line.find("UNITS=") == 0) { properties["Units"] = line.substr(6); } else if (line.find("SA Elevation=") == 0) { auto it = properties.find("Storage Area Elevations"); std::vector> sas; if (it != properties.end()) sas = std::any_cast>>(it->second); std::vector eleList; std::string s = line.substr(13); std::stringstream ss(s); std::string e; while (std::getline(ss, e, ',')) { eleList.push_back(std::stof(e)); } sas.push_back(eleList); properties["Storage Area Elevations"] = sas; } else if (line.find("Inline Structure Outlet TS Flows=") == 0) { auto it = properties.find("Inline Structure Outlet TS Flows"); std::vector> ts; if (it != properties.end()) ts = std::any_cast>>(it->second); std::vector tsList; std::string s = line.substr(33); std::stringstream ss(s); std::string t; while (std::getline(ss, t, ',')) { tsList.push_back(std::stof(t)); } ts.push_back(tsList); properties["Inline Structure Outlet TS Flows"] = ts; } } file.close(); } void printProperties() { // Printing the map requires handling different types; for simplicity, implement as needed std::cout << "Properties:" << std::endl; for (const auto& p : properties) { std::cout << p.first << ": "; // Add type checking and printing for each type // For example: if (p.first == "Flow Title" || p.first == "Units") { std::cout << std::any_cast(p.second) << std::endl; } else if (p.first == "Program Version") { std::cout << std::any_cast(p.second) << std::endl; } else if (p.first == "Number of Profiles" || p.first == "Interpolation Mode") { std::cout << std::any_cast(p.second) << std::endl; } else if (p.first == "Profile Names" || p.first == "Boundary Conditions") { auto list = std::any_cast>(p.second); for (const auto& item : list) std::cout << item << " "; std::cout << std::endl; } else if (p.first == "Flow Data") { auto flows = std::any_cast>>(p.second); for (const auto& fd : flows) { std::cout << std::any_cast(fd.at("location")) << " flows: "; auto flowList = std::any_cast>(fd.at("flows")); for (float f : flowList) std::cout << f << " "; std::cout << std::endl; } } // Add similar for other lists // Note: Complete implementation for all types as required } } void write(const std::string& newFilename = "") { std::string outFn = newFilename.empty() ? filename : newFilename; std::ofstream file(outFn); if (!file) { std::cerr << "Error opening file for writing" << std::endl; return; } if (properties.count("Flow Title")) file << "Flow Title=" << std::any_cast(properties["Flow Title"]) << "\n"; if (properties.count("Program Version")) file << "Program Version=" << std::any_cast(properties["Program Version"]) << "\n"; if (properties.count("Number of Profiles")) file << "Number of Profiles=" << std::any_cast(properties["Number of Profiles"]) << "\n"; if (properties.count("Profile Names")) { auto names = std::any_cast>(properties["Profile Names"]); file << "Profile Names="; for (size_t i = 0; i < names.size(); ++i) { file << names[i]; if (i < names.size() - 1) file << ","; } file << "\n"; } if (properties.count("Boundary Conditions")) { auto bcs = std::any_cast>(properties["Boundary Conditions"]); for (const auto& bc : bcs) file << bc << "\n"; } if (properties.count("Flow Data")) { auto flows = std::any_cast>>(properties["Flow Data"]); for (const auto& fd : flows) { file << std::any_cast(fd.at("location")) << "\n"; file << "Flow="; auto flowList = std::any_cast>(fd.at("flows")); for (size_t i = 0; i < flowList.size(); ++i) { file << flowList[i]; if (i < flowList.size() - 1) file << ","; } file << "\n"; } } if (properties.count("Interpolation Mode")) file << "Interpolation Mode=" << std::any_cast(properties["Interpolation Mode"]) << "\n"; if (properties.count("Units")) file << "UNITS=" << std::any_cast(properties["Units"]) << "\n"; if (properties.count("Storage Area Elevations")) { auto sas = std::any_cast>>(properties["Storage Area Elevations"]); for (const auto& sa : sas) { file << "SA Elevation="; for (size_t i = 0; i < sa.size(); ++i) { file << sa[i]; if (i < sa.size() - 1) file << ","; } file << "\n"; } } if (properties.count("Inline Structure Outlet TS Flows")) { auto ts = std::any_cast>>(properties["Inline Structure Outlet TS Flows"]); for (const auto& t : ts) { file << "Inline Structure Outlet TS Flows="; for (size_t i = 0; i < t.size(); ++i) { file << t[i]; if (i < t.size() - 1) file << ","; } file << "\n"; } } file.close(); } }; // Example usage: // int main() { // F03Parser parser("example.f03"); // parser.printProperties(); // parser.write("output.f03"); // return 0; // } // ===== end task-203 .F03 ===== // ===== task-205 .F18 [C] ===== #include #include #include #include #include #include #include typedef struct { char *filepath; char *content; } F18FileHandler; F18FileHandler* create_handler(const char *filepath) { F18FileHandler *handler = malloc(sizeof(F18FileHandler)); handler->filepath = strdup(filepath); handler->content = NULL; return handler; } void destroy_handler(F18FileHandler *handler) { free(handler->filepath); free(handler->content); free(handler); } char* open_and_read(F18FileHandler *handler) { FILE *f = fopen(handler->filepath, "r"); if (!f) return NULL; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); handler->content = malloc(size + 1); fread(handler->content, 1, size, f); handler->content[size] = '\0'; fclose(f); return handler->content; } void write_file(F18FileHandler *handler, const char *new_content) { FILE *f = fopen(handler->filepath, "w"); if (f) { fprintf(f, "%s", new_content); fclose(f); free(handler->content); handler->content = strdup(new_content); } } void print_properties(const F18FileHandler *handler) { struct stat st; if (stat(handler->filepath, &st) == 0) { printf("File name: %s\n", strrchr(handler->filepath, '/') ? strrchr(handler->filepath, '/') + 1 : handler->filepath); printf("File path: %s\n", handler->filepath); printf("File size: %ld\n", st.st_size); printf("Creation time: %s", ctime(&st.st_ctime)); printf("Modification time: %s", ctime(&st.st_mtime)); printf("Access time: %s", ctime(&st.st_atime)); printf("Permissions: %o\n", st.st_mode & 0777); printf("Owner user ID: %d\n", st.st_uid); printf("Group ID: %d\n", st.st_gid); printf("Inode number: %ld\n", st.st_ino); printf("File type: %s\n", S_ISREG(st.st_mode) ? "regular file" : "other"); } } // Example usage: // int main() { // F18FileHandler *handler = create_handler("example.f18"); // open_and_read(handler); // print_properties(handler); // write_file(handler, "New Fortran code"); // destroy_handler(handler); // return 0; // } // ===== end task-205 .F18 ===== // ===== task-206 .F4 [C] ===== #include #include #include #define MAX_LINES 1000 #define LINE_LEN 81 // 80 chars + null terminator typedef struct { char filepath[256]; char lines[MAX_LINES][LINE_LEN]; int line_count; } F4FileHandler; void init_f4_handler(F4FileHandler *handler, const char *filepath) { strncpy(handler->filepath, filepath, 255); handler->line_count = 0; } void read_and_decode(F4FileHandler *handler) { FILE *fp = fopen(handler->filepath, "r"); if (!fp) { perror("Error opening file"); return; } while (fgets(handler->lines[handler->line_count], LINE_LEN, fp) && handler->line_count < MAX_LINES) { handler->line_count++; } fclose(fp); printf("Decoded properties for %s:\n", handler->filepath); for (int idx = 0; idx < handler->line_count; idx++) { char padded[LINE_LEN]; strncpy(padded, handler->lines[idx], LINE_LEN - 1); padded[LINE_LEN - 1] = '\0'; int len = strlen(padded); memset(padded + len, ' ', LINE_LEN - 1 - len); char col1 = padded[0]; int is_comment = (col1 == 'C' || col1 == '*'); const char *line_type = is_comment ? "Comment" : "Statement"; char label[6] = {0}; strncpy(label, padded, 5); char *trim_label = strtok(label, " "); const char *final_label = is_comment ? "N/A" : (trim_label ? trim_label : "None"); char continuation = padded[5]; const char *cont_str = (continuation != ' ') ? &continuation : "None"; // Single char, but as string char statement[67] = {0}; strncpy(statement, padded + 6, 66); char *trim_stmt = strtok(statement, "\0 "); // Trim trailing spaces char id[9] = {0}; strncpy(id, padded + 72, 8); char *trim_id = strtok(id, " "); const char *final_id = trim_id ? trim_id : "None"; printf("Line %d:\n", idx + 1); printf(" - Line Type: %s\n", line_type); printf(" - Label: %s\n", final_label); printf(" - Continuation Indicator: %s\n", cont_str); // Prints char or "None" printf(" - Statement Body: %s\n", trim_stmt ? trim_stmt : ""); printf(" - Identification: %s\n", final_id); printf("\n"); } } void write_f4(F4FileHandler *handler, const char *output_path, const char **properties_list, int prop_count) { // properties_list is array of strings like "Statement|10| |PRINT *, \"Hello\"|SEQ001" FILE *fp = fopen(output_path, "w"); if (!fp) { perror("Error opening file"); return; } for (int i = 0; i < prop_count; i++) { char line_type[10], label[6], continuation[2], statement[67], id[9]; sscanf(properties_list[i], "%[^|]|%[^|]|%[^|]|%[^|]|%s", line_type, label, continuation, statement, id); char line[81]; if (strcmp(line_type, "Comment") == 0) { snprintf(line, 81, "C %s%-66s%8s", continuation, statement, id); } else { snprintf(line, 81, "%5s%s%-66s%8s", label, continuation, statement, id); } fprintf(fp, "%s\n", line); } fclose(fp); printf("Written to %s\n", output_path); } // Example usage: // F4FileHandler handler; // init_f4_handler(&handler, "example.F4"); // read_and_decode(&handler); // const char *props[] = {"Statement|10| |PRINT *, \"Hello\"|SEQ001"}; // write_f4(&handler, "output.F4", props, 1); // ===== end task-206 .F4 ===== // ===== task-207 .F4V [C++] ===== #include #include #include #include #include #include #include // For big-endian conversions if needed class F4VParser { private: std::string filename; std::vector data; std::map>> properties; public: F4VParser(const std::string& fn) : filename(fn) {} void read() { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) { std::cerr << "Cannot open file" << std::endl; return; } auto size = file.tellg(); data.resize(size); file.seekg(0); file.read(reinterpret_cast(data.data()), size); decode(); } void decode() { size_t offset = 0; while (offset < data.size()) { size_t boxStart = offset; uint32_t size = be32toh(*reinterpret_cast(&data[offset])); offset += 4; std::string type(reinterpret_cast(&data[offset]), 4); offset += 4; uint64_t extendedSize = 0; if (size == 1) { extendedSize = be64toh(*reinterpret_cast(&data[offset])); offset += 8; size = extendedSize; } else if (size == 0) { size = data.size() - boxStart; } auto& props = properties[type]; std::map prop; prop["size"] = size; props.push_back(prop); size_t boxOffset = offset; if (type == "ftyp") { std::string major(reinterpret_cast(&data[boxOffset]), 4); uint32_t minor = be32toh(*reinterpret_cast(&data[boxOffset + 4])); props.back()["minor"] = minor; // compat similar, skipped for brevity } else if (type == "mvhd") { uint8_t version = data[boxOffset]; size_t localOffset = boxOffset + 4; uint64_t creation = (version == 1) ? be64toh(*reinterpret_cast(&data[localOffset])) : be32toh(*reinterpret_cast(&data[localOffset])); localOffset += (version == 1) ? 8 : 4; uint64_t mod = (version == 1) ? be64toh(*reinterpret_cast(&data[localOffset])) : be32toh(*reinterpret_cast(&data[localOffset])); localOffset += (version == 1) ? 8 : 4; uint32_t timescale = be32toh(*reinterpret_cast(&data[localOffset])); localOffset += 4; uint64_t duration = (version == 1) ? be64toh(*reinterpret_cast(&data[localOffset])) : be32toh(*reinterpret_cast(&data[localOffset])); props.back()["version"] = version; props.back()["creation"] = creation; props.back()["mod"] = mod; props.back()["timescale"] = timescale; props.back()["duration"] = duration; } // Add for other boxes offset = boxStart + size; } } void printProperties() { for (const auto& [type, props] : properties) { for (const auto& p : props) { std::cout << "Box " << type << ": "; for (const auto& [k, v] : p) { std::cout << k << "=" << v << " "; } std::cout << std::endl; } } } void write(const std::string& outputFilename) { if (data.empty()) { std::cerr << "No data to write" << std::endl; return; } std::ofstream file(outputFilename, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); } }; // Example usage: // int main() { // F4VParser parser("sample.f4v"); // parser.read(); // parser.printProperties(); // parser.write("output.f4v"); // return 0; // } // ===== end task-207 .F4V ===== // ===== task-208 .F77 [C++] ===== #include #include #include #include #include struct F77LineProperties { bool isComment; std::string label; bool isContinuation; std::string statement; std::string identification; }; class F77FileHandler { private: std::string filepath; std::vector lines; std::vector parsedLines; public: F77FileHandler(const std::string& filepath) : filepath(filepath) {} void readAndDecode() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file: " << filepath << std::endl; return; } std::string line; while (std::getline(file, line)) { lines.push_back(line); } file.close(); for (const auto& line : lines) { std::string paddedLine = line; paddedLine.resize(80, ' '); char col1 = paddedLine[0]; std::string cols1_5 = paddedLine.substr(0, 5); cols1_5.erase(0, cols1_5.find_first_not_of(' ')); cols1_5.erase(cols1_5.find_last_not_of(' ') + 1); char col6 = paddedLine[5]; std::string cols7_72 = paddedLine.substr(6, 66); cols7_72.erase(0, cols7_72.find_first_not_of(' ')); cols7_72.erase(cols7_72.find_last_not_of(' ') + 1); std::string cols73_80 = paddedLine.substr(72, 8); cols73_80.erase(0, cols73_80.find_first_not_of(' ')); cols73_80.erase(cols73_80.find_last_not_of(' ') + 1); bool isComment = (col1 == 'C' || col1 == '*') || paddedLine.find_first_not_of(' ') == std::string::npos; std::string label = (cols1_5.find_first_not_of("0123456789") == std::string::npos && !cols1_5.empty()) ? cols1_5 : "none"; bool isContinuation = (col6 != ' ' && col6 != '0') && !isComment; std::string statement = cols7_72.empty() ? "none" : cols7_72; std::string identification = cols73_80.empty() ? "none" : cols73_80; parsedLines.push_back({isComment, label, isContinuation, statement, identification}); } } void printProperties() { if (parsedLines.empty()) { readAndDecode(); } for (size_t i = 0; i < parsedLines.size(); ++i) { const auto& props = parsedLines[i]; std::cout << "Line " << (i + 1) << ":" << std::endl; std::cout << "- Is Comment: " << (props.isComment ? "yes" : "no") << std::endl; std::cout << "- Label: " << props.label << std::endl; std::cout << "- Is Continuation: " << (props.isContinuation ? "yes" : "no") << std::endl; std::cout << "- Statement: " << props.statement << std::endl; std::cout << "- Identification (cols 73-80): " << props.identification << std::endl; std::cout << std::endl; } } void write(const std::string& newFilepath) { if (lines.empty()) { std::cerr << "No data to write. Read a file first." << std::endl; return; } std::ofstream outFile(newFilepath); if (!outFile.is_open()) { std::cerr << "Error opening output file: " << newFilepath << std::endl; return; } for (const auto& line : lines) { outFile << line << std::endl; } outFile.close(); } }; // Example usage: // int main() { // F77FileHandler handler("example.F77"); // handler.readAndDecode(); // handler.printProperties(); // handler.write("output.F77"); // return 0; // } // ===== end task-208 .F77 ===== // ===== task-209 .F90 [C++] ===== #include #include #include #include #include #include // For getuid, etc., if needed class F90File { private: std::string filepath; struct stat statInfo; std::string content; public: F90File(const std::string& fp) : filepath(fp) { if (stat(filepath.c_str(), &statInfo) != 0) { throw std::runtime_error("Failed to get file stats"); } content = readContent(); } std::string readContent() { std::ifstream file(filepath); if (!file) { throw std::runtime_error("Failed to open file for reading"); } return std::string((std::istreambuf_iterator(file)), std::istreambuf_iterator()); } void writeContent(const std::string& newContent) { std::ofstream file(filepath); if (!file) { throw std::runtime_error("Failed to open file for writing"); } file << newContent; // Update stat after write if (stat(filepath.c_str(), &statInfo) != 0) { throw std::runtime_error("Failed to get updated file stats"); } } void printProperties() { std::cout << "File name: " << filepath.substr(filepath.find_last_of("/\\") + 1) << std::endl; std::cout << "File size: " << statInfo.st_size << " bytes" << std::endl; std::cout << "Creation timestamp: " << std::ctime(&statInfo.st_ctime); // On Unix: change time std::cout << "Last modification timestamp: " << std::ctime(&statInfo.st_mtime); std::cout << "Last access timestamp: " << std::ctime(&statInfo.st_atime); std::cout << "Permissions: " << std::oct << (statInfo.st_mode & 0777) << std::dec << std::endl; std::cout << "Owner user ID: " << statInfo.st_uid << std::endl; std::cout << "Owner group ID: " << statInfo.st_gid << std::endl; std::cout << "MIME type: text/x-fortran (assumed; no standard FS storage)" << std::endl; } }; // Example usage: // int main() { // try { // F90File f("example.f90"); // f.printProperties(); // f.writeContent("new content"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-209 .F90 ===== // ===== task-211 .FA [C++] ===== #include #include #include #include #include #include class FASTAHandler { private: std::string filepath; std::vector> sequences; std::map properties; public: FASTAHandler(const std::string& fp) : filepath(fp) {} void readAndDecode() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file: " << filepath << std::endl; return; } std::string line, currentSeqID, currentDesc, currentSequence; while (std::getline(file, line)) { line.erase(0, line.find_first_not_of(" \t")); // Trim leading whitespace line.erase(line.find_last_not_of(" \t") + 1); // Trim trailing if (line.empty()) continue; if (line[0] == '>') { if (!currentSeqID.empty()) { addSequence(currentSeqID, currentDesc, currentSequence); } size_t spacePos = line.find(' ', 1); if (spacePos != std::string::npos) { currentSeqID = line.substr(1, spacePos - 1); currentDesc = line.substr(spacePos + 1); } else { currentSeqID = line.substr(1); currentDesc = ""; } currentSequence = ""; } else { currentSequence += line; } } if (!currentSeqID.empty()) { addSequence(currentSeqID, currentDesc, currentSequence); } file.close(); // Set properties properties["text_based"] = "true"; properties["multi_sequence"] = (sequences.size() > 1 ? "true" : "false"); properties["num_sequences"] = std::to_string(sequences.size()); properties["whitespace_tolerance"] = "true"; properties["case_sensitivity"] = "flexible"; properties["line_length_flexibility"] = "true"; properties["no_header_footer"] = "true"; } private: void addSequence(const std::string& id, const std::string& desc, const std::string& seq) { std::map seqMap; seqMap["seqID"] = id; seqMap["description"] = desc; seqMap["sequence"] = seq; seqMap["length"] = std::to_string(seq.length()); std::string seqUpper = seq; std::transform(seqUpper.begin(), seqUpper.end(), seqUpper.begin(), ::toupper); if (std::regex_match(seqUpper, std::regex("^[ACGTN-]+$"))) { seqMap["alphabet"] = "DNA/RNA"; } else if (std::regex_match(seqUpper, std::regex("^[ACDEFGHIKLMNPQRSTVWY*-]+$"))) { seqMap["alphabet"] = "Protein"; } else { seqMap["alphabet"] = "unknown"; } sequences.push_back(seqMap); } public: void printProperties() const { if (properties.empty()) { std::cout << "No properties loaded. Call readAndDecode() first." << std::endl; return; } std::cout << "File Properties:" << std::endl; std::cout << "- Text-based structure: " << properties.at("text_based") << std::endl; std::cout << "- Multi-sequence support: " << properties.at("multi_sequence") << std::endl; std::cout << "- Number of sequences: " << properties.at("num_sequences") << std::endl; std::cout << "- Whitespace tolerance: " << properties.at("whitespace_tolerance") << std::endl; std::cout << "- Case sensitivity: " << properties.at("case_sensitivity") << std::endl; std::cout << "- Line length flexibility: " << properties.at("line_length_flexibility") << std::endl; std::cout << "- No file header/footer: " << properties.at("no_header_footer") << std::endl; for (size_t i = 0; i < sequences.size(); ++i) { const auto& seq = sequences[i]; std::cout << "\nSequence " << (i + 1) << ":" << std::endl; std::cout << " - Definition line: >" << seq.at("seqID") << " " << seq.at("description") << std::endl; std::cout << " - Sequence identifier: " << seq.at("seqID") << std::endl; std::cout << " - Description: " << (seq.at("description").empty() ? "None" : seq.at("description")) << std::endl; std::string seqData = seq.at("sequence"); std::cout << " - Sequence data (first 50 chars): " << (seqData.length() > 50 ? seqData.substr(0, 50) + "..." : seqData) << std::endl; std::cout << " - Sequence length: " << seq.at("length") << std::endl; std::cout << " - Alphabet: " << seq.at("alphabet") << std::endl; } } void write(const std::string& outputPath) const { if (sequences.empty()) { std::cout << "No sequences to write." << std::endl; return; } std::ofstream outFile(outputPath); if (!outFile.is_open()) { std::cerr << "Error opening output file: " << outputPath << std::endl; return; } for (const auto& seq : sequences) { outFile << ">" << seq.at("seqID") << " " << seq.at("description") << "\n"; std::string seqStr = seq.at("sequence"); for (size_t j = 0; j < seqStr.length(); j += 80) { outFile << seqStr.substr(j, 80) << "\n"; } } outFile.close(); } }; // Example usage: // int main() { // FASTAHandler handler("example.fa"); // handler.readAndDecode(); // handler.printProperties(); // handler.write("output.fa"); // return 0; // } // ===== end task-211 .FA ===== // ===== task-212 .FAA [C++] ===== #include #include #include #include #include struct Sequence { std::string identifier; std::string description; std::string sequence; }; class FaaFile { private: std::string filepath; std::vector sequences; public: FaaFile(const std::string& fp = "") : filepath(fp) {} void read(const std::string& fp = "") { if (!fp.empty()) filepath = fp; std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "File not found." << std::endl; return; } sequences.clear(); std::string line; Sequence currentSeq; std::string seqBuffer; bool inSequence = false; while (std::getline(file, line)) { if (line[0] == '>') { if (inSequence) { currentSeq.sequence = seqBuffer; sequences.push_back(currentSeq); seqBuffer.clear(); } std::string defline = line.substr(1); std::istringstream iss(defline); iss >> currentSeq.identifier; std::getline(iss, currentSeq.description); currentSeq.description = currentSeq.description.substr(1); // Remove leading space inSequence = true; } else if (inSequence) { seqBuffer += line; } } if (inSequence) { currentSeq.sequence = seqBuffer; sequences.push_back(currentSeq); } file.close(); } void printProperties() const { if (sequences.empty()) { std::cout << "No sequences loaded." << std::endl; return; } for (size_t i = 0; i < sequences.size(); ++i) { std::cout << "Sequence " << (i + 1) << ":" << std::endl; std::cout << " Identifier: " << sequences[i].identifier << std::endl; std::cout << " Description: " << sequences[i].description << std::endl; std::cout << " Sequence: " << sequences[i].sequence << std::endl; std::cout << std::endl; } } void write(const std::string& outputPath) const { std::ofstream file(outputPath); if (!file.is_open()) { std::cerr << "Could not open file for writing." << std::endl; return; } for (const auto& seq : sequences) { file << ">" << seq.identifier << " " << seq.description << "\n"; const std::string& sequence = seq.sequence; for (size_t j = 0; j < sequence.length(); j += 80) { file << sequence.substr(j, 80) << "\n"; } } file.close(); } }; // Example usage: // int main() { // FaaFile faa("example.faa"); // faa.read(); // faa.printProperties(); // faa.write("output.faa"); // return 0; // } // ===== end task-212 .FAA ===== // ===== task-213 .FACTOR [C++] ===== #include #include #include #include #include #include #include // For htonl, ntohl (big-endian conversion) class FactorFile { private: std::string filepath; std::string fileName; int32_t n; int32_t padding[3]; std::vector dataArray; public: FactorFile(const std::string& fp = "") : filepath(fp), n(0) { std::fill(padding, padding + 3, 0); if (!fp.empty()) { read(); } } void read() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { std::cerr << "Error opening file" << std::endl; return; } size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(data.data(), size); char nameBuf[9] = {0}; std::memcpy(nameBuf, data.data(), 8); fileName = std::string(nameBuf); fileName.erase(std::find_if(fileName.rbegin(), fileName.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), fileName.end()); // Trim spaces std::memcpy(&n, data.data() + 8, 4); n = ntohl(n); // Big-endian to host std::memcpy(padding, data.data() + 12, 12); for (int i = 0; i < 3; ++i) { padding[i] = ntohl(padding[i]); } dataArray.resize(n); for (int i = 0; i < n; ++i) { uint32_t raw; std::memcpy(&raw, data.data() + 24 + i * 4, 4); raw = ntohl(raw); std::memcpy(&dataArray[i], &raw, 4); // Assume IEEE float } } void write(const std::string& fname, const std::vector& dArray, const std::string& fp = "") { if (!fp.empty()) filepath = fp; fileName = fname.substr(0, 8); fileName += std::string(8 - fileName.length(), ' '); n = dArray.size(); std::fill(padding, padding + 3, 0); dataArray = dArray; std::ofstream file(filepath, std::ios::binary); if (!file) { std::cerr << "Error writing file" << std::endl; return; } file.write(fileName.data(), 8); int32_t be_n = htonl(n); file.write(reinterpret_cast(&be_n), 4); for (int i = 0; i < 3; ++i) { int32_t be_pad = htonl(padding[i]); file.write(reinterpret_cast(&be_pad), 4); } for (float val : dataArray) { uint32_t raw; std::memcpy(&raw, &val, 4); raw = htonl(raw); file.write(reinterpret_cast(&raw), 4); } } void printProperties() const { std::cout << "File Name: " << fileName << std::endl; std::cout << "Data Record Length (N): " << n << std::endl; std::cout << "Padding Fields: " << padding[0] << ", " << padding[1] << ", " << padding[2] << std::endl; std::cout << "Data Array: ["; for (size_t i = 0; i < dataArray.size(); ++i) { std::cout << dataArray[i]; if (i < dataArray.size() - 1) std::cout << ", "; } std::cout << "]" << std::endl; } }; // Example usage: // int main() { // FactorFile ff("example.FACTOR"); // ff.printProperties(); // ff.write("TESTFILE", {1.0f, 2.5f, 3.14f}, "new.FACTOR"); // return 0; // } // ===== end task-213 .FACTOR ===== // ===== task-215 .FASTQ [C] ===== #include #include #include typedef struct { char* filename; int num_reads; long total_bases; int min_qual; int max_qual; char* detected_variant; char* sample_id; char* sample_seq; char* sample_qual; // Properties as static strings } FastqHandler; const char* PROPERTIES[] = { "fileType: Text-based", "recordStructure: 4 lines per record (@seq, sequence, +sep, quality)", "sequenceConstraints: No whitespace, IUPAC nucleotides", "qualityEncoding: ASCII offsets (variants: Sanger +33, Illumina +64 Phred, Solexa +64)", "lengthMatching: Quality length == sequence length", "lineTermination: LF or CRLF", "lineWrapping: Supported (but often single-line)", "fixedRecordSize: No (variable)", "fileExtension: .fastq or .fq", "variantDetection: Inferred from quality ASCII range", NULL }; FastqHandler* fastq_handler_create(const char* filename) { FastqHandler* h = malloc(sizeof(FastqHandler)); h->filename = strdup(filename); h->num_reads = 0; h->total_bases = 0; h->min_qual = INT_MAX; h->max_qual = INT_MIN; h->detected_variant = strdup("Unknown"); h->sample_id = NULL; h->sample_seq = NULL; h->sample_qual = NULL; return h; } void fastq_handler_destroy(FastqHandler* h) { free(h->filename); free(h->detected_variant); if (h->sample_id) free(h->sample_id); if (h->sample_seq) free(h->sample_seq); if (h->sample_qual) free(h->sample_qual); free(h); } void read_and_decode(FastqHandler* h) { FILE* f = fopen(h->filename, "r"); if (!f) return; char* line = NULL; size_t len = 0; ssize_t read; int i = 0; while ((read = getline(&line, &len, f)) != -1) { if (line[0] == '@') { h->num_reads++; if (h->sample_id) free(h->sample_id); h->sample_id = strdup(line + 1); i++; // Skip to seq char seq[10000] = {0}; // Simple buffer while (getline(&line, &len, f) != -1 && line[0] != '@' && line[0] != '+') { strcat(seq, line); } int seq_len = strlen(seq); h->total_bases += seq_len; if (h->num_reads == 1) { h->sample_seq = strdup(seq); } if (line[0] != '+') continue; char qual[10000] = {0}; while (getline(&line, &len, f) != -1 && line[0] != '@') { strcat(qual, line); } if (h->num_reads == 1) { h->sample_qual = strdup(qual); } // Detect variant int offset = 33; if (qual[0] >= 64) { offset = 64; if (is_phred(qual)) { free(h->detected_variant); h->detected_variant = strdup("Illumina"); } else { free(h->detected_variant); h->detected_variant = strdup("Solexa"); } } else { free(h->detected_variant); h->detected_variant = strdup("Sanger"); } for (int j = 0; qual[j]; j++) { int phred = (int)qual[j] - offset; if (phred < h->min_qual) h->min_qual = phred; if (phred > h->max_qual) h->max_qual = phred; } } } free(line); fclose(f); } int is_phred(const char* qual) { for (int j = 0; j < 10 && qual[j]; j++) { if ((int)qual[j] - 64 < 0) return 0; } return 1; } void print_properties(FastqHandler* h) { printf("FASTQ Format Properties:\n"); for (int k = 0; PROPERTIES[k]; k++) { printf("%s\n", PROPERTIES[k]); } printf("\nFile-Specific Properties:\n"); printf("Number of Reads: %d\n", h->num_reads); printf("Total Bases: %ld\n", h->total_bases); printf("Min/Max Phred Quality: %d/%d\n", h->min_qual, h->max_qual); printf("Detected Variant: %s\n", h->detected_variant); printf("Sample Identifier: %s", h->sample_id ? h->sample_id : "N/A"); printf("\nSample Sequence (first 100 chars): %.*s...\n", 100, h->sample_seq ? h->sample_seq : ""); printf("Sample Quality String (first 100 chars): %.*s...\n", 100, h->sample_qual ? h->sample_qual : ""); } void write_copy(FastqHandler* h, const char* output) { if (!output) { asprintf((char**)&output, "%s.copy", h->filename); } FILE* out = fopen(output, "w"); if (!out) return; // Simple write first record if (h->sample_id && h->sample_seq && h->sample_qual) { fprintf(out, "@%s\n", h->sample_id); fprintf(out, "%s\n", h->sample_seq); fprintf(out, "+\n"); fprintf(out, "%s\n", h->sample_qual); } fclose(out); printf("\nWritten copy to: %s\n", output); free((void*)output); } int main(int argc, char** argv) { if (argc != 2) { printf("Usage: ./fastq_handler \n"); return 1; } FastqHandler* h = fastq_handler_create(argv[1]); read_and_decode(h); print_properties(h); write_copy(h, NULL); fastq_handler_destroy(h); return 0; } // ===== end task-215 .FASTQ ===== // ===== task-216 .FB [C] ===== #include #include #include #define BLOCK_SIZE 1024 typedef struct { unsigned char **blocks; int num_blocks; } FBFile; FBFile *fbfile_new() { FBFile *fb = malloc(sizeof(FBFile)); fb->blocks = NULL; fb->num_blocks = 0; return fb; } void fbfile_free(FBFile *fb) { if (fb) { if (fb->blocks) { for (int i = 0; i < fb->num_blocks; i++) { free(fb->blocks[i]); } free(fb->blocks); } free(fb); } } unsigned char **fbfile_read(FBFile *fb, const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) { printf("Error: File not found.\n"); return NULL; } fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); if (size % BLOCK_SIZE != 0) { printf("Invalid format: File size must be a multiple of 1024 bytes.\n"); fclose(f); return NULL; } int num_blocks = size / BLOCK_SIZE; fb->num_blocks = num_blocks; fb->blocks = malloc(num_blocks * sizeof(unsigned char *)); for (int i = 0; i < num_blocks; i++) { fb->blocks[i] = malloc(BLOCK_SIZE); fread(fb->blocks[i], 1, BLOCK_SIZE, f); } fclose(f); printf("FB File Properties:\n"); printf("Block Size: %d bytes\n", BLOCK_SIZE); printf("Block Count: %d\n", num_blocks); printf("File Size Requirement Met: Yes\n"); printf("Block Numbering: 1 to %d\n", num_blocks); printf("Block Storage Structure: Sequential concatenation without header/footer\n"); printf("Line Format per Block: 16 lines of 64 characters each\n"); printf("Data Encoding: Binary (ASCII text expected)\n"); printf("Access Model: Random access by block number\n"); return fb->blocks; } int fbfile_write(FBFile *fb, const char *filename, unsigned char **blocks, int num_blocks) { if (!blocks || num_blocks == 0) { printf("Error: No blocks to write.\n"); return -1; } FILE *f = fopen(filename, "wb"); if (!f) { printf("Error: Cannot create file.\n"); return -1; } for (int i = 0; i < num_blocks; i++) { fwrite(blocks[i], 1, BLOCK_SIZE, f); } fclose(f); printf("Written %d blocks to %s.\n", num_blocks, filename); return 0; } int main() { FBFile *fb = fbfile_new(); unsigned char **blocks = fbfile_read(fb, "example.fb"); if (blocks) { fbfile_write(fb, "output.fb", blocks, fb->num_blocks); } fbfile_free(fb); return 0; } // ===== end task-216 .FB ===== // ===== task-217 .FB2 [C] ===== #include #include #include typedef struct { xmlDocPtr doc; xmlNsPtr ns; } FB2Parser; FB2Parser* fb2_parser_new(const char* file_path) { FB2Parser* parser = malloc(sizeof(FB2Parser)); parser->doc = xmlReadFile(file_path, NULL, 0); if (parser->doc == NULL) { fprintf(stderr, "Error parsing file\n"); free(parser); return NULL; } parser->ns = xmlSearchNs(parser->doc, xmlDocGetRootElement(parser->doc), (xmlChar*)"http://www.gribuser.ru/xml/fictionbook/2.0"); return parser; } void fb2_print_properties(FB2Parser* parser) { xmlNodePtr root = xmlDocGetRootElement(parser->doc); printf("FB2 Properties:\n"); xmlChar* xmlns = xmlGetNsProp(root, (xmlChar*)"xmlns", NULL); printf("Namespace: %s\n", xmlns ? (char*)xmlns : "Not found"); xmlFree(xmlns); // Description xmlNodePtr desc = xmlNsLookupNode(root->children, parser->ns, "description"); if (desc) { xmlNodePtr title_info = xmlNsLookupNode(desc->children, parser->ns, "title-info"); if (title_info) { // Genres xmlChar* genres = NULL; xmlNodePtr genre = xmlNsLookupNode(title_info->children, parser->ns, "genre"); while (genre) { if (genres) genres = xmlStrcat(genres, (xmlChar*)", "); genres = xmlStrcat(genres, genre->children ? genre->children->content : (xmlChar*)""); genre = genre->next; if (genre) genre = xmlNsLookupNode(genre, parser->ns, "genre"); } printf("Genres: %s\n", genres ? (char*)genres : ""); xmlFree(genres); // Authors xmlChar* authors = NULL; xmlNodePtr author = xmlNsLookupNode(title_info->children, parser->ns, "author"); while (author) { xmlNodePtr first = xmlNsLookupNode(author->children, parser->ns, "first-name"); xmlNodePtr last = xmlNsLookupNode(author->children, parser->ns, "last-name"); xmlChar* auth_str = xmlStrdup((xmlChar*)""); if (first && first->children) auth_str = xmlStrcat(auth_str, first->children->content); auth_str = xmlStrcat(auth_str, (xmlChar*)" "); if (last && last->children) auth_str = xmlStrcat(auth_str, last->children->content); if (authors) authors = xmlStrcat(authors, (xmlChar*)", "); authors = xmlStrcat(authors, auth_str); xmlFree(auth_str); author = author->next; if (author) author = xmlNsLookupNode(author, parser->ns, "author"); } printf("Authors: %s\n", authors ? (char*)authors : ""); xmlFree(authors); // Title, Lang, Date xmlNodePtr title = xmlNsLookupNode(title_info->children, parser->ns, "book-title"); printf("Title: %s\n", title && title->children ? (char*)title->children->content : "N/A"); xmlNodePtr lang = xmlNsLookupNode(title_info->children, parser->ns, "lang"); printf("Language: %s\n", lang && lang->children ? (char*)lang->children->content : "N/A"); xmlNodePtr date = xmlNsLookupNode(title_info->children, parser->ns, "date"); xmlChar* date_val = xmlGetProp(date, (xmlChar*)"value"); printf("Date: %s (value: %s)\n", date && date->children ? (char*)date->children->content : "N/A", date_val ? (char*)date_val : "N/A"); if (date_val) xmlFree(date_val); } // Document-info version xmlNodePtr doc_info = xmlNsLookupNode(desc->children, parser->ns, "document-info"); if (doc_info) { xmlNodePtr version = xmlNsLookupNode(doc_info->children, parser->ns, "version"); printf("Version: %s\n", version && version->children ? (char*)version->children->content : "N/A"); } // Publish-info xmlNodePtr pub_info = xmlNsLookupNode(desc->children, parser->ns, "publish-info"); if (pub_info) { xmlNodePtr publisher = xmlNsLookupNode(pub_info->children, parser->ns, "publisher"); printf("Publisher: %s\n", publisher && publisher->children ? (char*)publisher->children->content : "N/A"); xmlNodePtr isbn = xmlNsLookupNode(pub_info->children, parser->ns, "isbn"); printf("ISBN: %s\n", isbn && isbn->children ? (char*)isbn->children->content : "N/A"); } } // Body xmlNodePtr body = xmlNsLookupNode(root->children, parser->ns, "body"); if (body) { xmlChar* body_id = xmlGetProp(body, (xmlChar*)"id"); printf("Body ID: %s\n", body_id ? (char*)body_id : "N/A"); if (body_id) xmlFree(body_id); int sections = 0; xmlNodePtr section = xmlNsLookupNode(body->children, parser->ns, "section"); while (section) { sections++; section = section->next; if (section) section = xmlNsLookupNode(section, parser->ns, "section"); } printf("Number of Sections: %d\n", sections); // First section title (simplified) xmlNodePtr first_section = xmlNsLookupNode(body->children, parser->ns, "section"); if (first_section) { xmlNodePtr title = xmlNsLookupNode(first_section->children, parser->ns, "title"); if (title) { xmlNodePtr p = xmlNsLookupNode(title->children, parser->ns, "p"); printf("First Section Title: %s\n", p && p->children ? (char*)p->children->content : "N/A"); } } } // Binaries int binaries = 0; xmlNodePtr binary = xmlNsLookupNode(root->children, parser->ns, "binary"); while (binary) { binaries++; binary = binary->next; if (binary) binary = xmlNsLookupNode(binary, parser->ns, "binary"); } printf("Number of Binaries: %d\n", binaries); if (binaries > 0) { binary = xmlNsLookupNode(root->children, parser->ns, "binary"); // First xmlChar* id = xmlGetProp(binary, (xmlChar*)"id"); xmlChar* content_type = xmlGetProp(binary, (xmlChar*)"content-type"); printf("First Binary ID: %s, Type: %s\n", id ? (char*)id : "N/A", content_type ? (char*)content_type : "N/A"); if (id) xmlFree(id); if (content_type) xmlFree(content_type); } } void fb2_write(FB2Parser* parser, const char* output_path) { xmlSaveFormatFileEnc(output_path, parser->doc, "UTF-8", 1); } void fb2_parser_free(FB2Parser* parser) { xmlFreeDoc(parser->doc); free(parser); } int main(int argc, char** argv) { if (argc < 2) return 1; FB2Parser* parser = fb2_parser_new(argv[1]); if (parser) { fb2_print_properties(parser); // fb2_write(parser, "output.fb2"); fb2_parser_free(parser); } return 0; } // ===== end task-217 .FB2 ===== // ===== task-218 .FBX [C] ===== #include #include #include #include typedef struct { uint8_t* data; size_t pos; size_t size; } FBXBuffer; typedef struct { char type; void* value; // Union or variant in real impl } FBXProperty; FBXBuffer* fbx_load(const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); size_t len = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* buf = malloc(len); fread(buf, 1, len, f); fclose(f); FBXBuffer* b = malloc(sizeof(FBXBuffer)); b->data = buf; b->pos = 0; b->size = len; return b; } uint8_t fbx_read_uint8(FBXBuffer* b) { uint8_t v = b->data[b->pos++]; return v; } uint32_t fbx_read_uint32(FBXBuffer* b) { uint32_t v = *(uint32_t*)(b->data + b->pos); b->pos += 4; return __builtin_bswap32(v); // To LE if needed; assume host LE } int32_t fbx_read_int32(FBXBuffer* b) { int32_t v = *(int32_t*)(b->data + b->pos); b->pos += 4; return __builtin_bswap32(v); } float fbx_read_float32(FBXBuffer* b) { float v; memcpy(&v, b->data + b->pos, 4); b->pos += 4; return v; // Assume LE } double fbx_read_float64(FBXBuffer* b) { double v; memcpy(&v, b->data + b->pos, 8); b->pos += 8; return v; } int64_t fbx_read_int64(FBXBuffer* b) { int64_t v; memcpy(&v, b->data + b->pos, 8); b->pos += 8; return v; } char* fbx_read_string(FBXBuffer* b, uint32_t len) { char* s = malloc(len + 1); memcpy(s, b->data + b->pos, len); s[len] = '\0'; b->pos += len; return s; } uint8_t* fbx_read_bytes(FBXBuffer* b, uint32_t len) { uint8_t* bytes = malloc(len); memcpy(bytes, b->data + b->pos, len); b->pos += len; return bytes; } void fbx_parse_property(FBXBuffer* b, FBXProperty* prop) { prop->type = (char)fbx_read_uint8(b); // Simplified: print type and skip data bytes based on type (implement full union) switch (prop->type) { case 'Y': prop->value = malloc(2); memcpy(prop->value, b->data + b->pos, 2); b->pos += 2; break; case 'C': /* 1 byte already read */ break; case 'I': prop->value = malloc(4); memcpy(prop->value, b->data + b->pos, 4); b->pos += 4; break; // Add F, D, L similarly case 'S': case 'R': { uint32_t len = fbx_read_uint32(b); prop->value = fbx_read_bytes(b, len); break; } case 'f': case 'd': case 'l': case 'i': case 'b': { uint32_t len = fbx_read_uint32(b); uint32_t enc = fbx_read_uint32(b); uint32_t comp_len = fbx_read_uint32(b); // Stub: skip data b->pos += (enc == 0 ? len * (prop->type == 'f' || prop->type == 'i' ? 4 : 8) : comp_len); prop->value = malloc(4); // Preview break; } default: prop->value = NULL; } printf("Property type: %c\n", prop->type); } void fbx_parse_node(FBXBuffer* b, const char* name, const char* indent) { uint32_t end_offset = fbx_read_uint32(b); uint32_t num_props = fbx_read_uint32(b); uint32_t prop_len = fbx_read_uint32(b); uint8_t name_len = fbx_read_uint8(b); char* node_name = name_len ? fbx_read_string(b, name_len) : strdup(name); printf("%sNode: %s\n", indent, node_name); printf("%s EndOffset: %u\n", indent, end_offset); printf("%s NumProps: %u\n", indent, num_props); printf("%s PropLen: %u\n", indent, prop_len); for (uint32_t i = 0; i < num_props; i++) { FBXProperty prop = {0}; fbx_parse_property(b, &prop); // Free prop.value if needed } // Skip children and NULL (13 bytes) b->pos = end_offset - 13; b->pos += 13; free(node_name); } void fbx_parse_header(FBXBuffer* b) { char magic[22]; memcpy(magic, b->data, 21); magic[21] = '\0'; b->pos = 21; uint8_t unk1 = fbx_read_uint8(b); uint8_t endian = fbx_read_uint8(b); uint32_t version = fbx_read_uint32(b); printf("Header Magic: %s\n", magic); printf("Unknown1: 0x%02x\n", unk1); printf("Endian: %s\n", endian == 0 ? "Little" : "Big"); printf("Version: %u\n", version); b->pos = 27; } void fbx_read_and_print(FBXBuffer* b) { fbx_parse_header(b); fbx_parse_node(b, "Root", ""); } void fbx_write(const char* filename, uint32_t version) { FILE* f = fopen(filename, "wb"); if (!f) return; const char* header = "Kaydara FBX Binary \0\x1A\0"; fwrite(header, 1, 25, f); // 21 +1 null +2 unk +1 for version start fwrite(&version, 4, 1, f); uint32_t root_end = 27 + 13; fwrite(&root_end, 4, 1, f); uint32_t zero = 0; fwrite(&zero, 4, 1, f); // Num props fwrite(&zero, 4, 1, f); // Prop len uint8_t name_len = 0; fwrite(&name_len, 1, 1, f); uint8_t null_rec[13] = {0}; fwrite(null_rec, 1, 13, f); fclose(f); } int main() { FBXBuffer* b = fbx_load("cube.fbx"); if (b) { fbx_read_and_print(b); // fbx_write("minimal.fbx", 7300); free(b->data); free(b); } return 0; } // ===== end task-218 .FBX ===== // ===== task-219 .FCHK [C] ===== #include #include #include #include // For regex, or implement simple parsing // Simplified: Use arrays for properties (up to 100 keys, values as double* or int) #define MAX_PROPS 100 #define MAX_LINE 1024 #define MAX_KEY 256 typedef struct { char keys[MAX_PROPS][MAX_KEY]; void* values[MAX_PROPS]; // double* for arrays/scalars (cast) int types[MAX_PROPS]; // 0: scalar int, 1: scalar double, 2: array double int ns[MAX_PROPS]; // size for arrays, 1 for scalars int count; char title[73]; char type[11]; char method[31]; char basis[31]; } FCHKProperties; void parse_fchk(FCHKProperties* props, const char* filename) { FILE* fp = fopen(filename, "r"); if (!fp) return; char line[MAX_LINE]; fgets(line, sizeof(line), fp); strncpy(props->title, line, 72); fgets(line, sizeof(line), fp); sscanf(line, "%10s %30s %30s", props->type, props->method, props->basis); props->count = 0; regex_t regex; regcomp(®ex, "^([A-Za-z ]+?)(I|R)( N=([0-9]+))?$", REG_EXTENDED); while (fgets(line, sizeof(line), fp)) { size_t len = strlen(line); if (len < 2 || line[0] == '\n') continue; regmatch_t matches[5]; if (regexec(®ex, line, 5, matches, 0) != 0) continue; char label[256], dtype[2], nstr[16]; int label_start = matches[1].rm_so; int label_end = matches[1].rm_eo; strncpy(label, line + label_start, label_end - label_start); label[label_end - label_start] = '\0'; strncpy(dtype, line + matches[2].rm_so, 1); int is_array = (matches[3].rm_so != -1); int n = 1; if (is_array) { strncpy(nstr, line + matches[4].rm_so, matches[4].rm_eo - matches[4].rm_so); n = atoi(nstr); } strncpy(props->keys[props->count], label, sizeof(label)); for (int i = 0; i < strlen(props->keys[props->count]); i++) { if (props->keys[props->count][i] == ' ') props->keys[props->count][i] = '_'; } tolower(props->keys[props->count]); double* val = malloc((is_array ? n : 1) * sizeof(double)); if (!is_array) { // Scalar: parse from line sscanf(line + matches[2].rm_eo, "%lf", val); props->types[props->count] = 1; // double scalar } else { // Array: read next lines int remaining = n; int col = strcmp(dtype, "R") == 0 ? 6 : 5; while (remaining > 0 && fgets(line, sizeof(line), fp)) { char* ptr = line; for (int j = 0; j < col && remaining > 0; j++) { if (sscanf(ptr, "%lf", val + (n - remaining)) == 1) { // Advance ptr roughly ptr = strstr(ptr, " ") + 1; remaining--; } } } props->types[props->count] = 2; // array } props->ns[props->count] = n; props->values[props->count] = val; props->count++; if (props->count >= MAX_PROPS) break; } fclose(fp); regfree(®ex); } void write_fchk(FCHKProperties* props, const char* output) { FILE* fp = fopen(output, "w"); if (!fp) return; fprintf(fp, "%s\n", props->title); fprintf(fp, "%-10s %-30s %-30s\n", props->type, props->method, props->basis); for (int i = 0; i < props->count; i++) { if (strstr(props->keys[i], "title") || strstr(props->keys[i], "type") || strstr(props->keys[i], "method") || strstr(props->keys[i], "basis")) continue; char lbl[256]; strcpy(lbl, props->keys[i]); for (int j = 0; lbl[j]; j++) lbl[j] = toupper(lbl[j]); char* underscore = strstr(lbl, "_"); if (underscore) *underscore = ' '; char dtype = props->types[i] == 0 ? 'I' : 'R'; if (props->types[i] == 2) { fprintf(fp, "%s %c N=%d\n", lbl, dtype, props->ns[i]); int col = 6; double* arr = (double*) props->values[i]; for (int j = 0; j < props->ns[i]; j += col) { for (int k = 0; k < col && j + k < props->ns[i]; k++) { fprintf(fp, "%16.8E ", arr[j + k]); } fprintf(fp, "\n"); } } else { double v = *(double*) props->values[i]; fprintf(fp, "%s %c %.8E\n", lbl, dtype, v); } } fclose(fp); } void print_properties(FCHKProperties* props) { printf("Title: %s\n", props->title); printf("Type: %s, Method: %s, Basis: %s\n", props->type, props->method, props->basis); for (int i = 0; i < props->count; i++) { printf("%s: ", props->keys[i]); if (props->types[i] == 2) { double* arr = (double*) props->values[i]; printf("["); for (int j = 0; j < props->ns[i]; j++) { printf("%.3f", arr[j]); if (j < props->ns[i] - 1) printf(", "); } printf("]\n"); } else { printf("%.8E\n", *(double*) props->values[i]); } } } void free_props(FCHKProperties* props) { for (int i = 0; i < props->count; i++) { free(props->values[i]); } } // Usage: FCHKProperties props = {0}; parse_fchk(&props, "sample.fchk"); print_properties(&props); write_fchk(&props, "output.fchk"); free_props(&props); // ===== end task-219 .FCHK ===== // ===== task-220 .FCS [C] ===== #include #include #include typedef struct { char filepath[256]; unsigned char* buffer; long filesize; char version[7]; char delimiter; long offsets[6]; // 0:BEGINSTEXT,1:ENDSTEXT,2:BEGINDATA,3:ENDDATA,4:BEGINANALYSIS,5:ENDANALYSIS char keywords[100][256]; // Simple array for keywords (key=value) int num_keywords; int par; } FCSReader; void parse_header(FCSReader* reader) { memcpy(reader->version, reader->buffer, 6); reader->version[6] = '\0'; printf("FCS Version: %s\n", reader->version); long parse_offset(int start) { char str[9]; memcpy(str, reader->buffer + start, 8); str[8] = '\0'; char* end; return strtol(str, &end, 10); } reader->offsets[0] = parse_offset(10); // BEGINSTEXT reader->offsets[1] = parse_offset(18); // ENDSTEXT reader->offsets[2] = parse_offset(26); // BEGINDATA reader->offsets[3] = parse_offset(34); // ENDDATA reader->offsets[4] = parse_offset(42); // BEGINANALYSIS reader->offsets[5] = parse_offset(50); // ENDANALYSIS char* offset_names[] = {"BEGINSTEXT", "ENDSTEXT", "BEGINDATA", "ENDDATA", "BEGINANALYSIS", "ENDANALYSIS"}; for (int i = 0; i < 6; i++) { printf("$%s: %ld\n", offset_names[i], reader->offsets[i]); } } void parse_text(FCSReader* reader) { long start = reader->offsets[0]; long end = reader->offsets[1]; reader->delimiter = reader->buffer[start]; printf("Delimiter: '%c'\n", reader->delimiter); // Simple keyword parse (assumes no escapes, basic split) reader->num_keywords = 0; char text[10000]; memcpy(text, reader->buffer + start + 1, end - start - 1); text[end - start - 1] = '\0'; char* token = strtok(text, &reader->delimiter); while (token && reader->num_keywords < 100) { char* key = token; token = strtok(NULL, &reader->delimiter); if (!token) break; char* val = token; token = strtok(NULL, &reader->delimiter); if (val) { snprintf(reader->keywords[reader->num_keywords], 256, "%s=%s", key, val); reader->num_keywords++; } } } void print_keywords(FCSReader* reader) { char nextdata[20] = "0"; char byteord[50] = "Unknown"; char datatype[20] = "Unknown"; char mode[20] = "Unknown"; int par = 0, tot = 0; for (int i = 0; i < reader->num_keywords; i++) { if (strncmp(reader->keywords[i], "$NEXTDATA=", 10) == 0) strncpy(nextdata, reader->keywords[i] + 10, 19); if (strncmp(reader->keywords[i], "$BYTEORD=", 9) == 0) strncpy(byteord, reader->keywords[i] + 9, 49); if (strncmp(reader->keywords[i], "$DATATYPE=", 10) == 0) strncpy(datatype, reader->keywords[i] + 10, 19); if (strncmp(reader->keywords[i], "$MODE=", 6) == 0) strncpy(mode, reader->keywords[i] + 6, 19); if (strncmp(reader->keywords[i], "$PAR=", 5) == 0) par = atoi(reader->keywords[i] + 5); if (strncmp(reader->keywords[i], "$TOT=", 5) == 0) tot = atoi(reader->keywords[i] + 5); } printf("$NEXTDATA: %s\n", nextdata); printf("$BYTEORD: %s\n", byteord); printf("$DATATYPE: %s\n", datatype); printf("$MODE: %s\n", mode); printf("$PAR: %d\n", par); reader->par = par; printf("$TOT: %d\n", tot); for (int n = 1; n <= par; n++) { char pnN[50] = "Unknown", pnB[20] = "Unknown", pnE[20] = "Unknown", pnR[20] = "Unknown"; char search[10]; snprintf(search, 10, "$P%dN=", n); for (int i = 0; i < reader->num_keywords; i++) { if (strncmp(reader->keywords[i], search, strlen(search)) == 0) strncpy(pnN, reader->keywords[i] + strlen(search), 49); snprintf(search, 10, "$P%dB=", n); if (strncmp(reader->keywords[i], search, strlen(search)) == 0) strncpy(pnB, reader->keywords[i] + strlen(search), 19); snprintf(search, 10, "$P%dE=", n); if (strncmp(reader->keywords[i], search, strlen(search)) == 0) strncpy(pnE, reader->keywords[i] + strlen(search), 19); snprintf(search, 10, "$P%dR=", n); if (strncmp(reader->keywords[i], search, strlen(search)) == 0) strncpy(pnR, reader->keywords[i] + strlen(search), 19); } printf("\nParameter %d:\n", n); printf(" $P%dN: %s\n", n, pnN); printf(" $P%dB: %s\n", n, pnB); printf(" $P%dE: %s\n", n, pnE); printf(" $P%dR: %s\n", n, pnR); } } void write_file(FCSReader* reader, char* output_path) { FILE* out = fopen(output_path, "wb"); if (!out) return; // HEADER fwrite(reader->version, 1, 6, out); for (int i = 0; i < 4; i++) fputc(' ', out); char off_str[9]; for (int i = 0; i < 6; i++) { sprintf(off_str, "%8ld", reader->offsets[i]); fwrite(off_str, 1, 8, out); } // TEXT (simplified) fputc(reader->delimiter, out); // Write keywords roughly for (int i = 0; i < reader->num_keywords; i++) { char* eq = strchr(reader->keywords[i], '='); if (eq) { *eq = '\0'; char key[256]; strncpy(key, reader->keywords[i], 255); char val[256]; strcpy(val, eq + 1); *eq = '='; fprintf(out, "%s%c%s%c", key + 1, reader->delimiter, val, reader->delimiter); // Skip $ } } // Pad TEXT long text_len = reader->offsets[1] - reader->offsets[0]; long cur_pos = ftell(out); for (long j = cur_pos; j < reader->offsets[0] + text_len; j++) fputc(' ', out); // DATA and ANALYSIS fwrite(reader->buffer + reader->offsets[2], 1, reader->offsets[3] - reader->offsets[2], out); if (reader->offsets[4] > 0) { fseek(out, reader->offsets[4], SEEK_SET); fwrite(reader->buffer + reader->offsets[4], 1, reader->offsets[5] - reader->offsets[4], out); } fclose(out); printf("Written to %s\n", output_path); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s [output.fcs]\n", argv[0]); return 1; } FCSReader reader; strcpy(reader.filepath, argv[1]); FILE* f = fopen(argv[1], "rb"); fseek(f, 0, SEEK_END); reader.filesize = ftell(f); fseek(f, 0, SEEK_SET); reader.buffer = malloc(reader.filesize); fread(reader.buffer, 1, reader.filesize, f); fclose(f); parse_header(&reader); parse_text(&reader); print_keywords(&reader); if (argc > 2) write_file(&reader, argv[2]); free(reader.buffer); return 0; } // ===== end task-220 .FCS ===== // ===== task-221 .FEN [C] ===== #include #include #include typedef struct { int line; char piece_placement[100]; char active_color[2]; char castling[5]; char en_passant[5]; int halfmove_clock; int fullmove_number; } FENPosition; typedef struct { FENPosition* positions; int count; } FENHandler; FENHandler* fen_handler_new(const char* filename) { FENHandler* handler = malloc(sizeof(FENHandler)); handler->positions = NULL; handler->count = 0; FILE* file = fopen(filename, "r"); if (!file) { fprintf(stderr, "Error opening file: %s\n", filename); free(handler); return NULL; } char line[256]; int line_num = 1; while (fgets(line, sizeof(line), file)) { char* fen = line; while (*fen == ' ' || *fen == '\t') fen++; // Trim start char* end = fen + strlen(fen) - 1; while (end > fen && (*end == ' ' || *end == '\t' || *end == '\n')) *end-- = '\0'; if (strlen(fen) == 0) { line_num++; continue; } char* fields[6]; int field_count = 0; char* token = strtok(fen, " "); while (token && field_count < 6) { fields[field_count++] = token; token = strtok(NULL, " "); } if (field_count != 6) { fprintf(stderr, "Invalid FEN on line %d: Must have 6 fields.\n", line_num); line_num++; continue; } FENPosition pos = {line_num, "", "", "", "", 0, 0}; strncpy(pos.piece_placement, fields[0], sizeof(pos.piece_placement) - 1); strncpy(pos.active_color, fields[1], 1); strncpy(pos.castling, fields[2], sizeof(pos.castling) - 1); strncpy(pos.en_passant, fields[3], sizeof(pos.en_passant) - 1); pos.halfmove_clock = atoi(fields[4]); pos.fullmove_number = atoi(fields[5]); handler->positions = realloc(handler->positions, (handler->count + 1) * sizeof(FENPosition)); handler->positions[handler->count++] = pos; line_num++; } fclose(file); return handler; } void print_properties(FENHandler* handler) { for (int i = 0; i < handler->count; i++) { FENPosition* pos = &handler->positions[i]; printf("Position from line %d:\n", pos->line); printf(" piecePlacement: %s\n", pos->piece_placement); printf(" activeColor: %s\n", pos->active_color); printf(" castlingAvailability: %s\n", pos->castling); printf(" enPassantTarget: %s\n", pos->en_passant); printf(" halfmoveClock: %d\n", pos->halfmove_clock); printf(" fullmoveNumber: %d\n", pos->fullmove_number); printf("\n"); } } void write_fen(FENHandler* handler, const char* output_filename) { FILE* out = fopen(output_filename, "w"); if (!out) { fprintf(stderr, "Error opening output file: %s\n", output_filename); return; } for (int i = 0; i < handler->count; i++) { FENPosition* pos = &handler->positions[i]; fprintf(out, "%s %s %s %s %d %d\n", pos->piece_placement, pos->active_color, pos->castling, pos->en_passant, pos->halfmove_clock, pos->fullmove_number); } fclose(out); } void fen_handler_free(FENHandler* handler) { free(handler->positions); free(handler); } // Example usage in main: // int main() { // FENHandler* handler = fen_handler_new("sample.fen"); // if (handler) { // print_properties(handler); // write_fen(handler, "output.fen"); // fen_handler_free(handler); // } // return 0; // } // ===== end task-221 .FEN ===== // ===== task-222 .FF [C] ===== #include #include #include #include typedef struct { uint32_t decompressed_size; uint32_t referenced_size; uint32_t unknown_flag; uint8_t unknown_padding[12]; uint32_t size_related; uint8_t unknown_header[16]; uint32_t num_strings; uint32_t num_blocks; } FFHeader; typedef struct { char* type_name; uint32_t type_id; uint32_t offset; uint32_t size; } FFBlock; typedef struct { FFHeader header; char** strings; FFBlock* blocks; size_t num_strings_actual; size_t num_blocks_actual; } FFProperties; typedef struct { const char* type_names[33]; // Indexed by type_id } FFParser; // Initialize type names void ff_parser_init(FFParser* parser) { parser->type_names[0] = "xmodelpieces"; parser->type_names[1] = "physpreset"; parser->type_names[2] = "xanim"; parser->type_names[3] = "xmodel"; parser->type_names[4] = "material"; parser->type_names[5] = "pixelshader"; parser->type_names[6] = "techset"; parser->type_names[7] = "image"; parser->type_names[8] = "sndcurve"; parser->type_names[9] = "loaded_sound"; parser->type_names[10] = "col_map_sp"; parser->type_names[11] = "col_map_mp"; parser->type_names[12] = "com_map"; parser->type_names[13] = "game_map_sp"; parser->type_names[14] = "game_map_mp"; parser->type_names[15] = "map_ents"; parser->type_names[16] = "gfx_map"; parser->type_names[17] = "lightdef"; parser->type_names[18] = "ui_map"; parser->type_names[19] = "font"; parser->type_names[20] = "menufile"; parser->type_names[21] = "menu"; parser->type_names[22] = "localize"; parser->type_names[23] = "weapon"; parser->type_names[24] = "snddriverglobals"; parser->type_names[25] = "impactfx"; parser->type_names[26] = "aitype"; parser->type_names[27] = "mptype"; parser->type_names[28] = "character"; parser->type_names[29] = "xmodelalias"; parser->type_names[31] = "rawfile"; parser->type_names[32] = "stringtable"; } FFProperties* ff_read(const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); FFProperties* props = malloc(sizeof(FFProperties)); FFParser parser; ff_parser_init(&parser); uint32_t offset = 0; props->header.decompressed_size = *(uint32_t*)(data + offset) + 44; offset += 4; props->header.referenced_size = *(uint32_t*)(data + offset); offset += 4; props->header.unknown_flag = *(uint32_t*)(data + offset); offset += 4; memcpy(props->header.unknown_padding, data + offset, 12); offset += 12; props->header.size_related = *(uint32_t*)(data + offset); offset += 4; memcpy(props->header.unknown_header, data + offset, 16); offset += 16; props->header.num_strings = *(uint32_t*)(data + offset); offset += 4; offset += 4; // Separator props->header.num_blocks = *(uint32_t*)(data + offset); offset += 4; offset += 8; // Separator props->num_strings_actual = 0; props->strings = malloc(sizeof(char*) * props->header.num_strings); if (props->header.num_strings > 0) { uint32_t* string_offsets = malloc(sizeof(uint32_t) * props->header.num_strings); for (uint32_t i = 0; i < props->header.num_strings; i++) { string_offsets[i] = *(uint32_t*)(data + offset); offset += 4; } for (uint32_t i = 0; i < props->header.num_strings; i++) { uint32_t soff = string_offsets[i]; uint32_t len = 0; while (data[soff + len] != 0) len++; props->strings[i] = malloc(len + 1); memcpy(props->strings[i], data + soff, len + 1); props->num_strings_actual++; } free(string_offsets); } // Data blocks (simplified) props->num_blocks_actual = props->header.num_blocks; props->blocks = malloc(sizeof(FFBlock) * props->num_blocks_actual); uint32_t prev_off = offset + (props->header.num_blocks * 8); for (uint32_t i = 0; i < props->num_blocks_actual; i++) { uint32_t block_offset = *(uint32_t*)(data + offset); uint32_t type_id = *(uint32_t*)(data + offset + 4); offset += 8; uint32_t actual_off = (block_offset == 0xFFFFFFFF) ? prev_off : block_offset; uint32_t block_size = (i < props->num_blocks_actual - 1) ? props->blocks[i].offset : size - actual_off; const char* type_name = parser.type_names[type_id] ? parser.type_names[type_id] : "Unknown"; props->blocks[i].type_name = strdup(type_name); props->blocks[i].type_id = type_id; props->blocks[i].offset = actual_off; props->blocks[i].size = block_size; prev_off = actual_off + block_size; } free(data); return props; } void ff_print_properties(FFProperties* props) { printf("=== .FF File Properties ===\n"); printf("Decompressed Size: %u\n", props->header.decompressed_size); printf("Referenced Data Size: %u\n", props->header.referenced_size); printf("Unknown Flag: %u\n", props->header.unknown_flag); printf("Num Strings: %u\n", props->header.num_strings); printf("Num Blocks: %u\n", props->header.num_blocks); if (props->num_strings_actual > 0) { printf("Strings: "); for (size_t i = 0; i < props->num_strings_actual; i++) { printf("%s ", props->strings[i]); } printf("\n"); } printf("Data Blocks:\n"); for (size_t i = 0; i < props->num_blocks_actual; i++) { printf(" - Type: %s (ID: 0x%08X), Offset: %u, Size: %u\n", props->blocks[i].type_name, props->blocks[i].type_id, props->blocks[i].offset, props->blocks[i].size); } } void ff_write(const char* filename, FFProperties* props) { FILE* f = fopen(filename, "wb"); if (!f) return; // Stub header fwrite(&props->header.decompressed_size, 4, 1, f); props->header.decompressed_size -= 44; // Adjust for write // Write other fields similarly (little-endian assumed) fwrite(&props->header, sizeof(FFHeader) - 4, 1, f); // Skip last for simplicity // Stub separators and blocks for (size_t i = 0; i < props->num_blocks_actual; i++) { uint8_t sep[4] = {0xFF, 0xFF, 0xFF, 0xFF}; fwrite(sep, 1, 4, f); uint8_t* placeholder = calloc(props->blocks[i].size, 1); fwrite(placeholder, 1, props->blocks[i].size, f); free(placeholder); } fclose(f); } void ff_free(FFProperties* props) { for (size_t i = 0; i < props->num_strings_actual; i++) free(props->strings[i]); free(props->strings); for (size_t i = 0; i < props->num_blocks_actual; i++) free((void*)props->blocks[i].type_name); free(props->blocks); free(props); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: ./ff_parser \n"); return 1; } FFProperties* props = ff_read(argv[1]); if (!props) { printf("Failed to read file.\n"); return 1; } ff_print_properties(props); // ff_write("output.ff", props); ff_free(props); return 0; } // ===== end task-222 .FF ===== // ===== task-223 .FFAPX [C] ===== #include #include #include #include #include #include typedef struct { char *filepath; char *properties[10]; // Simple key-value array (limited) int prop_count; } FFAPXDecoder; FFAPXDecoder* ffapx_decoder_new(const char *filepath) { FFAPXDecoder *decoder = malloc(sizeof(FFAPXDecoder)); if (!decoder) return NULL; decoder->filepath = strdup(filepath); decoder->prop_count = 0; if (strlen(filepath) < 6 || strcmp(filepath + strlen(filepath) - 6, ".FFAPX") != 0) { free(decoder->filepath); free(decoder); fprintf(stderr, "Error: File must end with .FFAPX\n"); return NULL; } return decoder; } void ffapx_decoder_free(FFAPXDecoder *decoder) { if (decoder) { free(decoder->filepath); for (int i = 0; i < decoder->prop_count; i++) { free(decoder->properties[i]); } free(decoder); } } void add_property(FFAPXDecoder *decoder, const char *key, const char *value) { if (decoder->prop_count < 10) { char *prop = malloc(strlen(key) + strlen(value) + 2); sprintf(prop, "%s: %s", key, value); decoder->properties[decoder->prop_count++] = prop; } } void read_properties(FFAPXDecoder *decoder) { struct stat st; if (stat(decoder->filepath, &st) != 0) { fprintf(stderr, "Error: File %s not found.\n", decoder->filepath); return; } add_property(decoder, "filename", decoder->filepath + strrchr(decoder->filepath, '/') ? strrchr(decoder->filepath, '/') + 1 : decoder->filepath); char size_str[32]; sprintf(size_str, "%ld", (long)st.st_size); add_property(decoder, "size_bytes", size_str); char time_str[32]; sprintf(time_str, "%ld", (long)st.st_mtime); add_property(decoder, "modified_time", time_str); // Hex dump first 512 bytes FILE *f = fopen(decoder->filepath, "rb"); if (!f) return; unsigned char buffer[512]; size_t bytes = fread(buffer, 1, 512, f); fclose(f); char hex_str[1025]; for (size_t i = 0; i < bytes; i++) { sprintf(hex_str + i * 2, "%02x", buffer[i]); } hex_str[bytes * 2] = '\0'; add_property(decoder, "hex_preview", hex_str); printf("FFAPX Properties (limited due to proprietary format):\n"); for (int i = 0; i < decoder->prop_count; i++) { printf("%s\n", decoder->properties[i]); } } void write_properties(FFAPXDecoder *decoder, const char *output_path) { fprintf(stderr, "Error: Write functionality requires format specs.\n"); } int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } FFAPXDecoder *decoder = ffapx_decoder_new(argv[1]); if (decoder) { read_properties(decoder); ffapx_decoder_free(decoder); } return 0; } // ===== end task-223 .FFAPX ===== // ===== task-224 .FFN [C] ===== #include #include #include typedef struct { char* filepath; char* fileType; char* extension; char* mimeType; char* structure; char* headerPrefix; char* headerContent; char* sequenceData; char* allowedCharacters; char* multiSequenceSupport; char* lineEndings; char* binaryComponents; char* endianness; char* magicBytes; char* intrinsicFileSystemProperties; int numSequences; int totalSequenceLength; } FFNHandler; FFNHandler* createFFNHandler(char* filepath) { FFNHandler* handler = malloc(sizeof(FFNHandler)); handler->filepath = strdup(filepath); handler->fileType = "Text (ASCII/UTF-8)"; handler->extension = ".ffn"; handler->mimeType = "text/plain or application/x-fasta"; handler->structure = "Unstructured text with alternating headers and sequence lines"; handler->headerPrefix = ">"; handler->headerContent = "Sequence identifier (mandatory) and description (optional)"; handler->sequenceData = "Lines of nucleotide characters"; handler->allowedCharacters = "A, C, G, T, U, N, R, Y, K, M, S, W, B, D, H, V, -"; handler->multiSequenceSupport = "Yes"; handler->lineEndings = "CR/LF or LF"; handler->binaryComponents = "No"; handler->endianness = "N/A"; handler->magicBytes = "No"; handler->intrinsicFileSystemProperties = "Regular file, readable as text, size variable, creation/modified dates per FS"; handler->numSequences = 0; handler->totalSequenceLength = 0; return handler; } void destroyFFNHandler(FFNHandler* handler) { free(handler->filepath); free(handler); } typedef struct { char* header; char* seq; } Sequence; Sequence* readSequences(FFNHandler* handler, int* count) { FILE* f = fopen(handler->filepath, "r"); if (!f) return NULL; char* content = NULL; long length = 0; fseek(f, 0, SEEK_END); length = ftell(f); fseek(f, 0, SEEK_SET); content = malloc(length + 1); fread(content, 1, length, f); content[length] = '\0'; fclose(f); Sequence* sequences = NULL; *count = 0; char* line = strtok(content, "\n"); char* currentHeader = NULL; char* currentSeq = malloc(1); currentSeq[0] = '\0'; while (line) { if (line[0] == '>') { if (currentHeader) { sequences = realloc(sequences, (*count + 1) * sizeof(Sequence)); sequences[*count].header = currentHeader; sequences[*count].seq = currentSeq; handler->totalSequenceLength += strlen(currentSeq); (*count)++; } currentHeader = strdup(line + 1); currentSeq = malloc(1); currentSeq[0] = '\0'; } else { currentSeq = realloc(currentSeq, strlen(currentSeq) + strlen(line) + 1); strcat(currentSeq, line); } line = strtok(NULL, "\n"); } if (currentHeader) { sequences = realloc(sequences, (*count + 1) * sizeof(Sequence)); sequences[*count].header = currentHeader; sequences[*count].seq = currentSeq; handler->totalSequenceLength += strlen(currentSeq); (*count)++; } handler->numSequences = *count; free(content); return sequences; } void printProperties(FFNHandler* handler) { printf("fileType: %s\n", handler->fileType); printf("extension: %s\n", handler->extension); printf("mimeType: %s\n", handler->mimeType); printf("structure: %s\n", handler->structure); printf("headerPrefix: %s\n", handler->headerPrefix); printf("headerContent: %s\n", handler->headerContent); printf("sequenceData: %s\n", handler->sequenceData); printf("allowedCharacters: %s\n", handler->allowedCharacters); printf("multiSequenceSupport: %s\n", handler->multiSequenceSupport); printf("lineEndings: %s\n", handler->lineEndings); printf("binaryComponents: %s\n", handler->binaryComponents); printf("endianness: %s\n", handler->endianness); printf("magicBytes: %s\n", handler->magicBytes); printf("intrinsicFileSystemProperties: %s\n", handler->intrinsicFileSystemProperties); printf("numSequences: %d\n", handler->numSequences); printf("totalSequenceLength: %d\n", handler->totalSequenceLength); } void writeSequences(FFNHandler* handler, Sequence* sequences, int count, char* newFilepath) { char* path = newFilepath ? newFilepath : handler->filepath; FILE* f = fopen(path, "w"); if (!f) return; for (int i = 0; i < count; i++) { fprintf(f, ">%s\n", sequences[i].header); char* seq = sequences[i].seq; for (size_t j = 0; j < strlen(seq); j += 80) { char buffer[81]; strncpy(buffer, seq + j, 80); buffer[80] = '\0'; fprintf(f, "%s\n", buffer); } } fclose(f); } int main() { FFNHandler* handler = createFFNHandler("example.ffn"); int count; Sequence* sequences = readSequences(handler, &count); printProperties(handler); writeSequences(handler, sequences, count, "output.ffn"); // Free memory for (int i = 0; i < count; i++) { free(sequences[i].header); free(sequences[i].seq); } free(sequences); destroyFFNHandler(handler); return 0; } // ===== end task-224 .FFN ===== // ===== task-225 .FIT [C] ===== #include #include #include #include typedef struct { char *filepath; uint8_t header_size; uint8_t protocol_version; uint16_t profile_version; uint32_t data_size; char data_type[5]; uint16_t header_crc; uint16_t file_crc; } FitFileHandler; FitFileHandler* fit_create(const char *filepath) { FitFileHandler *handler = malloc(sizeof(FitFileHandler)); handler->filepath = strdup(filepath); memset(handler, 0, sizeof(FitFileHandler)); return handler; } void fit_destroy(FitFileHandler *handler) { free(handler->filepath); free(handler); } int fit_read_and_decode(FitFileHandler *handler) { FILE *f = fopen(handler->filepath, "rb"); if (!f) return -1; fseek(f, 0, SEEK_END); long len = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(len); fread(data, 1, len, f); fclose(f); if (len < 14) { free(data); return -1; } handler->header_size = data[0]; handler->protocol_version = data[1]; memcpy(&handler->profile_version, &data[2], 2); // LE assumed native memcpy(&handler->data_size, &data[4], 4); memcpy(handler->data_type, &data[8], 4); handler->data_type[4] = '\0'; handler->header_crc = 0; if (handler->header_size == 14) { memcpy(&handler->header_crc, &data[12], 2); } else if (handler->header_size != 12) { free(data); return -1; } uint32_t expected_len = handler->header_size + handler->data_size + 2; if (len != expected_len) { free(data); return -1; } memcpy(&handler->file_crc, &data[handler->header_size + handler->data_size], 2); free(data); return 0; } void fit_print_properties(FitFileHandler *handler) { printf("Header Size: %u\n", handler->header_size); printf("Protocol Version: %u\n", handler->protocol_version); printf("Profile Version: %u\n", handler->profile_version); printf("Data Size: %u\n", handler->data_size); printf("Data Type: %s\n", handler->data_type); printf("Header CRC: 0x%04X\n", handler->header_crc); printf("File CRC: 0x%04X\n", handler->file_crc); } int fit_write(FitFileHandler *handler, const char *output_path) { if (!output_path) output_path = "modified.fit"; FILE *src = fopen(handler->filepath, "rb"); FILE *dest = fopen(output_path, "wb"); if (!src || !dest) return -1; char buf[1024]; size_t read; while ((read = fread(buf, 1, sizeof(buf), src)) > 0) { fwrite(buf, 1, read, dest); } fclose(src); fclose(dest); printf("File written to %s\n", output_path); return 0; } // Example usage: // int main() { // FitFileHandler *handler = fit_create("example.fit"); // if (fit_read_and_decode(handler) == 0) { // fit_print_properties(handler); // fit_write(handler, NULL); // } // fit_destroy(handler); // return 0; // } // ===== end task-225 .FIT ===== // ===== task-226 .FITS [C++] ===== #include #include #include #include #include #include #include #include class FitsHandler { private: std::string filepath; std::map properties; // Store as string for simplicity std::vector data; public: FitsHandler(const std::string& fp) : filepath(fp) { read(); } void read() { std::ifstream file(filepath, std::ios::binary); if (!file) return; std::string header; char block[2880]; while (true) { file.read(block, 2880); header.append(block, 2880); if (header.find("END ") != std::string::npos) break; } for (size_t i = 0; i < header.size(); i += 80) { std::string card = header.substr(i, 80); if (card.substr(0, 3) == "END") break; std::string key = card.substr(0, 8); key.erase(key.find_last_not_of(" ") + 1); if (card[8] == '=') { std::string valueStr = card.substr(10, 70); valueStr.erase(0, valueStr.find_first_not_of(" ")); valueStr.erase(valueStr.find_last_not_of(" ") + 1); // Simple parse to string properties[key] = valueStr; } } // Read data int bitpix = std::stoi(properties["BITPIX"]); int naxis = std::stoi(properties["NAXIS"]); size_t size = std::abs(bitpix) / 8; for (int i = 1; i <= naxis; ++i) { std::string axKey = "NAXIS" + std::to_string(i); size *= std::stoi(properties[axKey]); } data.resize(size); file.read(data.data(), size); size_t pad = size % 2880; if (pad) file.ignore(2880 - pad); file.close(); } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& outputPath) { std::ofstream file(outputPath, std::ios::binary); std::string header; for (const auto& pair : properties) { std::ostringstream oss; oss << std::left << std::setw(8) << pair.first << "= " << std::setw(20) << std::right << pair.second << " / "; std::string card = oss.str().substr(0, 80); if (card.length() < 80) card += std::string(80 - card.length(), ' '); header += card; } header += std::string("END") + std::string(77, ' '); size_t pad = 2880 - (header.length() % 2880); if (pad < 2880) header += std::string(pad, ' '); file << header; if (!data.empty()) { file.write(data.data(), data.size()); size_t dataPad = 2880 - (data.size() % 2880); if (dataPad < 2880) { std::vector zeroPad(dataPad, 0); file.write(zeroPad.data(), dataPad); } } file.close(); } }; // Example usage: // int main() { // FitsHandler fits("example.fits"); // fits.printProperties(); // fits.write("output.fits"); // return 0; // } // ===== end task-226 .FITS ===== // ===== task-227 .FLAC [C++] ===== #include #include #include #include #include #include #include class FlacParser { private: std::string filepath; std::map> metadata; // Simplified string-based storage size_t audio_start = 0; uint64_t readBigEndian(const std::vector& data, size_t& offset, size_t bytes) { uint64_t val = 0; for (size_t i = 0; i < bytes; ++i) { val = (val << 8) | data[offset++]; } return val; } uint32_t readLittleEndian(const std::vector& data, size_t& offset, size_t bytes) { uint32_t val = 0; for (int i = bytes - 1; i >= 0; --i) { val = (val << 8) | data[offset + i]; } offset += bytes; return val; } public: FlacParser(const std::string& fp) : filepath(fp) { parse(); } void parse() { std::ifstream file(filepath, std::ios::binary); if (!file) return; file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(reinterpret_cast(data.data()), size); size_t offset = 0; // Stream Marker std::string marker(reinterpret_cast(data.data() + offset), 4); if (marker != "fLaC") { std::cerr << "Invalid FLAC file" << std::endl; return; } metadata["stream_marker"]["value"] = marker; offset += 4; while (true) { // Metadata Block Header uint32_t header = readBigEndian(data, offset, 4); uint8_t last_flag = (header >> 31) & 1; uint8_t type = (header >> 24) & 0x7F; uint32_t length = header & 0xFFFFFF; std::string block_key = "block_" + std::to_string(type); metadata[block_key]["last_flag"] = std::to_string(last_flag); metadata[block_key]["type"] = std::to_string(type); metadata[block_key]["length"] = std::to_string(length); if (type == 0) { // STREAMINFO uint16_t min_block = readBigEndian(data, offset, 2); uint16_t max_block = readBigEndian(data, offset, 2); uint32_t min_frame = readBigEndian(data, offset, 3); uint32_t max_frame = readBigEndian(data, offset, 3); uint32_t temp = readBigEndian(data, offset, 4); uint32_t sample_rate = temp >> 12; uint8_t channels = ((temp >> 9) & 0x7) + 1; uint8_t bps = ((temp >> 4) & 0x1F) + 1; uint64_t total_samples = ((temp & 0xF) * (1ULL << 32)) | readBigEndian(data, offset, 4); std::stringstream md5_ss; for (int i = 0; i < 16; ++i) { md5_ss << std::hex << std::setw(2) << std::setfill('0') << (int)data[offset++]; } metadata[block_key]["min_block_size"] = std::to_string(min_block); metadata[block_key]["max_block_size"] = std::to_string(max_block); metadata[block_key]["min_frame_size"] = std::to_string(min_frame); metadata[block_key]["max_frame_size"] = std::to_string(max_frame); metadata[block_key]["sample_rate"] = std::to_string(sample_rate); metadata[block_key]["channels"] = std::to_string(channels); metadata[block_key]["bits_per_sample"] = std::to_string(bps); metadata[block_key]["total_samples"] = std::to_string(total_samples); metadata[block_key]["md5"] = md5_ss.str(); } else if (type == 1) { // PADDING metadata[block_key]["padding_length"] = std::to_string(length); offset += length; } else if (type == 2) { // APPLICATION uint32_t app_id = readBigEndian(data, offset, 4); metadata[block_key]["app_id"] = std::to_string(app_id); offset += length - 4; } else if (type == 3) { // SEEKTABLE uint32_t num_points = length / 18; metadata[block_key]["num_points"] = std::to_string(num_points); for (uint32_t i = 0; i < num_points; ++i) { uint64_t sample_num = readBigEndian(data, offset, 8); uint64_t byte_offset = readBigEndian(data, offset, 8); uint16_t frame_samples = readBigEndian(data, offset, 2); // Store as string; extend for full list } } else if (type == 4) { // VORBIS_COMMENT uint32_t vendor_len = readLittleEndian(data, offset, 4); std::string vendor(reinterpret_cast(data.data() + offset), vendor_len); offset += vendor_len; uint32_t num_comments = readLittleEndian(data, offset, 4); metadata[block_key]["vendor"] = vendor; metadata[block_key]["num_comments"] = std::to_string(num_comments); for (uint32_t i = 0; i < num_comments; ++i) { uint32_t comment_len = readLittleEndian(data, offset, 4); std::string comment(reinterpret_cast(data.data() + offset), comment_len); offset += comment_len; // Store comments } } else if (type == 5) { // CUESHEET std::string catalog(reinterpret_cast(data.data() + offset), 128); offset += 128; uint64_t lead_in = readBigEndian(data, offset, 8); bool is_cd = (data[offset] & 0x80) != 0; offset += 1 + 258; uint8_t num_tracks = data[offset++]; metadata[block_key]["catalog"] = catalog; metadata[block_key]["lead_in"] = std::to_string(lead_in); metadata[block_key]["is_cd"] = std::to_string(is_cd); metadata[block_key]["num_tracks"] = std::to_string(num_tracks); offset += length - (128 + 8 + 1 + 258 + 1); } else if (type == 6) { // PICTURE uint32_t pic_type = readBigEndian(data, offset, 4); uint32_t mime_len = readBigEndian(data, offset, 4); std::string mime(reinterpret_cast(data.data() + offset), mime_len); offset += mime_len; uint32_t desc_len = readBigEndian(data, offset, 4); std::string desc(reinterpret_cast(data.data() + offset), desc_len); offset += desc_len; uint32_t width = readBigEndian(data, offset, 4); uint32_t height = readBigEndian(data, offset, 4); uint32_t depth = readBigEndian(data, offset, 4); uint32_t colors = readBigEndian(data, offset, 4); uint32_t data_len = readBigEndian(data, offset, 4); offset += data_len; metadata[block_key]["pic_type"] = std::to_string(pic_type); metadata[block_key]["mime"] = mime; metadata[block_key]["desc"] = desc; metadata[block_key]["width"] = std::to_string(width); metadata[block_key]["height"] = std::to_string(height); metadata[block_key]["depth"] = std::to_string(depth); metadata[block_key]["colors"] = std::to_string(colors); metadata[block_key]["data_len"] = std::to_string(data_len); } else { offset += length; } if (last_flag) break; } audio_start = offset; } void print_properties() { for (const auto& entry : metadata) { std::cout << entry.first << ":" << std::endl; for (const auto& prop : entry.second) { std::cout << " " << prop.first << ": " << prop.second << std::endl; } } } void write(const std::string& new_filepath) { std::ifstream src(filepath, std::ios::binary); std::ofstream dst(new_filepath, std::ios::binary); dst << src.rdbuf(); // Implement metadata updates here if needed } }; // Usage example: // int main() { // FlacParser parser("example.flac"); // parser.print_properties(); // parser.write("modified.flac"); // return 0; // } // ===== end task-227 .FLAC ===== // ===== task-228 .FLAME [C++] ===== #include #include #include #include #include class FlameFile { private: std::string filepath; xmlDocPtr doc; public: FlameFile(const std::string& fp = "") : filepath(fp), doc(nullptr) { if (!fp.empty()) { read(fp); } } ~FlameFile() { if (doc) xmlFreeDoc(doc); } void read(const std::string& fp) { doc = xmlReadFile(fp.c_str(), NULL, 0); filepath = fp; } void printProperties() { if (!doc) { std::cout << "No file loaded" << std::endl; return; } xmlNode *root = xmlDocGetRootElement(doc); if (root) { std::cout << "Flame Properties:" << std::endl; for (xmlAttr *attr = root->properties; attr; attr = attr->next) { std::cout << attr->name << ": " << attr->children->content << std::endl; } std::cout << "\nXforms:" << std::endl; int i = 1; for (xmlNode *node = root->children; node; node = node->next) { if (node->type == XML_ELEMENT_NODE && strcmp((char*)node->name, "xform") == 0) { std::cout << "Xform " << i++ << ":" << std::endl; for (xmlAttr *attr = node->properties; attr; attr = attr->next) { std::cout << " " << attr->name << ": " << attr->children->content << std::endl; } } } std::cout << "\nPalette:" << std::endl; for (xmlNode *node = root->children; node; node = node->next) { if (node->type == XML_ELEMENT_NODE && strcmp((char*)node->name, "palette") == 0) { for (xmlAttr *attr = node->properties; attr; attr = attr->next) { std::cout << " " << attr->name << ": " << attr->children->content << std::endl; } if (node->content) { std::cout << " data: " << node->content << std::endl; } } } } } void write(const std::string& fp = "") { if (!doc) { std::cout << "No data to write" << std::endl; return; } xmlSaveFormatFileEnc(fp.empty() ? filepath.c_str() : fp.c_str(), doc, "UTF-8", 1); } void addXform(const std::string& weight, const std::string& color) { if (!doc) { doc = xmlNewDoc(BAD_CAST "1.0"); xmlNodePtr root = xmlNewNode(NULL, BAD_CAST "flame"); xmlDocSetRootElement(doc, root); } xmlNodePtr root = xmlDocGetRootElement(doc); xmlNodePtr xform = xmlNewChild(root, NULL, BAD_CAST "xform", NULL); xmlNewProp(xform, BAD_CAST "weight", BAD_CAST weight.c_str()); xmlNewProp(xform, BAD_CAST "color", BAD_CAST color.c_str()); } }; // Example usage: // int main() { // FlameFile f("example.flame"); // f.printProperties(); // f.addXform("0.5", "0"); // f.write("modified.flame"); // return 0; // } // ===== end task-228 .FLAME ===== // ===== task-229 .FLP [C++] ===== #include #include #include #include #include #include // For value types (int, float, std::string, std::vector) using ValueType = std::variant>; struct Event { uint8_t id; ValueType value; }; class FLPParser { private: std::string filepath; std::vector data; struct { std::string magic; uint32_t size; int16_t format; uint16_t num_channels; uint16_t ppq; } header; struct { std::string magic; uint32_t size; } data_chunk; std::vector events; uint32_t readVarint(std::ifstream& file) { uint32_t length = 0; uint32_t shift = 0; uint8_t byte; do { file.read(reinterpret_cast(&byte), 1); length += (byte & 0x7F) << shift; shift += 7; } while (byte & 0x80); return length; } public: FLPParser(const std::string& fp) : filepath(fp) { std::ifstream file(filepath, std::ios::binary); if (!file) throw std::runtime_error("File not found"); data.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); parse(); } void parse() { size_t offset = 0; header.magic = std::string(data.begin() + offset, data.begin() + offset + 4); offset += 4; header.size = *reinterpret_cast(&data[offset]); offset += 4; header.format = *reinterpret_cast(&data[offset]); offset += 2; header.num_channels = *reinterpret_cast(&data[offset]); offset += 2; header.ppq = *reinterpret_cast(&data[offset]); offset += 2; data_chunk.magic = std::string(data.begin() + offset, data.begin() + offset + 4); offset += 4; data_chunk.size = *reinterpret_cast(&data[offset]); offset += 4; size_t end = offset + data_chunk.size; while (offset < end) { uint8_t id = data[offset++]; ValueType value; if (id <= 63) { value = static_cast(data[offset++]); } else if (id <= 127) { value = *reinterpret_cast(&data[offset]); offset += 2; } else if (id <= 191) { value = *reinterpret_cast(&data[offset]); offset += 4; } else { // Temp file stream for varint std::ifstream temp; // Dummy, since we have data uint32_t length = 0; // Implement varint read on data uint32_t shift = 0; uint8_t byte; do { byte = data[offset++]; length += (byte & 0x7F) << shift; shift += 7; } while (byte & 0x80); std::vector bytes(data.begin() + offset, data.begin() + offset + length); offset += length; try { std::string str(bytes.begin(), bytes.end()); value = str.substr(0, str.find('\0')); } catch (...) { value = bytes; } } events.push_back({id, value}); } } void printProperties() { std::cout << "Header Properties:" << std::endl; std::cout << "Magic: " << header.magic << std::endl; std::cout << "Size: " << header.size << std::endl; std::cout << "Format: " << header.format << std::endl; std::cout << "Num Channels: " << header.num_channels << std::endl; std::cout << "PPQ: " << header.ppq << std::endl; std::cout << "\nData Chunk Properties:" << std::endl; std::cout << "Magic: " << data_chunk.magic << std::endl; std::cout << "Size: " << data_chunk.size << std::endl; std::cout << "\nEvents:" << std::endl; for (const auto& e : events) { std::cout << "ID: " << static_cast(e.id) << ", Value: "; if (std::holds_alternative(e.value)) { std::cout << std::get(e.value); } else if (std::holds_alternative(e.value)) { std::cout << std::get(e.value); } else { std::cout << "[binary data]"; } std::cout << std::endl; } } void write(const std::string& newFilepath, std::optional newPpq = std::nullopt) { if (newPpq) header.ppq = *newPpq; std::ofstream file(newFilepath, std::ios::binary); file.write(header.magic.c_str(), 4); file.write(reinterpret_cast(&header.size), 4); file.write(reinterpret_cast(&header.format), 2); file.write(reinterpret_cast(&header.num_channels), 2); file.write(reinterpret_cast(&header.ppq), 2); file.write(data_chunk.magic.c_str(), 4); size_t dataPos = file.tellp() + sizeof(uint32_t); uint32_t newDataSize = 0; file.seekp(dataPos); for (const auto& e : events) { file.write(reinterpret_cast(&e.id), 1); if (e.id <= 63) { uint8_t val = std::get(e.value); file.write(reinterpret_cast(&val), 1); newDataSize += 2; } else if (e.id <= 127) { uint16_t val = std::get(e.value); file.write(reinterpret_cast(&val), 2); newDataSize += 3; } else if (e.id <= 191) { uint32_t val = std::get(e.value); file.write(reinterpret_cast(&val), 4); newDataSize += 5; } else { std::vector bytes; if (std::holds_alternative(e.value)) { std::string str = std::get(e.value); bytes.assign(str.begin(), str.end()); bytes.push_back(0); } else { bytes = std::get>(e.value); } uint32_t length = bytes.size(); std::vector varint; while (length > 0) { uint8_t byte = length & 0x7F; length >>= 7; if (length > 0) byte |= 0x80; varint.push_back(byte); } file.write(reinterpret_cast(varint.data()), varint.size()); file.write(reinterpret_cast(bytes.data()), bytes.size()); newDataSize += 1 + varint.size() + bytes.size(); } } file.seekp(dataPos - sizeof(uint32_t)); file.write(reinterpret_cast(&newDataSize), sizeof(uint32_t)); } }; // Example usage // int main() { // FLPParser parser("example.flp"); // parser.printProperties(); // parser.write("modified.flp", 480); // return 0; // } // ===== end task-229 .FLP ===== // ===== task-230 .FLV [C++] ===== #include #include #include #include #include #include #include class FLVHandler { private: std::string filepath; std::vector data; std::map> properties; // Simplified, using int64_t for values public: FLVHandler(const std::string& fp) : filepath(fp) {} void openAndDecode() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) return; auto size = file.tellg(); data.resize(size); file.seekg(0); file.read(reinterpret_cast(data.data()), size); parse(); } void parse() { size_t offset = 0; char sig[4] = {}; memcpy(sig, &data[offset], 3); offset += 3; uint8_t version = data[offset++]; uint8_t flags = data[offset++]; bool hasAudio = (flags & 0x04) >> 2; bool hasVideo = flags & 0x01; uint32_t dataOffset = (data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]; offset += 4; std::map header; header["version"] = version; header["has_audio"] = hasAudio; header["has_video"] = hasVideo; header["data_offset"] = dataOffset; properties["header"] = header; offset = dataOffset; std::vector> tags; int tagIndex = 0; while (offset < data.size()) { uint32_t prevSize = (data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]; offset += 4; if (offset >= data.size()) break; uint8_t tagByte1 = data[offset++]; int filter = (tagByte1 & 0x20) >> 5; int tagType = tagByte1 & 0x1F; uint32_t dataSize = (data[offset] << 16) | (data[offset+1] << 8) | data[offset+2]; offset += 3; uint32_t timestamp = (data[offset] << 16) | (data[offset+1] << 8) | data[offset+2]; offset += 3; uint8_t tsExt = data[offset++]; int64_t fullTs = (static_cast(tsExt) << 24) | timestamp; uint32_t streamId = (data[offset] << 16) | (data[offset+1] << 8) | data[offset+2]; offset += 3; std::map tagProps; tagProps["prev_size"] = prevSize; tagProps["filter"] = filter; tagProps["tag_type"] = tagType; tagProps["data_size"] = dataSize; tagProps["timestamp"] = fullTs; tagProps["stream_id"] = streamId; if (filter == 1) { offset += dataSize; } else if (tagType == 8) { // Audio uint8_t audioByte = data[offset++]; int soundFormat = (audioByte >> 4) & 0x0F; int soundRate = (audioByte >> 2) & 0x03; int soundSize = (audioByte >> 1) & 0x01; int soundType = audioByte & 0x01; tagProps["sound_format"] = soundFormat; tagProps["sound_rate"] = soundRate; tagProps["sound_size"] = soundSize; tagProps["sound_type"] = soundType; if (soundFormat == 10) { uint8_t aacType = data[offset++]; tagProps["aac_packet_type"] = aacType; } offset += dataSize - 1; } else if (tagType == 9) { // Video uint8_t videoByte = data[offset++]; int frameType = (videoByte >> 4) & 0x0F; int codecId = videoByte & 0x0F; tagProps["frame_type"] = frameType; tagProps["codec_id"] = codecId; if (codecId == 7) { uint8_t avcType = data[offset++]; int32_t compTime = static_cast((data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8)) >> 8; // SI24 sign extend if (compTime & 0x800000) compTime |= 0xFF000000; offset += 3; tagProps["avc_packet_type"] = avcType; tagProps["composition_time"] = compTime; } offset += dataSize - 1; } else if (tagType == 18) { offset += dataSize; } else { offset += dataSize; } tags.push_back(tagProps); tagIndex++; } // Store tags in properties (simplified, as map of maps) for (size_t i = 0; i < tags.size(); ++i) { properties["tag_" + std::to_string(i)] = tags[i]; } } void printProperties() { std::cout << "FLV Properties:" << std::endl; auto headerIt = properties.find("header"); if (headerIt != properties.end()) { std::cout << "Header:" << std::endl; for (const auto& kv : headerIt->second) { std::cout << " " << kv.first << ": " << kv.second << std::endl; } } int tagIndex = 0; while (true) { auto tagIt = properties.find("tag_" + std::to_string(tagIndex)); if (tagIt == properties.end()) break; std::cout << "Tag " << tagIndex << ":" << std::endl; for (const auto& kv : tagIt->second) { std::cout << " " << kv.first << ": " << kv.second << std::endl; } tagIndex++; } } void writeModified(const std::string& outputPath) { if (data.empty()) return; std::vector modifiedData = data; auto headerIt = properties.find("header"); if (headerIt != properties.end() && properties.find("tag_0") != properties.end()) { size_t firstTagOffset = headerIt->second["data_offset"] + 4; firstTagOffset += 1 + 3; int64_t newTs = properties["tag_0"]["timestamp"] + 1000; uint32_t newTsLower = newTs & 0xFFFFFF; uint8_t newTsExt = (newTs >> 24) & 0xFF; modifiedData[firstTagOffset] = (newTsLower >> 16) & 0xFF; modifiedData[firstTagOffset + 1] = (newTsLower >> 8) & 0xFF; modifiedData[firstTagOffset + 2] = newTsLower & 0xFF; modifiedData[firstTagOffset + 3] = newTsExt; } std::ofstream outFile(outputPath, std::ios::binary); outFile.write(reinterpret_cast(modifiedData.data()), modifiedData.size()); std::cout << "Written modified FLV to " << outputPath << std::endl; } }; // Usage example: // int main() { // FLVHandler handler("input.flv"); // handler.openAndDecode(); // handler.printProperties(); // handler.writeModified("output.flv"); // return 0; // } // ===== end task-230 .FLV ===== // ===== task-231 .FMU [C++] ===== #include #include #include #include #include // C++17 #include #include #include namespace fs = std::filesystem; class FMUHandler { private: std::string fmuPath; std::string tempDir = "fmu_temp"; std::string xmlPath = tempDir + "/modelDescription.xml"; tinyxml2::XMLDocument doc; void decode() { fs::create_directory(tempDir); unzFile uf = unzOpen(fmuPath.c_str()); if (!uf) throw std::runtime_error("Cannot open FMU"); do { char filename[256]; if (unzGetCurrentFileInfo(uf, nullptr, filename, sizeof(filename), nullptr, 0, nullptr, 0) != UNZ_OK) break; std::string dest = tempDir + "/" + filename; if (filename[strlen(filename)-1] == '/') { fs::create_directories(dest); continue; } unzOpenCurrentFile(uf); std::ofstream out(dest, std::ios::binary); char buf[4096]; int read; while ((read = unzReadCurrentFile(uf, buf, sizeof(buf))) > 0) out.write(buf, read); out.close(); unzCloseCurrentFile(uf); } while (unzGoToNextFile(uf) == UNZ_OK); unzClose(uf); if (doc.LoadFile(xmlPath.c_str()) != tinyxml2::XML_SUCCESS) { throw std::runtime_error("Cannot parse modelDescription.xml"); } } public: FMUHandler(const std::string& fmuPath) : fmuPath(fmuPath) { decode(); } std::map readProperties() { std::map props; auto root = doc.FirstChildElement("fmiModelDescription"); std::map rootAttrs; const char* attrs[] = {"fmiVersion", "modelName", "instantiationToken", "description", "author", "version", "copyright", "license", "generationTool", "generationDateAndTime", "variableNamingConvention"}; for (auto attr : attrs) { rootAttrs[attr] = root->Attribute(attr) ? root->Attribute(attr) : "N/A"; } props["root_attributes"] = rootAttrs; props["unit_definitions_count"] = countChildren(root->FirstChildElement("UnitDefinitions")); props["type_definitions_count"] = countChildren(root->FirstChildElement("TypeDefinitions")); props["log_categories_count"] = countChildren(root->FirstChildElement("LogCategories")); auto defaultExp = root->FirstChildElement("DefaultExperiment"); std::map defExpMap; const char* defAttrs[] = {"startTime", "stopTime", "tolerance", "stepSize"}; for (auto attr : defAttrs) { defExpMap[attr] = defaultExp && defaultExp->Attribute(attr) ? defaultExp->Attribute(attr) : "N/A"; } props["default_experiment"] = defExpMap; std::vector> variables; auto varElem = root->FirstChildElement("ModelVariables")->FirstChildElement(); while (varElem) { std::map varMap; const char* varAttrs[] = {"name", "valueReference", "causality", "variability", "initial"}; for (auto attr : varAttrs) { varMap[attr] = varElem->Attribute(attr) ? varElem->Attribute(attr) : "N/A"; } variables.push_back(varMap); varElem = varElem->NextSiblingElement(); } props["model_variables"] = variables; std::map structure; auto modelStruct = root->FirstChildElement("ModelStructure"); structure["outputs_count"] = countChildren(modelStruct->FirstChildElement("Outputs")); structure["continuous_state_derivatives_count"] = countChildren(modelStruct->FirstChildElement("ContinuousStateDerivatives")); structure["initial_unknowns_count"] = countChildren(modelStruct->FirstChildElement("InitialUnknowns")); props["model_structure"] = structure; std::map> interfaces; const char* types[] = {"ModelExchange", "CoSimulation", "ScheduledExecution"}; for (auto type : types) { auto el = root->FirstChildElement(type); if (el) { std::map ifMap; const char* ifAttrs[] = {"modelIdentifier", "needsExecutionTool", "canHandleVariableCommunicationStepSize", "canGetAndSetFMUState", "providesDirectionalDerivatives"}; for (auto attr : ifAttrs) { ifMap[attr] = el->Attribute(attr) ? el->Attribute(attr) : "false"; } interfaces[type] = ifMap; } } props["interface_types"] = interfaces; std::vector otherFiles; for (const auto& entry : fs::recursive_directory_iterator(tempDir)) { if (entry.is_regular_file() && entry.path().filename() != "modelDescription.xml") { otherFiles.push_back(entry.path().string()); } } props["other_files"] = otherFiles; return props; } int countChildren(tinyxml2::XMLElement* elem) { if (!elem) return 0; int count = 0; for (auto child = elem->FirstChildElement(); child; child = child->NextSiblingElement()) ++count; return count; } void printProperties() { auto props = readProperties(); std::cout << "FMU Properties:" << std::endl; // Printing logic (simplified; use recursion for maps/vectors) for (const auto& [key, value] : props) { std::cout << key << ": "; // Extend with type checks for any // Example for string map: if auto m = std::any_cast>(value); std::cout << std::endl; } } void writeProperties(const std::map& newProps) { auto root = doc.FirstChildElement("fmiModelDescription"); auto newRootAttrs = std::any_cast>(newProps.at("root_attributes")); for (const auto& [attr, val] : newRootAttrs) { root->SetAttribute(attr.c_str(), val.c_str()); } // More updates can be added doc.SaveFile(xmlPath.c_str()); std::string newFmuPath = fmuPath.substr(0, fmuPath.find_last_of('.')) + "_modified.fmu"; zipFile zf = zipOpen(newFmuPath.c_str(), APPEND_STATUS_CREATE); for (const auto& entry : fs::recursive_directory_iterator(tempDir)) { if (entry.is_regular_file()) { std::string relPath = entry.path().string().substr(tempDir.length() + 1); zip_fileinfo zi{}; zipOpenNewFileInZip(zf, relPath.c_str(), &zi, nullptr, 0, nullptr, 0, nullptr, Z_DEFLATED, Z_DEFAULT_COMPRESSION); std::ifstream in(entry.path().string(), std::ios::binary); char buf[4096]; while (in.read(buf, sizeof(buf))) zipWriteInFileInZip(zf, buf, in.gcount()); zipCloseFileInZip(zf); } } zipClose(zf, nullptr); std::cout << "Modified FMU saved to " << newFmuPath << std::endl; } ~FMUHandler() { fs::remove_all(tempDir); } }; // Usage example: // int main() { // try { // FMUHandler handler("example.fmu"); // handler.printProperties(); // std::map updates; // std::map rootUpdates = {{"description", "Updated description"}}; // updates["root_attributes"] = rootUpdates; // handler.writeProperties(updates); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-231 .FMU ===== // ===== task-232 .FNA [C++] ===== #include #include #include #include #include class FNAHandler { private: std::string filepath; struct Sequence { std::string identifier; std::string description; std::string sequence; }; std::vector sequences; std::vector staticProperties = { "Text-based (ASCII-compatible) structure", "Header lines start with '>'", "Identifier after '>', space-separated from description", "Sequence lines follow header, typically <=80 chars per line", "Allowed characters: A, C, G, T, U, R, Y, K, M, S, W, B, D, H, V, N, -", "Case-insensitive (lowercase mapped to uppercase)", "Supports multiple sequences", "No version number or binary header" }; public: FNAHandler(const std::string& fp) : filepath(fp) {} void readAndDecode() { std::ifstream file(filepath); if (!file) { std::cerr << "Error opening file." << std::endl; return; } std::string line; Sequence currentSeq; bool hasCurrent = false; while (std::getline(file, line)) { line.erase(0, line.find_first_not_of(" \t")); // trim left line.erase(line.find_last_not_of(" \t") + 1); // trim right if (line.empty()) continue; if (line[0] == '>') { if (hasCurrent) { sequences.push_back(currentSeq); } std::string header = line.substr(1); size_t spacePos = header.find(' '); currentSeq.identifier = (spacePos != std::string::npos) ? header.substr(0, spacePos) : header; currentSeq.description = (spacePos != std::string::npos) ? header.substr(spacePos + 1) : ""; currentSeq.sequence = ""; hasCurrent = true; } else if (hasCurrent) { std::transform(line.begin(), line.end(), line.begin(), ::toupper); currentSeq.sequence += line; } } if (hasCurrent) { sequences.push_back(currentSeq); } file.close(); } void printProperties() { std::cout << "Static Format Properties:" << std::endl; for (const auto& prop : staticProperties) { std::cout << "- " << prop << std::endl; } std::cout << "\nFile-Specific Parsed Properties:" << std::endl; std::cout << "Number of sequences: " << sequences.size() << std::endl; for (size_t i = 0; i < sequences.size(); ++i) { const auto& seq = sequences[i]; std::cout << "Sequence " << (i + 1) << ":" << std::endl; std::cout << " Identifier: " << seq.identifier << std::endl; std::cout << " Description: " << seq.description << std::endl; std::cout << " Length: " << seq.sequence.length() << std::endl; } } void write(const std::string& outputPath) { std::ofstream outFile(outputPath); if (!outFile) { std::cerr << "Error opening output file." << std::endl; return; } for (const auto& seq : sequences) { outFile << ">" << seq.identifier << " " << seq.description << "\n"; const std::string& seqStr = seq.sequence; for (size_t i = 0; i < seqStr.length(); i += 80) { outFile << seqStr.substr(i, 80) << "\n"; } } outFile.close(); } }; // Example usage: // int main() { // FNAHandler handler("example.fna"); // handler.readAndDecode(); // handler.printProperties(); // handler.write("output.fna"); // return 0; // } // ===== end task-232 .FNA ===== // ===== task-234 .FNX [C] ===== #include #include #include #include #include typedef struct { char* filename; char magic[5]; // null-terminated uint32_t version; time_t created; time_t modified; uint32_t num_props; struct Prop { char* name; uint8_t type; union { char* str; int32_t i32; double f64; } value; } *properties; } FNXFile; FNXFile* fnx_open(const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); FNXFile* file = malloc(sizeof(FNXFile)); file->filename = strdup(filename); int offset = 0; // Magic memcpy(file->magic, data + offset, 4); file->magic[4] = '\0'; offset += 4; if (strncmp(file->magic, "FNX\x00", 4) != 0) { free(data); free(file); return NULL; } // Version file->version = *(uint32_t*)(data + offset); offset += 4; // Timestamps (little-endian) uint64_t created_ts = *(uint64_t*)(data + offset); file->created = (time_t)created_ts; offset += 8; uint64_t modified_ts = *(uint64_t*)(data + offset); file->modified = (time_t)modified_ts; offset += 8; // Num props file->num_props = *(uint32_t*)(data + offset); offset += 4; // Properties file->properties = malloc(file->num_props * sizeof(struct Prop)); for (uint32_t i = 0; i < file->num_props; i++) { uint16_t name_len = *(uint16_t*)(data + offset); offset += 2; file->properties[i].name = malloc(name_len + 1); memcpy(file->properties[i].name, data + offset, name_len); file->properties[i].name[name_len] = '\0'; offset += name_len; file->properties[i].type = *(uint8_t*)(data + offset); offset += 1; uint32_t val_len = *(uint32_t*)(data + offset); offset += 4; if (file->properties[i].type == 0) { file->properties[i].value.str = malloc(val_len + 1); memcpy(file->properties[i].value.str, data + offset, val_len); file->properties[i].value.str[val_len] = '\0'; } else if (file->properties[i].type == 1) { file->properties[i].value.i32 = *(int32_t*)(data + offset); } else if (file->properties[i].type == 2) { file->properties[i].value.f64 = *(double*)(data + offset); } offset += val_len; } free(data); fnx_print(file); return file; } void fnx_print(FNXFile* file) { printf("Magic: %s\n", file->magic); printf("Version: %u\n", file->version); printf("Created: %s", ctime(&file->created)); printf("Modified: %s", ctime(&file->modified)); printf("Number of properties: %u\n", file->num_props); printf("Properties:\n"); for (uint32_t i = 0; i < file->num_props; i++) { printf(" %s (type %u): ", file->properties[i].name, file->properties[i].type); if (file->properties[i].type == 0) { printf("%s\n", file->properties[i].value.str); } else if (file->properties[i].type == 1) { printf("%d\n", file->properties[i].value.i32); } else if (file->properties[i].type == 2) { printf("%f\n", file->properties[i].value.f64); } else { printf("[Unknown]\n"); } } } void fnx_add_property(FNXFile* file, char* name, void* value, uint8_t type) { // Realloc and add (simplified; resize array) file->properties = realloc(file->properties, (file->num_props + 1) * sizeof(struct Prop)); struct Prop* prop = &file->properties[file->num_props]; prop->name = strdup(name); prop->type = type; if (type == 0) { prop->value.str = strdup((char*)value); } // Add cases for int/double file->num_props++; } void fnx_write(FNXFile* file, const char* output) { FILE* out = fopen(output, "wb"); if (!out) return; // Header (little-endian) fwrite("FNX\x00", 1, 4, out); fwrite(&file->version, 4, 1, out); uint64_t ts = (uint64_t)file->created; fwrite(&ts, 8, 1, out); ts = (uint64_t)file->modified; fwrite(&ts, 8, 1, out); fwrite(&file->num_props, 4, 1, out); // Properties (simplified write) for (uint32_t i = 0; i < file->num_props; i++) { struct Prop* p = &file->properties[i]; uint16_t name_len = strlen(p->name); fwrite(&name_len, 2, 1, out); fwrite(p->name, 1, name_len, out); fwrite(&p->type, 1, 1, out); uint32_t val_len = 0; // Compute based on type if (p->type == 0) val_len = strlen(p->value.str); fwrite(&val_len, 4, 1, out); if (p->type == 0) fwrite(p->value.str, 1, val_len, out); // Add cases } fclose(out); printf("Wrote to %s\n", output); } void fnx_close(FNXFile* file) { for (uint32_t i = 0; i < file->num_props; i++) { free(file->properties[i].name); if (file->properties[i].type == 0) free(file->properties[i].value.str); } free(file->properties); free(file->filename); free(file); } // Example usage: // FNXFile* f = fnx_open("example.fnx"); // fnx_add_property(f, "author", "Grok", 0); // fnx_write(f, "output.fnx"); // fnx_close(f); // ===== end task-234 .FNX ===== // ===== task-235 .FODG [C] ===== #include #include #include #include typedef struct { xmlDocPtr doc; xmlNodePtr root; } FODGHandler; FODGHandler* fodg_load(const char* file_path) { FODGHandler* handler = malloc(sizeof(FODGHandler)); handler->doc = xmlReadFile(file_path, NULL, 0); if (handler->doc == NULL) { fprintf(stderr, "Error loading file\n"); free(handler); return NULL; } handler->root = xmlDocGetRootElement(handler->doc); printf("Loaded .FODG file: %s\n", file_path); return handler; } void fodg_extract_and_print_properties(FODGHandler* handler) { if (!handler || !handler->root) return; // General printf("MIME Type: application/vnd.oasis.opendocument.graphics-flat-xml\n"); printf("Extension: .fodg\n"); xmlChar* version = xmlGetProp(handler->root, (xmlChar*)"office:version"); printf("Office Version: %s\n", version ? (char*)version : "Unknown"); xmlFree(version); // Namespaces (print first few) printf("Namespaces:\n"); for (xmlAttrPtr attr = handler->root->properties; attr; attr = attr->next) { if (attr->name && strncmp((char*)attr->name, "xmlns:", 6) == 0) { printf(" %s: %s\n", attr->name, xmlGetProp(handler->root, attr->name)); } } // Structure (use XPath for counts) xmlXPathContextPtr context = xmlXPathNewContext(handler->doc); context->node = (xmlNodePtr) handler->root; // Meta xmlXPathObjectPtr meta = xmlXPathEvalExpression((xmlChar*)"//office:meta", context); printf("Meta Present: %s\n", meta->nodesetval ? "Yes" : "No"); xmlXPathFreeObject(meta); // Styles count xmlXPathObjectPtr styles = xmlXPathEvalExpression((xmlChar*)"//style:style", context); printf("Styles Count: %d\n", styles->nodesetval ? styles->nodesetval->nodeNr : 0); xmlXPathFreeObject(styles); // Pages xmlXPathObjectPtr pages = xmlXPathEvalExpression((xmlChar*)"//draw:page", context); printf("Pages Count: %d\n", pages->nodesetval ? pages->nodesetval->nodeNr : 0); for (int i = 0; i < (pages->nodesetval ? pages->nodesetval->nodeNr : 0); i++) { xmlNodePtr page = pages->nodesetval->nodeTab[i]; xmlChar* name = xmlGetProp(page, (xmlChar*)"draw:name"); printf(" Page %d Name: %s\n", i, name ? (char*)name : "Unknown"); xmlFree(name); } xmlXPathFreeObject(pages); // Draw elements (example rect) xmlXPathObjectPtr rects = xmlXPathEvalExpression((xmlChar*)"//draw:rect", context); printf("Rect Count: %d\n", rects->nodesetval ? rects->nodesetval->nodeNr : 0); xmlXPathFreeObject(rects); // Sample attribute xmlChar* x = xmlGetProp(pages->nodesetval ? pages->nodesetval->nodeTab[0] : NULL, (xmlChar*)"svg:x"); printf("Sample Attribute svg:x: %s\n", x ? (char*)x : "None"); xmlFree(x); xmlXPathFreeContext(context); } void fodg_write(FODGHandler* handler, const char* file_path, const char* mod_version) { if (mod_version) { xmlSetProp(handler->root, (xmlChar*)"office:version", (xmlChar*)mod_version); } int success = xmlSaveFormatFileEnc(file_path, handler->doc, "UTF-8", 1); if (success != -1) { printf("Wrote .FODG file: %s\n", file_path); } else { fprintf(stderr, "Write failed\n"); } } void fodg_free(FODGHandler* handler) { if (handler) { xmlFreeDoc(handler->doc); free(handler); } } int main(int argc, char** argv) { if (argc < 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } FODGHandler* handler = fodg_load(argv[1]); if (handler) { fodg_extract_and_print_properties(handler); fodg_write(handler, "modified.fodg", "1.3"); fodg_free(handler); } xmlCleanupParser(); return 0; } // ===== end task-235 .FODG ===== // ===== task-236 .FODP [C++] ===== #include #include #include #include #include // Note: This is a simplified implementation using string parsing for key tags. // For robust XML parsing, integrate a library like TinyXML-2. class FODPHandler { private: std::string xmlContent; std::string extractAttribute(const std::string& tag, const std::string& attr) { size_t tagPos = xmlContent.find("<" + tag); if (tagPos == std::string::npos) return "N/A"; size_t attrPos = xmlContent.find(attr + "=\"", tagPos); if (attrPos == std::string::npos) return "N/A"; size_t start = attrPos + attr.length() + 2; size_t end = xmlContent.find("\"", start); return xmlContent.substr(start, end - start); } std::string extractText(const std::string& tag) { size_t startTag = xmlContent.find("<" + tag + ">"); if (startTag == std::string::npos) return "N/A"; size_t contentStart = startTag + tag.length() + 2; size_t endTag = xmlContent.find("", contentStart); return xmlContent.substr(contentStart, endTag - contentStart); } // Simplified; assumes single occurrence for most, handles multiples where needed void extractUserDefined(std::vector>& userDefs) { size_t pos = 0; while ((pos = xmlContent.find("", nameEnd) + 1; size_t contentEnd = xmlContent.find("", contentStart); std::string value = xmlContent.substr(contentStart, contentEnd - contentStart); userDefs.emplace_back(name, value); pos = contentEnd; } } std::map extractStats() { std::map stats; size_t pos = xmlContent.find("", pos); std::string attrs = xmlContent.substr(pos, end - pos); // Parse attributes simplistically size_t pagePos = attrs.find("meta:page-count=\""); if (pagePos != std::string::npos) { size_t start = pagePos + 17; size_t len = attrs.find("\"", start) - start; stats["page-count"] = attrs.substr(start, len); } // Add similar for object-count, image-count, etc. return stats; } public: FODPHandler(const std::string& filepath) { std::ifstream file(filepath); if (file) { xmlContent = std::string((std::istreambuf_iterator(file)), std::istreambuf_iterator()); } else { std::cerr << "Failed to open file." << std::endl; } } void getAndPrintProperties() { std::cout << "Extracted Properties:" << std::endl; std::cout << "Document Version: " << extractAttribute("office:document", "office:version") << std::endl; std::cout << "MIME Type: " << extractAttribute("office:document", "office:mimetype") << std::endl; std::cout << "Generator: " << extractText("meta:generator") << std::endl; std::cout << "Creation Date: " << extractText("meta:creation-date") << std::endl; std::cout << "Initial Creator: " << extractText("meta:initial-creator") << std::endl; std::cout << "Last Modified Date: " << extractText("dc:date") << std::endl; std::cout << "Last Modified By: " << extractText("dc:creator") << std::endl; std::cout << "Print Date: " << extractText("meta:print-date") << std::endl; std::cout << "Printed By: " << extractText("meta:printed-by") << std::endl; std::cout << "Title: " << extractText("dc:title") << std::endl; std::cout << "Subject: " << extractText("dc:subject") << std::endl; std::cout << "Description: " << extractText("dc:description") << std::endl; // Keywords: Find all std::string keywords; size_t kwPos = 0; while ((kwPos = xmlContent.find("", kwPos)) != std::string::npos) { size_t start = kwPos + 14; size_t end = xmlContent.find("", start); if (!keywords.empty()) keywords += ", "; keywords += xmlContent.substr(start, end - start); kwPos = end; } std::cout << "Keywords: " << (keywords.empty() ? "N/A" : keywords) << std::endl; std::cout << "Language: " << extractText("dc:language") << std::endl; std::cout << "Editing Cycles: " << extractText("meta:editing-cycles") << std::endl; std::cout << "Editing Duration: " << extractText("meta:editing-duration") << std::endl; std::vector> userDefs; extractUserDefined(userDefs); if (!userDefs.empty()) { std::cout << "User-Defined Metadata:" << std::endl; for (const auto& ud : userDefs) { std::cout << " " << ud.first << ": " << ud.second << std::endl; } } else { std::cout << "User-Defined Metadata: N/A" << std::endl; } auto stats = extractStats(); if (!stats.empty()) { std::cout << "Document Statistics:" << std::endl; std::cout << " Page Count: " << stats["page-count"] << std::endl; // Add others similarly } else { std::cout << "Document Statistics: N/A" << std::endl; } } void writeFile(const std::string& newFilepath) { std::ofstream outFile(newFilepath); if (outFile) { outFile << xmlContent; } else { std::cerr << "Failed to write file." << std::endl; } } }; // Example usage: // int main() { // FODPHandler handler("example.fodp"); // handler.getAndPrintProperties(); // handler.writeFile("modified.fodp"); // return 0; // } // ===== end task-236 .FODP ===== // ===== task-237 .FODS [C] ===== #include #include #include typedef struct { char *content; long size; } FODSHandler; void fods_read(FODSHandler *handler, const char *file_path) { FILE *file = fopen(file_path, "r"); if (!file) { printf("Error opening file\n"); return; } fseek(file, 0, SEEK_END); handler->size = ftell(file); fseek(file, 0, SEEK_SET); handler->content = malloc(handler->size + 1); fread(handler->content, 1, handler->size, file); handler->content[handler->size] = '\0'; fclose(file); if (!strstr(handler->content, "content, " office:mimetype=\"%99[^\"]\"", mime) == 1) { printf("MIME Type: %s\n", mime); } char version[10]; if (sscanf(handler->content, " office:version=\"%9[^\"]\"", version) == 1) { printf("Version: %s\n", version); } printf("Root Element: office:document\n"); printf("Encoding: UTF-8\n"); printf("XML Version: 1.0\n"); // Simple namespace extraction (first few) char *ns_ptr = strstr(handler->content, "xmlns:"); if (ns_ptr) { char ns[200]; sscanf(ns_ptr, "xmlns:%199s", ns); printf("Namespaces: %s (and others)...\n", ns); } // Child elements (grep-like for office:*) int count_office = 0; char *ptr = handler->content; while ((ptr = strstr(ptr, "content, "content; while ((ptr = strstr(ptr, "content) { printf("No document loaded\n"); return; } FILE *file = fopen(file_path, "w"); if (!file) { printf("Error writing file\n"); return; } fwrite(handler->content, 1, handler->size, file); fclose(file); printf("Written to %s\n", file_path); } void fods_free(FODSHandler *handler) { free(handler->content); handler->content = NULL; handler->size = 0; } // Usage example int main() { FODSHandler handler = {0}; fods_read(&handler, "example.fods"); fods_write(&handler, "output.fods"); fods_free(&handler); return 0; } // ===== end task-237 .FODS ===== // ===== task-238 .FODT [C] ===== #include #include #include #include typedef struct { xmlDocPtr doc; xmlNodePtr root; } FODTParser; FODTParser* fodt_parser_new(const char* file_path) { FODTParser* parser = malloc(sizeof(FODTParser)); parser->doc = xmlReadFile(file_path, "UTF-8", 0); if (parser->doc == NULL) { fprintf(stderr, "Error parsing file\n"); free(parser); return NULL; } parser->root = xmlDocGetRootElement(parser->doc); return parser; } void extract_and_print_properties(FODTParser* parser) { printf("File Extension: .fodt\n"); printf("MIME Type: application/vnd.oasis.opendocument.text-flat-xml\n"); printf("Encoding: UTF-8\n"); printf("XML Version: 1.0\n"); printf("Root Element: %s\n", parser->root->name); xmlChar* version = xmlGetProp(parser->root, (xmlChar*)"office:version"); printf("Version Attribute: %s\n", version ? (char*)version : "N/A"); xmlFree(version); // Namespaces simplified printf("Namespaces: %s\n", parser->root->ns ? (char*)parser->root->ns->href : "N/A"); xmlNodePtr child = parser->root->children; char child_list[1024] = {0}; while (child) { if (child->type == XML_ELEMENT_NODE) { strcat(child_list, (char*)child->name); strcat(child_list, ", "); } child = child->next; } printf("Required Child Elements: %s\n", child_list); xmlXPathContextPtr ctx = xmlXPathNewContext(parser->doc); xmlXPathObjectPtr title = xmlXPathEvalExpression((xmlChar*)"//dc:title", ctx); printf("Metadata Title: %s\n", title && title->nodesetval ? (char*)xmlNodeGetContent(title->nodesetval->nodeTab[0]) : "N/A"); xmlXPathFreeObject(title); // Similar for creator xmlXPathFreeContext(ctx); } void write_file(FODTParser* parser, const char* output_path) { int res = xmlSaveFormatFileEnc(output_path, parser->doc, "UTF-8", 1); if (res == -1) { fprintf(stderr, "Error writing file\n"); } } void fodt_parser_free(FODTParser* parser) { xmlFreeDoc(parser->doc); free(parser); } int main() { FODTParser* parser = fodt_parser_new("input.fodt"); if (parser) { extract_and_print_properties(parser); write_file(parser, "output.fodt"); fodt_parser_free(parser); } return 0; } // ===== end task-238 .FODT ===== // ===== task-239 .FOR [C] ===== #include #include #include #define MAX_LINES 10000 #define MAX_LINE_LEN 132 typedef struct { char filename[256]; char lines[MAX_LINES][MAX_LINE_LEN]; int num_lines; int properties[6]; // 0:total, 1:blank, 2:comment, 3:cont, 4:label, 5:max_len char violations[1024]; } FORFile; void read_file(FORFile *f) { FILE *fp = fopen(f->filename, "r"); if (!fp) { perror("Error opening file"); return; } f->num_lines = 0; while (fgets(f->lines[f->num_lines], MAX_LINE_LEN, fp) && f->num_lines < MAX_LINES - 1) { f->num_lines++; } fclose(fp); } void decode(FORFile *f) { int total = f->num_lines; int blank = 0, comment = 0, cont = 0, label = 0; int max_len = 0; char *viol = f->violations; *viol = '\0'; for (int i = 0; i < total; i++) { char *line = f->lines[i]; int len = strlen(line); if (len > 0) line[len - 1] = '\0'; // trim \n int tlen = strlen(line); max_len = (tlen > max_len) ? tlen : max_len; if (tlen == 0) { blank++; continue; } char col1 = line[0]; if (col1 == 'C' || col1 == 'c' || col1 == '*') { comment++; continue; } // label char label_buf[6]; strncpy(label_buf, line, 5); label_buf[5] = '\0'; char *end = label_buf; while (*end == ' ') end++; int is_label = 0; while (*end >= '0' && *end <= '9') end++; if (end > label_buf && *end == '\0') is_label = 1; if (is_label) label++; // cont char col6 = (tlen > 5) ? line[5] : ' '; if (col6 != ' ' && col6 != '0') cont++; if (tlen > 72) { char buf[100]; sprintf(buf, "Line %d: Length %d > 72\n", i + 1, tlen); strncat(viol, buf, sizeof(f->violations) - strlen(viol) - 1); } } f->properties[0] = total; f->properties[1] = blank; f->properties[2] = comment; f->properties[3] = cont; f->properties[4] = label; f->properties[5] = max_len; if (*f->violations == '\0') strcat(f->violations, "None"); } void write_file(FORFile *f, char *output_filename) { FILE *fp = fopen(output_filename ? output_filename : f->filename, "w"); if (!fp) { perror("Error writing file"); return; } for (int i = 0; i < f->num_lines; i++) { fprintf(fp, "%s\n", f->lines[i]); } fclose(fp); } void print_properties(FORFile *f) { printf("Total Lines: %d\n", f->properties[0]); printf("Blank Lines: %d\n", f->properties[1]); printf("Comment Lines: %d\n", f->properties[2]); printf("Continuation Lines: %d\n", f->properties[3]); printf("Label Lines: %d\n", f->properties[4]); printf("Max Line Length: %d\n", f->properties[5]); printf("Violations:\n%s\n", f->violations); } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } FORFile f; strcpy(f.filename, argv[1]); read_file(&f); decode(&f); print_properties(&f); // write_file(&f, "output.for"); return 0; } // ===== end task-239 .FOR ===== // ===== task-240 .FQL [C] ===== #include #include #include #include #include typedef struct { char* file_path; char* content; size_t content_size; char* properties[8]; // Fixed array for properties } FQLFileHandler; FQLFileHandler* fql_create(const char* file_path) { FQLFileHandler* handler = malloc(sizeof(FQLFileHandler)); handler->file_path = strdup(file_path); handler->content = NULL; handler->content_size = 0; for (int i = 0; i < 8; i++) handler->properties[i] = NULL; return handler; } void fql_free(FQLFileHandler* handler) { free(handler->file_path); free(handler->content); for (int i = 0; i < 8; i++) free(handler->properties[i]); free(handler); } int fql_read(FQLFileHandler* handler) { FILE* f = fopen(handler->file_path, "r"); if (!f) return -1; fseek(f, 0, SEEK_END); handler->content_size = ftell(f); fseek(f, 0, SEEK_SET); handler->content = malloc(handler->content_size + 1); fread(handler->content, 1, handler->content_size, f); handler->content[handler->content_size] = '\0'; fclose(f); // Extract properties (simplified) handler->properties[0] = strdup("File type: Regular text file"); handler->properties[1] = strdup("Encoding: UTF-8"); char* line_end = strstr(handler->content, "\r\n") ? "CRLF (Windows)" : "LF (Unix)"; char le[50]; sprintf(le, "Line endings: %s", line_end); handler->properties[2] = strdup(le); handler->properties[3] = strdup("MIME type: text/plain"); char sz[20]; sprintf(sz, "Size: %zu", handler->content_size); handler->properties[4] = strdup(sz); int lines = 1; for (size_t i = 0; i < handler->content_size; i++) if (handler->content[i] == '\n') lines++; char struct_str[50]; sprintf(struct_str, "Structure: %s", lines > 1 ? "Line-based FQL expressions" : "Single-line FQL"); handler->properties[5] = strdup(struct_str); struct stat st; stat(handler->file_path, &st); char perm[20]; sprintf(perm, "Permissions: %o", st.st_mode & 0777); handler->properties[6] = strdup(perm); handler->properties[7] = strdup("No indexing or fragmentation: Contiguous file on disk"); fql_print_properties(handler); return 0; } void fql_print_properties(FQLFileHandler* handler) { printf("FQL File Properties:\n"); for (int i = 0; i < 8 && handler->properties[i]; i++) { printf("%s\n", handler->properties[i]); } printf("Content preview: %.*s...\n", 500, handler->content); } int fql_write(FQLFileHandler* handler, const char* output_path) { FILE* f = fopen(output_path, "w"); if (!f) return -1; fwrite(handler->content, 1, handler->content_size, f); fclose(f); printf("Written to %s\n", output_path); return 0; } // Example usage: // int main() { // FQLFileHandler* h = fql_create("example.fql"); // if (fql_read(h) == 0) { // fql_write(h, "output.fql"); // } // fql_free(h); // return 0; // } // ===== end task-240 .FQL ===== // ===== task-241 .FRAG [C++] ===== #include #include #include #include #include #include class FragHandler { private: std::string filepath; std::string content; std::vector lines; public: FragHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::in); if (!file.is_open()) { throw std::runtime_error("Cannot open file."); } std::stringstream buffer; buffer << file.rdbuf(); content = buffer.str(); std::string line; while (std::getline(file, line)) { lines.push_back(line); } file.close(); std::cout << "File read successfully." << std::endl; } std::string extractVersion() { std::regex re(R"(#version\s+(\d+(?:\.\d+)?)\s*(core|compatibility|es)?)", std::regex::icase); std::smatch match; if (std::regex_search(content, match, re)) { return match[1].str() + (match[2].matched ? " " + match[2].str() : ""); } return "Not specified"; } std::string extractExtensions() { std::regex re(R"(#extension\s+([^:]+):?\s*(enable|require|warn|disable)?)", std::regex::icase); std::sregex_iterator iter(content.begin(), content.end(), re); std::sregex_iterator end; std::stringstream ss; for (; iter != end; ++iter) { ss << "#extension " << iter->str(1) << " " << (iter->str(2).empty() ? "" : iter->str(2)) << "\n"; } std::string res = ss.str(); return res.empty() ? "None" : res; } std::string extractPrecision() { std::regex re(R"(^precision\s+(lowp|mediump|highp)\s+(float|int);$)", std::regex::icase); std::vector matches; for (const auto& line : lines) { std::smatch m; if (std::regex_match(line, m, re)) { matches.push_back(line); } } if (matches.empty()) return "Default (highp float)"; std::stringstream ss; for (const auto& m : matches) ss << m << "\n"; return ss.str(); } std::string extractUniforms() { std::regex re(R"(^uniform\s+\w+\s+\w+;)", std::regex::icase); std::vector matches; for (const auto& line : lines) { std::smatch m; if (std::regex_search(line, m, re)) { matches.push_back(line); } } if (matches.empty()) return "None"; std::stringstream ss; for (const auto& m : matches) ss << m << "\n"; return ss.str(); } std::string extractInputs() { std::regex re(R"(^in\s+\w+\s+\w+;)", std::regex::icase); std::vector matches; for (const auto& line : lines) { std::smatch m; if (std::regex_search(line, m, re)) { matches.push_back(line); } } if (matches.empty()) return "None"; std::stringstream ss; for (const auto& m : matches) ss << m << "\n"; return ss.str(); } std::string extractOutputs() { std::regex re(R"(^out\s+\w+\s+\w+;)", std::regex::icase); std::vector matches; for (const auto& line : lines) { std::smatch m; if (std::regex_search(line, m, re)) { matches.push_back(line); } } if (matches.empty()) return "None"; std::stringstream ss; for (const auto& m : matches) ss << m << "\n"; return ss.str(); } std::string extractBuiltins() { std::vector builtins = {"gl_FragCoord", "gl_FragDepth", "gl_FrontFacing", "gl_PointCoord"}; std::vector used; for (const auto& b : builtins) { if (content.find(b) != std::string::npos) { used.push_back(b); } } if (used.empty()) return "None"; std::stringstream ss; for (size_t i = 0; i < used.size(); ++i) { ss << used[i]; if (i < used.size() - 1) ss << ", "; } return ss.str(); } std::string extractFunctions() { std::regex re(R"(\w+\s+\w+\s*\([^)]*\)\s*\{[^}]*\})"); std::sregex_iterator iter(content.begin(), content.end(), re); std::sregex_iterator end; std::vector funcs; for (; iter != end && funcs.size() < 5; ++iter) { funcs.push_back(iter->str().substr(0, 30) + "(...)"); // Truncate for display } if (funcs.empty()) return "None"; std::stringstream ss; for (const auto& f : funcs) ss << f << "\n"; if (std::distance(std::sregex_iterator(content.begin(), content.end(), re), end) > 5) ss << "... (truncated)"; return ss.str(); } std::string extractMain() { std::regex re(R"(void\s+main\s*\([^)]*\)\s*\{([^}]*)\})", std::regex::icase); std::smatch match; if (std::regex_search(content, match, re)) { return match[1].str(); } return "Not found"; } void printProperties() { if (content.empty()) read(); std::cout << "=== .FRAG Properties ===" << std::endl; std::cout << "GLSL Version: " << extractVersion() << std::endl; std::cout << "Extensions: " << extractExtensions() << std::endl; std::cout << "Precision Qualifiers: " << extractPrecision() << std::endl; std::cout << "Uniforms: " << extractUniforms() << std::endl; std::cout << "Input Variables (in): " << extractInputs() << std::endl; std::cout << "Output Variables (out): " << extractOutputs() << std::endl; std::cout << "Built-in Variables: " << extractBuiltins() << std::endl; std::cout << "Custom Functions: " << extractFunctions() << std::endl; std::cout << "Main Function Body: " << extractMain() << std::endl; std::cout << "Encoding/Line Endings: UTF-8 / LF (assumed)" << std::endl; std::cout << "MIME Type: text/plain" << std::endl; std::cout << "File Size Constraints: None formal" << std::endl; std::cout << "======================" << std::endl; } void write(const std::string& outputPath) { if (content.empty()) throw std::runtime_error("Content not loaded. Call read() first."); std::ofstream file(outputPath); if (!file.is_open()) { throw std::runtime_error("Cannot write file."); } file << content; file.close(); std::cout << "File written to " << outputPath << "." << std::endl; } }; int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "Usage: ./frag_handler " << std::endl; return 1; } try { FragHandler handler(argv[1]); handler.read(); handler.printProperties(); handler.write("output.frag"); // Writes a copy } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } // ===== end task-241 .FRAG ===== // ===== task-242 .FREQ [C] ===== #include #include #include typedef struct { char* filepath; char* header; char* alphabet; int num_nodes; char*** node_ids; // array of strings double*** transitions; // 9 per node double*** match_em; double*** insert_em; int end_marker; double* lett_count; double* freq_ave; } FreqFile; FreqFile* freqfile_new(const char* filepath) { FreqFile* f = malloc(sizeof(FreqFile)); f->filepath = strdup(filepath); f->header = NULL; f->alphabet = NULL; f->num_nodes = 0; f->node_ids = NULL; f->transitions = NULL; f->match_em = NULL; f->insert_em = NULL; f->end_marker = 0; f->lett_count = NULL; f->freq_ave = NULL; return f; } void freqfile_free(FreqFile* f) { free(f->filepath); free(f->header); free(f->alphabet); for (int i = 0; i < f->num_nodes; i++) { free(f->node_ids[i]); for (int j = 0; j < 9; j++) free(f->transitions[i][j]); // Similar for match_em, insert_em based on alphabet } free(f->node_ids); // Free other arrays free(f); } void freqfile_read(FreqFile* f) { FILE* fp = fopen(f->filepath, "r"); if (!fp) { printf("File not found: %s\n", f->filepath); return; } char line[1024]; fgets(line, sizeof(line), fp); if (strncmp(line, "FREQUENCIES", 11) == 0) f->header = strdup("FREQUENCIES"); // Parse alphabet if (fgets(line, sizeof(line), fp)) { if (strncmp(line, "alphabet ", 9) == 0) { f->alphabet = strdup(line + 9); f->alphabet[strlen(f->alphabet) - 1] = '\0'; // trim newline } else { ungetc('\n', fp); // push back } } // Parse node lines (simplified, assume DNA for 4 emissions) int alphabet_size = (f->alphabet && strcmp(f->alphabet, "PROTEIN") == 0) ? 20 : 4; f->num_nodes = 0; while (fgets(line, sizeof(line), fp)) { if (strncmp(line, "ENDFREQUENCIES", 14) == 0) { f->end_marker = 1; break; } if (strncmp(line, "LETTCOUNT", 9) == 0) { // Parse lett_count continue; } if (strncmp(line, "FREQAVE", 7) == 0) { // Parse freq_ave continue; } // Parse node line f->num_nodes++; // Realloc arrays and parse parts (omitted for brevity, use strtok for fields) // Assume parsing into transitions (9 doubles), match_em (alphabet_size), insert_em (alphabet_size) } fclose(fp); freqfile_print_properties(f); } void freqfile_print_properties(FreqFile* f) { printf("Properties:\n"); printf("Encoding: ascii\n"); printf("Header: %s\n", f->header ? "Present" : "Missing"); printf("Alphabet: %s\n", f->alphabet ? f->alphabet : "Unknown"); printf("Number of node lines: %d\n", f->num_nodes); // Print node details (omitted for brevity) printf("End marker: %s\n", f->end_marker ? "Present" : "Missing"); // Print lett_count and freq_ave if present } void freqfile_write(FreqFile* f, const char* output) { FILE* fp = fopen(output, "w"); fprintf(fp, "FREQUENCIES\n"); if (f->alphabet) fprintf(fp, "alphabet %s\n", f->alphabet); // Write node lines (omitted for brevity) fprintf(fp, "ENDFREQUENCIES\n"); // Write optional sections fclose(fp); printf("Written to %s\n", output); } // Example usage: // FreqFile* f = freqfile_new("example.FREQ"); // freqfile_read(f); // freqfile_write(f, "output.FREQ"); // freqfile_free(f); // ===== end task-242 .FREQ ===== // ===== task-243 .FRM [C] ===== #include #include #include #include typedef struct { uint16_t magic; uint8_t frm_version; uint8_t legacy_db_type; uint16_t names_length; uint16_t io_size; uint16_t num_forms; uint32_t unused_alignment; uint16_t tmp_key_length; uint16_t rec_length; uint32_t max_rows; uint32_t min_rows; uint8_t unused_flag; uint8_t long_pack_fields; uint16_t key_info_length; uint16_t table_options; uint8_t unused_filename; uint8_t mark_50; uint32_t avg_row_length; uint8_t default_charset; uint8_t unused_transactional; uint8_t row_format; uint8_t unused_raid_type; uint8_t unused_raid_chunks; uint32_t unused_raid_chunk_size; uint32_t ext_key_info_length; uint32_t mysql_version; uint32_t extra_info_size; // Forminfo uint16_t column_count; uint16_t screens_length; uint16_t null_columns; uint16_t names_length_form; uint16_t interval_length; uint16_t comments_length; } FrmProperties; typedef struct { uint8_t *data; size_t size; } FrmData; FrmData *frm_load(const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); FrmData *fd = malloc(sizeof(FrmData)); fd->data = data; fd->size = size; return fd; } void frm_free(FrmData *fd) { free(fd->data); free(fd); } void frm_read_properties(FrmData *fd, FrmProperties *props) { uint8_t *d = fd->data; // Little-endian reads props->magic = (d[0] << 8) | d[1]; props->frm_version = d[2]; props->legacy_db_type = d[3]; props->names_length = (d[4] << 8) | d[5]; props->io_size = (d[6] << 8) | d[7]; props->num_forms = (d[8] << 8) | d[9]; props->unused_alignment = (d[10] << 24) | (d[11] << 16) | (d[12] << 8) | d[13]; props->tmp_key_length = (d[14] << 8) | d[15]; props->rec_length = (d[16] << 8) | d[17]; props->max_rows = (d[18] << 24) | (d[19] << 16) | (d[20] << 8) | d[21]; props->min_rows = (d[22] << 24) | (d[23] << 16) | (d[24] << 8) | d[25]; props->unused_flag = d[26]; props->long_pack_fields = d[27]; props->key_info_length = (d[28] << 8) | d[29]; props->table_options = (d[30] << 8) | d[31]; props->unused_filename = d[32]; props->mark_50 = d[33]; props->avg_row_length = (d[34] << 24) | (d[35] << 16) | (d[36] << 8) | d[37]; props->default_charset = d[38]; props->unused_transactional = d[39]; props->row_format = d[40]; props->unused_raid_type = d[41]; props->unused_raid_chunks = d[42]; props->unused_raid_chunk_size = (d[43] << 24) | (d[44] << 16) | (d[45] << 8) | d[46]; props->ext_key_info_length = (d[47] << 24) | (d[48] << 16) | (d[49] << 8) | d[50]; props->mysql_version = (d[51] << 24) | (d[52] << 16) | (d[53] << 8) | d[54]; props->extra_info_size = (d[55] << 24) | (d[56] << 16) | (d[57] << 8) | d[58]; // Forminfo at 64 int offset = 64; props->column_count = (d[offset + 258] << 8) | d[offset + 259]; props->screens_length = (d[offset + 260] << 8) | d[offset + 261]; props->null_columns = (d[offset + 282] << 8) | d[offset + 283]; props->names_length_form = (d[offset + 268] << 8) | d[offset + 269]; props->interval_length = (d[offset + 274] << 8) | d[offset + 275]; props->comments_length = (d[offset + 284] << 8) | d[offset + 285]; // Print to console printf("Magic: 0x%04X\n", props->magic); printf("FRM Version: %u\n", props->frm_version); // ... (print all; omitted for brevity) printf("Column Count: %u\n", props->column_count); } void frm_write(const char *filename, FrmData *fd, FrmProperties *props) { if (props == NULL) { // Copy FILE *f = fopen(filename, "wb"); fwrite(fd->data, 1, fd->size, f); fclose(f); } else { // Reconstruct minimal uint8_t *out = malloc(64 + 288); // Pack (little-endian) out[0] = (props->magic >> 8) & 0xFF; out[1] = props->magic & 0xFF; out[2] = props->frm_version; // ... (pack all) out[47] = (props->ext_key_info_length >> 24) & 0xFF; // ... FILE *f = fopen(filename, "wb"); fwrite(out, 1, 64 + 288, f); fclose(f); free(out); } printf("Wrote to %s\n", filename); } // Usage // FrmData *fd = frm_load("sample.frm"); // FrmProperties props = {0}; // frm_read_properties(fd, &props); // frm_write("output.frm", fd, &props); // frm_free(fd); // ===== end task-243 .FRM ===== // ===== task-244 .FRQ7 [C] ===== #include #include #include #include #include // For le32toh, etc.; fallback for non-GNU typedef struct { float freq, mag, phase; } Point; typedef struct { uint8_t magic[4]; uint8_t version; uint8_t reserved[3]; uint32_t num_points; float sampling_rate; Point* data; } FRQ7File; FRQ7File* frq7_create() { FRQ7File* f = malloc(sizeof(FRQ7File)); memcpy(f->magic, "FRQ7", 4); f->version = 7; memset(f->reserved, 0, 3); f->num_points = 0; f->sampling_rate = 0.0f; f->data = NULL; return f; } void frq7_free(FRQ7File* f) { if (f->data) free(f->data); free(f); } void frq7_read(FRQ7File* f, const char* filename) { FILE* fp = fopen(filename, "rb"); if (!fp) { perror("fopen"); return; } fread(f->magic, 1, 4, fp); if (memcmp(f->magic, "FRQ7", 4)) { fprintf(stderr, "Invalid magic\n"); fclose(fp); return; } fread(&f->version, 1, 1, fp); if (f->version != 7) { fprintf(stderr, "Unsupported version: %d\n", f->version); fclose(fp); return; } fread(f->reserved, 1, 3, fp); if (f->reserved[0] || f->reserved[1] || f->reserved[2]) { fprintf(stderr, "Reserved non-zero\n"); fclose(fp); return; } fread(&f->num_points, 4, 1, fp); f->num_points = le32toh(f->num_points); fread(&f->sampling_rate, 4, 1, fp); f->sampling_rate = __builtin_bswap32(*(uint32_t*)&f->sampling_rate) * (1.0f / (1 << 23)) * (256.0f - (128.0f / 256.0f)); // Simple LE float swap approx f->data = malloc(f->num_points * sizeof(Point)); for (uint32_t i = 0; i < f->num_points; i++) { fread(&f->data[i], 12, 1, fp); // Assumes LE; adjust if big-endian host // Swap floats if needed: similar to above for each } fclose(fp); frq7_print(f); } void frq7_write(FRQ7File* f, const char* filename, float sampling_rate, Point* data, uint32_t num_points) { f->sampling_rate = sampling_rate; f->num_points = num_points; if (f->data) free(f->data); f->data = malloc(num_points * sizeof(Point)); memcpy(f->data, data, num_points * sizeof(Point)); FILE* fp = fopen(filename, "wb"); if (!fp) { perror("fopen"); return; } fwrite(f->magic, 1, 4, fp); fwrite(&f->version, 1, 1, fp); fwrite(f->reserved, 1, 3, fp); uint32_t np_le = htole32(num_points); fwrite(&np_le, 4, 1, fp); // Swap float to LE if needed uint32_t sr_le = htole32(*(uint32_t*)&sampling_rate); fwrite(&sr_le, 4, 1, fp); for (uint32_t i = 0; i < num_points; i++) { fwrite(&f->data[i], 12, 1, fp); // Swap each float to LE if needed } fclose(fp); } void frq7_print(FRQ7File* f) { printf("Version: %d\n", f->version); printf("Num Points: %u\n", f->num_points); printf("Sampling Rate: %.2f Hz\n", f->sampling_rate); printf("Data Points:\n"); for (uint32_t i = 0; i < f->num_points; i++) { printf(" Point %u: Freq=%.2f, Mag=%.2f, Phase=%.2f\n", i, f->data[i].freq, f->data[i].mag, f->data[i].phase); } } int main(int argc, char** argv) { if (argc < 3) { fprintf(stderr, "Usage: %s [read|write] file.frq7\n", argv[0]); return 1; } FRQ7File* f = frq7_create(); if (strcmp(argv[1], "read") == 0) { frq7_read(f, argv[2]); } else if (strcmp(argv[1], "write") == 0) { // Prompt for data, etc.; omitted for brevity printf("Write mode: Implement data input here.\n"); } frq7_free(f); return 0; } // ===== end task-244 .FRQ7 ===== // ===== task-245 .FS [C] ===== #include #include #include typedef struct { char **names; char **props; int count; } FSAttributes; FSAttributes *parse_header(const char *content) { FSAttributes *attrs = malloc(sizeof(FSAttributes)); attrs->names = NULL; attrs->props = NULL; attrs->count = 0; char *lines[1000]; // Assume max 1000 lines int line_count = 0; char *token = strtok((char *)content, "\n"); while (token && line_count < 1000) { lines[line_count++] = token; token = strtok(NULL, "\n"); } int i = 0; if (line_count > 0 && strncmp(lines[i], "@E ", 3) == 0) i++; // Simple parsing: collect @ lines char *header[100]; // Assume max 100 header lines int header_count = 0; while (i < line_count && strlen(lines[i]) > 0) { if (lines[i][0] == '@') { header[header_count++] = lines[i]; } i++; } // Parse header to attributes (simplified: one prop per attr for brevity) attrs->count = header_count; attrs->names = malloc(sizeof(char *) * attrs->count); attrs->props = malloc(sizeof(char *) * attrs->count); for (int j = 0; j < header_count; j++) { char *line = header[j]; if (strncmp(line, "@L ", 3) == 0) { // Simplified: treat as 'L' attrs->names[j] = strdup(line + 3); // Name only attrs->props[j] = strdup("L"); } else { attrs->names[j] = strdup(line + 3); attrs->props[j] = malloc(2); snprintf(attrs->props[j], 2, "%c", line[1]); } } return attrs; } void print_properties(FSAttributes *attrs) { for (int j = 0; j < attrs->count; j++) { printf("Attribute '%s': %s\n", attrs->names[j], attrs->props[j]); } } void write_file(const char *content, const char *output_filename) { FILE *f = fopen(output_filename, "w"); if (f) { fputs(content, f); fclose(f); printf("Written to %s\n", output_filename); } } void free_attrs(FSAttributes *attrs) { for (int j = 0; j < attrs->count; j++) { free(attrs->names[j]); free(attrs->props[j]); } free(attrs->names); free(attrs->props); free(attrs); } // Example usage: // int main() { // FILE *f = fopen("example.fs", "r"); // fseek(f, 0, SEEK_END); // long size = ftell(f); // fseek(f, 0, SEEK_SET); // char *content = malloc(size + 1); // fread(content, 1, size, f); // content[size] = '\0'; // fclose(f); // FSAttributes *attrs = parse_header(content); // print_properties(attrs); // write_file(content, "output.fs"); // free_attrs(attrs); // free(content); // return 0; // } // ===== end task-245 .FS ===== // ===== task-246 .FTH [C] ===== #include #include #include #include typedef struct { xmlDocPtr doc; char* filename; } FTHDecoder; FTHDecoder* fth_new(const char* filename) { FTHDecoder* self = malloc(sizeof(FTHDecoder)); self->filename = strdup(filename); self->doc = xmlReadFile(filename, NULL, 0); if (!self->doc) { fprintf(stderr, "Invalid .FTH\n"); free(self); return NULL; } xmlNodePtr root = xmlDocGetRootElement(self->doc); if (strcmp((char*)root->name, "FMTHEMES") != 0) { fprintf(stderr, "Invalid root\n"); xmlFreeDoc(self->doc); free(self); return NULL; } return self; } void fth_print_properties(FTHDecoder* self) { if (!self) return; printf("=== .FTH Properties ===\n"); xmlNodePtr cur = self->doc->children; xmlNodePtr theme; int i = 1; for (cur = cur->children; cur; cur = cur->next) { if (cur->type == XML_ELEMENT_NODE && strcmp((char*)cur->name, "FMTHEME") == 0) { printf("\nTheme %d:\n", i++); // Name xmlNodePtr name = NULL; for (xmlNodePtr child = cur->children; child; child = child->next) { if (child->type == XML_ELEMENT_NODE && strcmp((char*)child->name, "THEMENAME") == 0) { name = child; break; } } if (name) { xmlChar* val = xmlGetProp(name, (xmlChar*)"VALUE"); xmlChar* hint = xmlGetProp(name, (xmlChar*)"HINT"); printf("- Name: %s (Hint: %s)\n", val ? (char*)val : "unknown", hint ? (char*)hint : "none"); xmlFree(val); xmlFree(hint); } // Version, Default similar... // Parts example for BODY xmlNodePtr body = NULL; for (xmlNodePtr child = cur->children; child; child = child->next) { if (child->type == XML_ELEMENT_NODE && strcmp((char*)child->name, "BODYPART") == 0) { body = child; break; } } if (body) { printf("\n Body Part:\n"); xmlNodePtr fill = NULL; for (xmlNodePtr ch = body->children; ch; ch = ch->next) { if (ch->type == XML_ELEMENT_NODE && strcmp((char*)ch->name, "FILL") == 0) { fill = ch; break; } } if (fill) { xmlChar* color = xmlGetProp(fill, (xmlChar*)"COLOR"); xmlChar* pat = xmlGetProp(fill, (xmlChar*)"PATTERN"); printf(" Fill - Color: %s, Pattern: %s\n", color ? (char*)color : "none", pat ? (char*)pat : "none"); xmlFree(color); xmlFree(pat); } // Text, Field similar traversal... } } } } void fth_write(FTHDecoder* self, const char* output, const char* modify_color) { if (modify_color) { // Modify first FILL color (simplified traversal) xmlNodePtr fill = NULL; // Find first FILL... if (fill) xmlSetProp(fill, (xmlChar*)"COLOR", (xmlChar*)modify_color); } xmlSaveFormatFileEnc(output, self->doc, "UTF-8", 1); printf("Wrote to %s\n", output); } void fth_free(FTHDecoder* self) { if (self) { xmlFreeDoc(self->doc); free(self->filename); free(self); } } int main() { FTHDecoder* decoder = fth_new("example.fth"); if (decoder) { fth_print_properties(decoder); fth_write(decoder, "modified.fth", "red"); fth_free(decoder); } return 0; } // ===== end task-246 .FTH ===== // ===== task-247 .G4 [C] ===== #include #include #include #include typedef struct { char byte_order[3]; uint16_t version; uint32_t ifd_offset; uint16_t num_tags; // Add other properties as needed uint32_t image_width; uint32_t image_length; uint16_t bits_per_sample; uint16_t compression; uint16_t photometric; uint16_t fill_order; uint16_t samples_per_pixel; uint32_t rows_per_strip; uint32_t strip_offsets; uint32_t strip_byte_counts; uint32_t t6_options; } G4Properties; typedef struct { uint8_t* data; size_t size; G4Properties props; } G4File; void parse_g4(G4File* g4) { if (g4->size < 8) { fprintf(stderr, "File too short\n"); return; } memcpy(g4->props.byte_order, g4->data, 2); g4->props.byte_order[2] = '\0'; int little_endian = (g4->props.byte_order[0] == 'I' && g4->props.byte_order[1] == 'I'); g4->props.version = little_endian ? *(uint16_t*)(g4->data + 2) : __builtin_bswap16(*(uint16_t*)(g4->data + 2)); if (g4->props.version != 42) { fprintf(stderr, "Not a TIFF file\n"); return; } g4->props.ifd_offset = little_endian ? *(uint32_t*)(g4->data + 4) : __builtin_bswap32(*(uint32_t*)(g4->data + 4)); uint16_t* ifd_ptr = (uint16_t*)(g4->data + g4->props.ifd_offset); g4->props.num_tags = little_endian ? *ifd_ptr : __builtin_bswap16(*ifd_ptr); // Simplified tag parsing (assume offsets correct, little_endian) // For full impl, loop over tags and extract // Dummy extraction for key tags (in real, parse each 12-byte tag) g4->props.image_width = 100; // Placeholder; implement full parse // ... similarly for others // Print printf("Byte Order: %s\n", g4->props.byte_order); printf("TIFF Version: %d\n", g4->props.version); printf("IFD Offset: %u\n", g4->props.ifd_offset); printf("Number of Tags: %d\n", g4->props.num_tags); printf("Image Width: %u\n", g4->props.image_width); // ... print all } void print_properties(G4File* g4) { // Print all props } void write_g4(const char* filename, uint32_t width, uint32_t height) { // Minimal writer with dummy data FILE* f = fopen(filename, "wb"); if (!f) return; // Header fwrite("II", 1, 2, f); uint16_t ver = 42; fwrite(&ver, 2, 1, f); uint32_t ifd_off = 8; fwrite(&ifd_off, 4, 1, f); // IFD and dummy G4 (simplified) uint8_t dummy[] = {0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01}; fwrite(dummy, 1, sizeof(dummy), f); fclose(f); } G4File* load_g4(const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); G4File* g4 = malloc(sizeof(G4File)); g4->data = data; g4->size = size; parse_g4(g4); return g4; } void free_g4(G4File* g4) { free(g4->data); free(g4); } // Usage // G4File* g4 = load_g4("sample.g4"); // print_properties(g4); // write_g4("output.g4", 200, 200); // free_g4(g4); // ===== end task-247 .G4 ===== // ===== task-248 .G8 [C] ===== #include #include #include typedef struct { int n; int k; int num_edges; int* edges; // Flattened: [i1, j1, i2, j2, ...] int edges_count; char* encoded_str; } G6File; int decode_n(const char* str) { int b = (unsigned char)str[0] - 63; if (b < 63) return b; char bits[19] = {0}; for (int i = 1; i <= 3; i++) { int y = (unsigned char)str[i] - 63; char buf[7]; sprintf(buf, "%06d", y); // Binary padded // Manual bin: for simplicity, assume helper for (int j = 0; j < 6; j++) { bits[(i-1)*6 + j] = ((y >> (5 - j)) & 1) + '0'; } } bits[18] = 0; return (int)strtol(bits, NULL, 2); } int get_n_length(int n) { return n < 63 ? 1 : 4; } void decode_bits(const char* encoded, char* bit_str, int max_len) { int idx = 0; for (int i = 0; encoded[i] && idx < max_len * 6; i++) { // Approx int y = (unsigned char)encoded[i] - 63; for (int j = 0; j < 6; j++) { if (idx < max_len) { bit_str[idx++] = ((y >> (5 - j)) & 1) + '0'; } } } bit_str[idx < max_len ? idx : max_len] = 0; } void extract_edges(char* bit_str, int n, int** edges, int* count) { *count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int idx = 0; for (int r = 0; r < i; r++) idx += n - 1 - r; idx += j - i - 1; if (bit_str[idx] == '1') (*count)++; } } *edges = malloc((*count) * 2 * sizeof(int)); int pos = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int idx = 0; for (int r = 0; r < i; r++) idx += n - 1 - r; idx += j - i - 1; if (bit_str[idx] == '1') { (*edges)[pos++] = i; (*edges)[pos++] = j; } } } } G6File* g6_open(const char* filename) { FILE* f = fopen(filename, "r"); if (!f) return NULL; fseek(f, 0, SEEK_END); long len = ftell(f); fseek(f, 0, SEEK_SET); char* content = malloc(len + 1); fread(content, 1, len, f); content[len] = 0; fclose(f); if (strncmp(content, ">>graph6<<", 9) == 0) { memmove(content, content + 8, len - 8); } char* line = strtok(content, "\n"); G6File* g6 = malloc(sizeof(G6File)); g6->encoded_str = strdup(line); g6->n = decode_n(line); g6->k = g6->n * (g6->n - 1) / 2; char* bit_str = malloc(g6->k + 1); decode_bits(line + get_n_length(g6->n), bit_str, g6->k); g6->num_edges = 0; for (int i = 0; i < g6->k; i++) if (bit_str[i] == '1') g6->num_edges++; extract_edges(bit_str, g6->n, &g6->edges, &g6->edges_count); free(bit_str); free(content); return g6; } void g6_print_properties(G6File* g6) { printf("Number of vertices: %d\n", g6->n); printf("Bit vector length: %d\n", g6->k); printf("Number of edges: %d\n", g6->num_edges); printf("Edges: "); for (int i = 0; i < g6->edges_count * 2; i += 2) { printf("(%d,%d) ", g6->edges[i], g6->edges[i+1]); } printf("\nRaw encoded: %s\n", g6->encoded_str); } void g6_write(G6File* g6, const char* output_filename, int custom_n, int* custom_edges, int custom_count) { int write_n = custom_n ? custom_n : g6->n; int* write_edges = custom_edges ? custom_edges : g6->edges; int write_count = custom_count ? custom_count : g6->edges_count; int write_k = write_n * (write_n - 1) / 2; char* bit_str = calloc(write_k, 1); for (int e = 0; e < write_count; e++) { int i = write_edges[e * 2], j = write_edges[e * 2 + 1]; int idx = 0; for (int r = 0; r < i; r++) idx += write_n - 1 - r; idx += j - i - 1; bit_str[idx] = '1'; } // Pad and R(x) - simplified, implement similarly to decode // ... (full impl for encode similar to Python, omitted for brevity; use loops for 6-bit groups) // Write to file: fopen, fprintf encoded + \n // Free resources } void g6_free(G6File* g6) { free(g6->encoded_str); free(g6->edges); free(g6); } // Usage: G6File* g6 = g6_open("example.g6"); g6_print_properties(g6); g6_free(g6); // ===== end task-248 .G8 ===== // ===== task-249 .GB [C] ===== #include #include #include typedef struct { char locus_name[17]; char length[10]; char type[10]; char division[4]; char date[12]; char definition[1024]; char accession[20]; char version[20]; char gi[20]; char keywords[256]; char source[512]; char organism[512]; char* references; // Simplified as single string // Features as array (simplified) struct Feature { char key[20]; char location[100]; char qualifiers[10][100]; // Up to 10 quals int num_quals; } features[100]; int num_features; char base_count[256]; char origin[20]; char* sequence; } GBProperties; void parse_gb(const char* filename, GBProperties* props) { FILE* fp = fopen(filename, "r"); if (!fp) { printf("Error opening %s\n", filename); return; } char line[1024]; props->num_features = 0; while (fgets(line, sizeof(line), fp)) { if (strncmp(line, "LOCUS ", 6) == 0) { sscanf(line, "LOCUS %16s %9s %9s %3s %11s", props->locus_name, props->length, props->type, props->division, props->date); } else if (strncmp(line, "DEFINITION ", 11) == 0) { strncpy(props->definition, line + 11, sizeof(props->definition) - 1); // Multi-line simplified } // Similar sscanf for other sections... // For features: else if (strncmp(line, "FEATURES", 8) == 0) { while (fgets(line, sizeof(line), fp) && strncmp(line, "ORIGIN", 6) != 0) { if (sscanf(line, "%*5c%19s", props->features[props->num_features].key) == 1) { // Parse loc and quals (simplified) strcpy(props->features[props->num_features].location, line + 21); props->num_features++; } } } } fclose(fp); } void print_properties(const GBProperties* props) { printf("=== GenBank Properties ===\n"); printf("Locus: %s\n", props->locus_name); printf("Length: %s\n", props->length); printf("Definition: %s\n", props->definition); // ... print others for (int i = 0; i < props->num_features; i++) { printf("Feature: %s %s\n", props->features[i].key, props->features[i].location); } } void write_gb(const GBProperties* props, const char* output) { FILE* out = fopen(output, "w"); if (out) { fprintf(out, "LOCUS %s %s %s %s %s\n", props->locus_name, props->length, props->type, props->division, props->date); // ... add others fprintf(out, "//\n"); fclose(out); } } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } GBProperties props = {0}; parse_gb(argv[1], &props); print_properties(&props); // write_gb(&props, "out.gb"); free(props.sequence); // If allocated return 0; } // ===== end task-249 .GB ===== // ===== task-250 .GBK [C++] ===== #include #include #include #include #include class GBKHandler { private: std::map sections; public: void read(const std::string& filepath) { std::ifstream file(filepath); if (!file.is_open()) return; std::string line; std::string currentSection; std::regex pattern(R"(^([A-Z]+)\s*(.*)$)"); while (std::getline(file, line)) { std::string trimmed = line; trimmed.erase(trimmed.find_last_not_of(" \n\r\t") + 1); if (trimmed.rfind("//", 0) == 0) { break; } std::smatch match; if (std::regex_match(line, match, pattern) && line[0] != ' ') { currentSection = match[1]; sections[currentSection] += match[2].str() + "\n"; } else if (!currentSection.empty()) { sections[currentSection] += line + "\n"; } } file.close(); } void printProperties() const { for (const auto& pair : sections) { std::string value = pair.second; value.erase(value.find_last_not_of(" \n\r\t") + 1); std::cout << pair.first << ":\n" << value << "\n\n"; } } void write(const std::string& filepath) const { std::ofstream file(filepath); if (!file.is_open()) return; for (const auto& pair : sections) { file << pair.first << " " << pair.second; } file << "//\n"; file.close(); } }; // Example usage: // int main() { // GBKHandler handler; // handler.read("example.gbk"); // handler.printProperties(); // handler.sections["DEFINITION"] = "Modified definition\n"; // Note: Direct map access for modification // handler.write("modified.gbk"); // return 0; // } // ===== end task-250 .GBK ===== // ===== task-251 .GBR [C] ===== #include #include #include typedef struct { char encoding[20]; char structure[50]; char coordinateSystem[30]; char units[10]; char formatSpec[20]; char polarity[10]; char** apertureDefinitions; int numApertures; char** apertureList; int numApertureList; char stepRepeat[50]; // Simplified: only fileFunction for attributes char fileFunction[50]; int linear, circularCW, circularCCW, multiQuadrant; int draw, move, flash; int endOfFile; } GBRProperties; GBRProperties* initProperties() { GBRProperties* props = malloc(sizeof(GBRProperties)); strcpy(props->encoding, "UTF-8 ASCII"); strcpy(props->structure, "Command stream terminated by *"); strcpy(props->coordinateSystem, "Absolute (default)"); strcpy(props->units, "INCH (default)"); strcpy(props->formatSpec, "LAX35Y35"); strcpy(props->polarity, "POS (default)"); props->apertureDefinitions = NULL; props->numApertures = 0; props->apertureList = NULL; props->numApertureList = 0; strcpy(props->stepRepeat, ""); strcpy(props->fileFunction, ""); props->linear = 1; props->circularCW = 0; props->circularCCW = 0; props->multiQuadrant = 1; props->draw = 0; props->move = 0; props->flash = 0; props->endOfFile = 0; return props; } void parseGBR(GBRProperties* props, const char* content) { // Simple split simulation: find * and process substrings char* cmd = strtok((char*)content, "*"); while (cmd != NULL) { cmd = strtok(NULL, "*"); // Skip first if (cmd) { while (*cmd == ' ' || *cmd == '\n' || *cmd == '\r') cmd++; // Trim if (strncmp(cmd, "%FS", 3) == 0) { strcpy(props->formatSpec, cmd + 3); } else if (strncmp(cmd, "%MO", 3) == 0) { strcpy(props->units, cmd + 3); } else if (strncmp(cmd, "%IP", 3) == 0) { strcpy(props->polarity, cmd + 3); } else if (strncmp(cmd, "%AD", 3) == 0) { props->numApertures++; props->apertureDefinitions = realloc(props->apertureDefinitions, props->numApertures * sizeof(char*)); props->apertureDefinitions[props->numApertures - 1] = malloc(50); strcpy(props->apertureDefinitions[props->numApertures - 1], cmd + 3); } else if (strncmp(cmd, "G01", 3) == 0) props->linear = 1; else if (strncmp(cmd, "G02", 3) == 0) props->circularCW = 1; else if (strncmp(cmd, "G03", 3) == 0) props->circularCCW = 1; else if (strncmp(cmd, "G75", 3) == 0) props->multiQuadrant = 1; else if (strncmp(cmd, "D01", 3) == 0) props->draw++; else if (strncmp(cmd, "D02", 3) == 0) props->move++; else if (strncmp(cmd, "D03", 3) == 0) props->flash++; else if (strncmp(cmd, "M02", 3) == 0) props->endOfFile = 1; // Add more as needed } cmd = strtok(NULL, "*"); } } void printProperties(GBRProperties* props) { printf("Encoding: %s\n", props->encoding); printf("Units: %s\n", props->units); printf("Format Spec: %s\n", props->formatSpec); printf("Polarity: %s\n", props->polarity); printf("Apertures: %d\n", props->numApertures); for (int i = 0; i < props->numApertures; i++) { printf(" %s\n", props->apertureDefinitions[i]); } printf("Operations - Draw: %d, Move: %d, Flash: %d\n", props->draw, props->move, props->flash); // Add more prints } void readGBR(GBRProperties* props, const char* filename) { FILE* file = fopen(filename, "r"); if (!file) { printf("File not found: %s\n", filename); return; } fseek(file, 0, SEEK_END); long size = ftell(file); fseek(file, 0, SEEK_SET); char* content = malloc(size + 1); fread(content, 1, size, file); content[size] = '\0'; fclose(file); parseGBR(props, content); printProperties(props); free(content); } void writeGBR(GBRProperties* props, const char* filename) { FILE* file = fopen(filename, "w"); if (!file) return; fprintf(file, "%%FS%s*\n", props->formatSpec); fprintf(file, "%%MO%s*\n", props->units); fprintf(file, "%%IP%s*\n", props->polarity); for (int i = 0; i < props->numApertures; i++) { fprintf(file, "%%AD%s*\n", props->apertureDefinitions[i]); } fprintf(file, "M02*\n"); fclose(file); } void freeProperties(GBRProperties* props) { for (int i = 0; i < props->numApertures; i++) { free(props->apertureDefinitions[i]); } free(props->apertureDefinitions); free(props); } int main() { GBRProperties* props = initProperties(); readGBR(props, "sample.gbr"); writeGBR(props, "output.gbr"); freeProperties(props); return 0; } // ===== end task-251 .GBR ===== // ===== task-252 .GDF [C] ===== #include #include #include #include typedef struct { char version[8]; char patient_id[66]; uint8_t weight; uint8_t height; char gender[10]; // Derived uint16_t header_len; int64_t nrec; uint16_t ns; char ch1_label[16]; double ch1_phys_min; double ch1_phys_max; uint32_t ch1_gdftyp; uint32_t ch1_spr; } GDFProps; typedef struct { FILE *file; GDFProps props; } GDFHandler; void gdf_read(GDFHandler *h) { fread(h->props.version, 1, 8, h->file); h->props.version[7] = '\0'; fseek(h->file, 8, SEEK_SET); fread(h->props.patient_id, 1, 66, h->file); h->props.patient_id[65] = '\0'; fseek(h->file, 85, SEEK_SET); fread(&h->props.weight, 1, 1, h->file); fread(&h->props.height, 1, 1, h->file); uint8_t byte87; fread(&byte87, 1, 1, h->file); strcpy(h->props.gender, (byte87 & 0x03) == 1 ? "Male" : (byte87 & 0x03) == 2 ? "Female" : "Unknown"); fseek(h->file, 184, SEEK_SET); fread(&h->props.header_len, 2, 1, h->file); h->props.header_len *= 256; fseek(h->file, 236, SEEK_SET); fread(&h->props.nrec, 8, 1, h->file); fseek(h->file, 252, SEEK_SET); fread(&h->props.ns, 2, 1, h->file); // Header 2 long ch_offset = 256; fseek(h->file, ch_offset, SEEK_SET); fread(h->props.ch1_label, 1, 16, h->file); h->props.ch1_label[15] = '\0'; fseek(h->file, ch_offset + 104, SEEK_SET); fread(&h->props.ch1_phys_min, 8, 1, h->file); fread(&h->props.ch1_phys_max, 8, 1, h->file); fseek(h->file, ch_offset + 220, SEEK_SET); fread(&h->props.ch1_gdftyp, 4, 1, h->file); fseek(h->file, ch_offset + 216, SEEK_SET); fread(&h->props.ch1_spr, 4, 1, h->file); // Print (simplified) printf("Version: %s\nPatient ID: %s\nWeight: %u\nHeight: %u\nGender: %s\nHeader Len: %u\nNREC: %ld\nNS: %u\nCh1 Label: %s\nCh1 Phys Min: %f\nCh1 Phys Max: %f\nCh1 GDFTyp: %u\nCh1 SPR: %u\n", h->props.version, h->props.patient_id, h->props.weight, h->props.height, h->props.gender, h->props.header_len, h->props.nrec, h->props.ns, h->props.ch1_label, h->props.ch1_phys_min, h->props.ch1_phys_max, h->props.ch1_gdftyp, h->props.ch1_spr); } void gdf_write(GDFHandler *h, const char *output_filename) { FILE *out = fopen(output_filename, "wb"); // Simplified Header 1 fwrite("GDF 2.10", 1, 8, out); fwrite("X", 1, 66, out); // Patient placeholder fputc(h->props.weight, out); // ... Write others with fwrite uint16_t hlen = h->props.header_len / 256; fwrite(&hlen, 2, 1, out); fwrite("\0", 1, 256 - ftell(out) % 256, out); // Pad fclose(out); printf("Wrote %s\n", output_filename); } int main(int argc, char **argv) { if (argc < 2) return 1; GDFHandler h = { .file = fopen(argv[1], "rb") }; if (!h.file) return 1; gdf_read(&h); fclose(h.file); // gdf_write(&h, "output.gdf"); return 0; } // ===== end task-252 .GDF ===== // ===== task-253 .GDSCRIPT [C] ===== #include #include #include #include typedef struct { char* filepath; char* content; size_t size; struct { char extension[4]; char format_type[12]; char encoding[7]; char line_endings[8]; char indentation[10]; char file_termination[16]; char character_set[16]; char mime_type[11]; char bom_presence[20]; char detected_line_endings[25]; char detected_indentation[25]; char file_termination_detected[25]; } properties; } GDScriptHandler; void init_properties(GDScriptHandler* handler) { strcpy(handler->properties.extension, ".gd"); strcpy(handler->properties.format_type, "Plain text"); strcpy(handler->properties.encoding, "UTF-8"); strcpy(handler->properties.line_endings, "LF (\\n)"); strcpy(handler->properties.indentation, "Tabs (\\t)"); strcpy(handler->properties.file_termination, "Single newline"); strcpy(handler->properties.character_set, "Unicode (UTF-8)"); strcpy(handler->properties.mime_type, "text/plain"); } int read_and_decode(GDScriptHandler* handler) { FILE* file = fopen(handler->filepath, "rb"); if (!file) { perror("Error opening file"); return 0; } fseek(file, 0, SEEK_END); handler->size = ftell(file); fseek(file, 0, SEEK_SET); handler->content = malloc(handler->size + 1); fread(handler->content, 1, handler->size, file); handler->content[handler->size] = '\0'; fclose(file); // Simple UTF-8 decode (assume valid); detect BOM if (handler->size >= 3 && handler->content[0] == 0xEF && handler->content[1] == 0xBB && handler->content[2] == 0xBF) { strcpy(handler->properties.bom_presence, "Yes (Non-standard)"); // Shift content past BOM memmove(handler->content, handler->content + 3, handler->size - 3); handler->size -= 3; handler->content[handler->size] = '\0'; } else { strcpy(handler->properties.bom_presence, "No - Standard"); } detect_properties(handler); print_properties(handler); return 1; } void detect_properties(GDScriptHandler* handler) { // Detect line endings if (strstr(handler->content, "\r\n")) { strcpy(handler->properties.detected_line_endings, "CRLF (\\r\\n) - Non-standard"); } else { strcpy(handler->properties.detected_line_endings, "LF (\\n) - Standard"); } // Detect indentation (simple: find first indented line) char* indent_start = strstr(handler->content, "\n "); if (!indent_start) indent_start = strstr(handler->content, "\n\t"); if (indent_start && *(indent_start + 2) == '\t') { strcpy(handler->properties.detected_indentation, "Tabs (\\t) - Standard"); } else if (indent_start) { strcpy(handler->properties.detected_indentation, "Spaces - Non-standard"); } else { strcpy(handler->properties.detected_indentation, "None detected"); } if (handler->content[handler->size - 1] != '\n') { strcpy(handler->properties.file_termination_detected, "Non-standard"); } else { strcpy(handler->properties.file_termination_detected, "Single newline - Standard"); } } void print_properties(GDScriptHandler* handler) { printf("GDScript File Properties:\n"); printf("EXTENSION: %s\n", handler->properties.extension); printf("FORMAT TYPE: %s\n", handler->properties.format_type); printf("ENCODING: %s\n", handler->properties.encoding); printf("LINE ENDINGS: %s\n", handler->properties.line_endings); printf("INDENTATION: %s\n", handler->properties.indentation); printf("FILE TERMINATION: %s\n", handler->properties.file_termination); printf("CHARACTER SET: %s\n", handler->properties.character_set); printf("MIME TYPE: %s\n", handler->properties.mime_type); printf("BOM PRESENCE: %s\n", handler->properties.bom_presence); printf("DETECTED LINE ENDINGS: %s\n", handler->properties.detected_line_endings); printf("DETECTED INDENTATION: %s\n", handler->properties.detected_indentation); printf("FILE TERMINATION DETECTED: %s\n", handler->properties.file_termination_detected); struct stat st; stat(handler->filepath, &st); printf("FILE SIZE: %ld bytes\n", (long)st.st_size); printf("\nRAW CONTENT PREVIEW:\n"); handler->content[500] = '\0'; // Truncate for preview printf("%s...\n", handler->content); } void write_file(GDScriptHandler* handler, char* output_path) { // Normalize: remove CRLF, ensure LF end char* normalized = malloc(handler->size + 1); char* src = handler->content; char* dst = normalized; while (*src) { if (src[0] == '\r' && src[1] == '\n') { *dst++ = '\n'; src += 2; } else { *dst++ = *src++; } } *dst = '\0'; if (normalized[handler->size - 1] != '\n') { strcat(normalized, "\n"); } FILE* out = fopen(output_path ? output_path : handler->filepath, "wb"); if (out) { fwrite(normalized, 1, strlen(normalized), out); fclose(out); printf("File written successfully to %s\n", output_path ? output_path : handler->filepath); } else { perror("Error writing file"); } free(normalized); } void free_handler(GDScriptHandler* handler) { free(handler->content); free(handler->filepath); free(handler); } int main(int argc, char* argv[]) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } GDScriptHandler* handler = malloc(sizeof(GDScriptHandler)); handler->filepath = strdup(argv[1]); init_properties(handler); if (read_and_decode(handler)) { write_file(handler, NULL); // Write back to same file } free_handler(handler); return 0; } // ===== end task-253 .GDSCRIPT ===== // ===== task-254 .GDT [C] ===== #include #include #include #include typedef struct { xmlDocPtr doc; } GDTParser; static void print_attr(xmlNodePtr node, const char* attr_name, const char* label) { xmlChar* attr_val = xmlGetProp(node, (const xmlChar*)attr_name); printf(" %s: %s\n", label, attr_val ? (char*)attr_val : "N/A"); if (attr_val) xmlFree(attr_val); } void print_properties(GDTParser* parser) { xmlNodePtr root = xmlDocGetRootElement(parser->doc); if (!root || xmlStrcmp(root->name, (const xmlChar*)"gretldata")) { fprintf(stderr, "Not a valid .GDT file\n"); return; } printf("=== .GDT File Properties ===\n"); printf("\nRoot Attributes:\n"); print_attr(root, "version", "- version"); print_attr(root, "name", "- name"); print_attr(root, "frequency", "- frequency"); print_attr(root, "n", "- n"); print_attr(root, "startobs", "- startobs"); print_attr(root, "endobs", "- endobs"); print_attr(root, "type", "- type"); print_attr(root, "binary", "- binary"); print_attr(root, "rseed", "- rseed"); print_attr(root, "mapfile", "- mapfile"); print_attr(root, "mpi-transfer", "- mpi-transfer"); xmlNodePtr desc = NULL; for (xmlNodePtr child = root->children; child; child = child->next) { if (xmlStrcmp(child->name, (const xmlChar*)"description") == 0) { desc = child; break; } } if (desc) { xmlChar* text = xmlNodeGetContent(desc); printf("\nDescription:\n"); printf("- Text: %s\n", text ? (char*)text : "N/A"); print_attr(desc, "source", "- Source"); if (text) xmlFree(text); } xmlNodePtr vars = NULL; for (xmlNodePtr child = root->children; child; child = child->next) { if (xmlStrcmp(child->name, (const xmlChar*)"variables") == 0) { vars = child; break; } } if (vars) { print_attr(vars, "count", "\nVariables (count:"); printf("):\n"); for (xmlNodePtr v = vars->children; v; v = v->next) { if (xmlStrcmp(v->name, (const xmlChar*)"variable") == 0) { xmlChar* name = xmlNodeGetContent(v); printf(" - Name: %s\n", name ? (char*)name : "N/A"); print_attr(v, "label", " Label"); print_attr(v, "displayname", " Displayname"); print_attr(v, "parent", " Parent"); print_attr(v, "transform", " Transform"); print_attr(v, "lag", " Lag"); print_attr(v, "compact-method", " Compact-method"); print_attr(v, "discrete", " Discrete"); print_attr(v, "coded", " Coded"); print_attr(v, "role", " Role"); print_attr(v, "value", " Value"); printf("\n"); if (name) xmlFree(name); } } } xmlNodePtr obs_elem = NULL; for (xmlNodePtr child = root->children; child; child = child->next) { if (xmlStrcmp(child->name, (const xmlChar*)"observations") == 0) { obs_elem = child; break; } } if (obs_elem) { print_attr(obs_elem, "count", "\nObservations (count:"); printf("):\n"); print_attr(obs_elem, "missval", "- Missval"); print_attr(obs_elem, "labels", "- Labels"); print_attr(obs_elem, "panel-info", "- Panel-info ref"); for (xmlNodePtr o = obs_elem->children; o; o = o->next) { if (xmlStrcmp(o->name, (const xmlChar*)"obs") == 0) { xmlChar* values = xmlNodeGetContent(o); printf(" - Values: %s\n", values ? (char*)values : "N/A"); print_attr(o, "label", " Label"); print_attr(o, "unit", " Unit"); print_attr(o, "period", " Period"); print_attr(o, "id", " ID"); printf("\n"); if (values) xmlFree(values); } } } xmlNodePtr str_tables = NULL; for (xmlNodePtr child = root->children; child; child = child->next) { if (xmlStrcmp(child->name, (const xmlChar*)"string-tables") == 0) { str_tables = child; break; } } if (str_tables) { print_attr(str_tables, "count", "\nString Tables (count:"); printf("):\n"); for (xmlNodePtr s = str_tables->children; s; s = s->next) { if (xmlStrcmp(s->name, (const xmlChar*)"valstrings") == 0) { print_attr(s, "owner", " - Owner"); print_attr(s, "count", " Count"); xmlChar* strings = xmlNodeGetContent(s); printf(" Strings: %s\n", strings ? (char*)strings : "N/A"); printf("\n"); if (strings) xmlFree(strings); } } } xmlNodePtr panel = NULL; for (xmlNodePtr child = root->children; child; child = child->next) { if (xmlStrcmp(child->name, (const xmlChar*)"panel-info") == 0) { panel = child; break; } } if (panel) { printf("\nPanel Info:\n"); print_attr(panel, "group-names", "- Group-names"); print_attr(panel, "time-frequency", "- Time-frequency"); print_attr(panel, "time-start", "- Time-start"); print_attr(panel, "skip-padding", "- Skip-padding"); } } void load(GDTParser* parser, const char* filename) { parser->doc = xmlReadFile(filename, NULL, 0); if (!parser->doc) { fprintf(stderr, "Failed to parse %s\n", filename); return; } print_properties(parser); } void write(GDTParser* parser, const char* filename) { if (!parser->doc) return; int success = xmlSaveFormatFileEnc(filename, parser->doc, "UTF-8", 1); if (success != -1) { printf("Written to %s\n", filename); } else { fprintf(stderr, "Write failed\n"); } } int main(int argc, char** argv) { if (argc < 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } GDTParser parser = {0}; load(&parser, argv[1]); // Example modification: xmlSetProp(xmlDocGetRootElement(parser.doc), (xmlChar*)"name", (xmlChar*)"Modified"); // write(&parser, "modified.gdt"); xmlFreeDoc(parser.doc); xmlCleanupParser(); return 0; } // ===== end task-254 .GDT ===== // ===== task-255 .GED [C] ===== #include #include #include #include // For parsing (POSIX regex) typedef struct { char *properties[13][2]; // Key-value pairs } GEDProperties; typedef struct { int index; char *level; char *xref; char *tag; char *value; char *raw; // If unparsed } ParsedLine; GEDProperties props = { .properties = {{"File Extension", ".GED"}, {"Supported Encodings", "ANSEL, ASCII, UTF-8, Unicode"}, {"Line Terminators", "CR, LF, CRLF, LFCR"}, {"Max Line Length", "255 chars"}, {"Overall Structure", "Header (HEAD), Records (level 0), Trailer (TRLR)"}, {"Line Format", "level [space] [@XREF@] [space] tag [space] value"}, {"Levels", "0-99, no leading zeros, incremental by <=1"}, {"XREFs", "Enclosed in @, unique"}, {"Tags", "Uppercase 3-4 letters"}, {"Continuation", "CONT (with CR), CONC (without)"}, {"Escapes", "@#text@ "}, {"Header Req.", "SOUR, VERS=5.5.1, CHAR"}, {"Trailer", "0 TRLR"}} }; void init_props(GEDProperties *p) { // Already initialized } ParsedLine *read_and_decode(const char *filename, int *num_lines, int *max_len, char *detected_ending, int *has_header, int *has_trailer) { FILE *fp = fopen(filename, "r"); if (!fp) { perror("fopen"); exit(1); } fseek(fp, 0, SEEK_END); long fsize = ftell(fp); fseek(fp, 0, SEEK_SET); char *content = malloc(fsize + 1); fread(content, 1, fsize, fp); content[fsize] = 0; fclose(fp); // Simple line split (assume \n for simplicity) *num_lines = 0; for (char *ptr = content; *ptr; ptr++) if (*ptr == '\n') (*num_lines)++; ParsedLine *parsed = malloc(sizeof(ParsedLine) * (*num_lines + 1)); char *line_start = content; int i = 0, local_max = 0; *detected_ending = 'N'; // Simplified: check for \r\n if (strstr(content, "\r\n")) *detected_ending = 'L'; // CRLF else if (strstr(content, "\r")) *detected_ending = 'C'; else *detected_ending = 'F'; // LF *has_header = strstr(content, "0 HEAD") != NULL; *has_trailer = strstr(content, "0 TRLR") != NULL; regex_t regex; regcomp(®ex, "^(\\d+)(?:\\s+@([^@]+)@)?\\s+([A-Z]{3,4})(?:\\s+(.*))?$", REG_EXTENDED); char *saveptr; for (char *line = strtok_r(content, "\r\n", &saveptr); line; line = strtok_r(NULL, "\r\n", &saveptr), i++) { int len = strlen(line); if (len > local_max) local_max = len; parsed[i].index = i; regmatch_t matches[5]; if (regexec(®ex, line, 5, matches, 0) == 0) { parsed[i].level = strndup(line + matches[1].rm_so, matches[1].rm_eo - matches[1].rm_so); parsed[i].xref = (matches[2].rm_so != -1) ? strndup(line + matches[2].rm_so, matches[2].rm_eo - matches[2].rm_so) : strdup(""); parsed[i].tag = strndup(line + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so); parsed[i].value = (matches[4].rm_so != -1) ? strndup(line + matches[4].rm_so, matches[4].rm_eo - matches[4].rm_so) : strdup(""); parsed[i].raw = NULL; } else { parsed[i].raw = strdup(line); parsed[i].level = parsed[i].xref = parsed[i].tag = parsed[i].value = NULL; } } *max_len = local_max; parsed[*num_lines].level = NULL; // Sentinel regfree(®ex); free(content); return parsed; } void print_properties(ParsedLine *parsed, int num_lines, int max_len, char detected_ending, int has_header, int has_trailer) { printf("=== GEDCOM Properties Dump ===\n"); for (int j = 0; j < 13; j++) { printf("%s: %s", props.properties[j][0], props.properties[j][1]); if (strcmp(props.properties[j][0], "Max Line Length") == 0) printf(" (File max: %d)", max_len); if (strcmp(props.properties[j][0], "Line Terminators") == 0) { printf(" (Detected: %c)", detected_ending == 'L' ? 'L' : (detected_ending == 'C' ? 'C' : 'F')); } if (strcmp(props.properties[j][0], "Overall Structure") == 0) printf(" (Has HEAD: %s, Has TRLR: %s)", has_header ? "Yes" : "No", has_trailer ? "Yes" : "No"); printf("\n"); } printf("\n=== Parsed Lines Sample (First 20) ===\n"); for (int k = 0; k < num_lines && k < 20; k++) { if (parsed[k].raw) { printf("Line %d: %s\n", parsed[k].index, parsed[k].raw); } else { printf("Line %d: Level=%s, XREF=%s, Tag=%s, Value=%s\n", parsed[k].index, parsed[k].level, parsed[k].xref, parsed[k].tag, parsed[k].value); } } } void write_file(const char *filename, ParsedLine *parsed, int num_lines, const char *append_note) { FILE *fp = fopen(strcat((char*)filename, "_modified.ged"), "w"); if (!fp) { perror("fopen write"); exit(1); } for (int m = 0; m < num_lines; m++) { if (parsed[m].raw) { fprintf(fp, "%s\n", parsed[m].raw); } else { char line[256]; snprintf(line, sizeof(line), "%s %s %s %s", parsed[m].level, parsed[m].xref[0] ? parsed[m].xref : "", parsed[m].tag, parsed[m].value[0] ? parsed[m].value : ""); if (append_note && strcmp(parsed[m].tag, "HEAD") == 0) { strcat(line, " NOTE "); strcat(line, append_note); } fprintf(fp, "%s\n", line); } } fprintf(fp, "0 TRLR\n"); fclose(fp); printf("Wrote modified file: %s\n", filename); } int main(int argc, char *argv[]) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } int num_lines, max_len, has_header, has_trailer; char ending; ParsedLine *parsed = read_and_decode(argv[1], &num_lines, &max_len, &ending, &has_header, &has_trailer); print_properties(parsed, num_lines, max_len, ending, has_header, has_trailer); write_file(argv[1], parsed, num_lines, "Modified by C parser"); // Cleanup for (int n = 0; n < num_lines; n++) { if (parsed[n].raw) free(parsed[n].raw); else { free(parsed[n].level); free(parsed[n].xref); free(parsed[n].tag); free(parsed[n].value); } } free(parsed); return 0; } // ===== end task-255 .GED ===== // ===== task-256 .GEOJSON [C] ===== #include #include #include #include typedef struct { char* type; double* bbox; // Simplified: assume 2D array of 4 doubles int bbox_size; // Simplified: no full parse for features/geometries; count via string scan int feature_count; char* geom_type; // Single type for simplicity char* filepath; char* content; // Raw JSON string for write } GeoJSONHandler; GeoJSONHandler* geojson_open(const char* filepath) { FILE* f = fopen(filepath, "r"); if (!f) return NULL; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); char* content = malloc(size + 1); fread(content, 1, size, f); content[size] = '\0'; fclose(f); GeoJSONHandler* handler = malloc(sizeof(GeoJSONHandler)); handler->content = content; handler->filepath = strdup(filepath); // Simple parse: extract "type" char* type_start = strstr(content, "\"type\":"); if (type_start) { type_start += 7; // Skip "\"type\":" while (*type_start && isspace(*type_start)) type_start++; if (*type_start == '"') type_start++; char* type_end = strchr(type_start, '"'); if (type_end) { int len = type_end - type_start; handler->type = malloc(len + 1); strncpy(handler->type, type_start, len); handler->type[len] = '\0'; } } // Simplified bbox: scan for [num,num,num,num] handler->bbox = NULL; handler->bbox_size = 0; char* bbox_start = strstr(content, "\"bbox\":["); if (bbox_start) { // Basic: assume 4 numbers; parse roughly handler->bbox = malloc(4 * sizeof(double)); // Placeholder parse (use sscanf in real impl) sscanf(bbox_start + 8, "%lf,%lf,%lf,%lf", &handler->bbox[0], &handler->bbox[1], &handler->bbox[2], &handler->bbox[3]); handler->bbox_size = 4; } // Feature count: count "features" array length (simplified string count) handler->feature_count = 0; if (strstr(content, "\"FeatureCollection\"")) { char* features_start = strstr(content, "\"features\":["); if (features_start) { char* count_pos = strchr(features_start + 12, '{'); while (count_pos && strstr(count_pos, "\"type\":\"Feature\"")) { handler->feature_count++; count_pos = strchr(count_pos + 1, '{'); } } } // Geom type: first occurrence handler->geom_type = NULL; char* geom_start = strstr(content, "\"type\":\""); if (geom_start) { geom_start += 8; char* geom_end = strchr(geom_start, '"'); if (geom_end) { int len = geom_end - geom_start; handler->geom_type = malloc(len + 1); strncpy(handler->geom_type, geom_start, len); handler->geom_type[len] = '\0'; } } return handler; } void geojson_write(GeoJSONHandler* handler, const char* output_path) { FILE* f = fopen(output_path, "w"); if (f) { fputs(handler->content, f); fclose(f); } } void geojson_print_properties(GeoJSONHandler* handler) { printf("File Encoding: UTF-8 (JSON-based)\n"); printf("Top-Level Type: %s\n", handler->type ? handler->type : "Unknown"); printf("CRS: WGS 84 (lon/lat order)\n"); printf("Coordinate Precision: Up to 6 decimals recommended\n"); printf("Bounding Box: %s\n", handler->bbox ? "Present (parsed values)" : "Not present"); printf("Properties Object: Present (assumed if Feature)\n"); printf("Identifier: Not present (simplified parse)\n"); printf("Foreign Members: Unknown (full parse needed)\n"); printf("Validity Notes: Assumes no antimeridian crossing; empty geometries treated as null\n"); if (strstr(handler->content, "\"FeatureCollection\"")) { printf("Feature Count: %d\n", handler->feature_count); printf("Geometry Types: %s (first found)\n", handler->geom_type ? handler->geom_type : "None"); } else { printf("Geometry Type: %s\n", handler->geom_type ? handler->geom_type : "Unknown"); } } void geojson_close(GeoJSONHandler* handler) { free(handler->content); free(handler->type); free(handler->geom_type); if (handler->bbox) free(handler->bbox); free(handler->filepath); free(handler); } int main(int argc, char* argv[]) { if (argc < 2) return 1; GeoJSONHandler* handler = geojson_open(argv[1]); if (handler) { geojson_print_properties(handler); // geojson_write(handler, "output.geojson"); geojson_close(handler); } return 0; } // ===== end task-256 .GEOJSON ===== // ===== task-257 .GEOTIFF [C] ===== #include #include #include #include typedef struct { char byteOrder[3]; uint16_t version; uint32_t ifdOffset; } Header; typedef struct { int numTags; // Tags as array or map; simplified to print } IFD; typedef struct { Header header; IFD ifd; // Geo props simplified } GeoProps; typedef struct { GeoProps props; FILE* file; int littleEndian; } GeoTIFFHandler; void readHeader(GeoTIFFHandler* h) { fseek(h->file, 0, SEEK_SET); uint16_t bo; fread(&bo, 2, 1, h->file); h->littleEndian = (bo == 0x4949); uint16_t ver; fread(&ver, 2, 1, h->file); uint32_t offset; fread(&offset, 4, 1, h->file); strcpy(h->props.header.byteOrder, h->littleEndian ? "II" : "MM"); h->props.header.version = ver; h->props.header.ifdOffset = offset; if (ver != 42) { fprintf(stderr, "Invalid TIFF\n"); exit(1); } } void read(GeoTIFFHandler* h, const char* path) { h->file = fopen(path, "rb"); if (!h->file) { perror("Open failed"); return; } fseek(h->file, 0, SEEK_END); long size = ftell(h->file); fseek(h->file, 0, SEEK_SET); uint8_t* buf = malloc(size); fread(buf, 1, size, h->file); readHeader(h); // Parse IFD and Geo (simplified print) fprintf(stdout, "Header: %s, Ver: %d, IFD: %u\n", h->props.header.byteOrder, h->props.header.version, h->props.header.ifdOffset); // Add IFD/Geo parsing with buf (similar logic, unpack with mem offsets) fclose(h->file); free(buf); } void write(GeoTIFFHandler* h, const char* outPath) { // Simplified copy FILE* out = fopen(outPath, "wb"); fseek(h->file, 0, SEEK_SET); // Reopen if needed // Copy logic fprintf(stdout, "Wrote to %s\n", outPath); fclose(out); } // Usage: GeoTIFFHandler h = {0}; read(&h, "sample.tif"); // ===== end task-257 .GEOTIFF ===== // ===== task-258 .GGB [C] ===== #include #include #include #include #include #define ZIP_LOCAL_SIG 0x04034B50 #define ZIP_CENTRAL_SIG 0x02014B50 #define ZIP_END_SIG 0x06054B50 #define BUFFER_SIZE 1024 typedef struct { unsigned long compressed_size; unsigned long uncompressed_size; unsigned short compression_method; char *name; } ZipEntry; typedef struct { int num_entries; ZipEntry *entries; } GGBFile; GGBFile *ggb_open(const char *path) { GGBFile *ggb = malloc(sizeof(GGBFile)); ggb->num_entries = 0; ggb->entries = NULL; int fd = open(path, O_RDONLY); if (fd < 0) return NULL; // Find end of central directory (read backward) long file_size = lseek(fd, 0, SEEK_END); char buf[22]; long pos = file_size - 22; while (pos >= 0) { lseek(fd, pos, SEEK_SET); read(fd, buf, 22); if (*(unsigned long *)buf == ZIP_END_SIG) break; pos--; } if (pos < 0) { close(fd); free(ggb); return NULL; } // Parse central directory offset and size unsigned long central_offset = *(unsigned long *)(buf + 16); unsigned short central_size = *(unsigned short *)(buf + 12); // Parse central directory lseek(fd, central_offset, SEEK_SET); ggb->num_entries = central_size / 46; // Approx size per entry ggb->entries = malloc(ggb->num_entries * sizeof(ZipEntry)); int entry_idx = 0; char central_buf[BUFFER_SIZE]; while (central_offset < file_size && entry_idx < ggb->num_entries) { read(fd, central_buf, 46); if (*(unsigned long *)central_buf != ZIP_CENTRAL_SIG) break; ZipEntry *entry = &ggb->entries[entry_idx]; entry->compression_method = *(unsigned short *)(central_buf + 10); entry->compressed_size = *(unsigned long *)(central_buf + 20); entry->uncompressed_size = *(unsigned long *)(central_buf + 24); unsigned short name_len = *(unsigned short *)(central_buf + 28); unsigned long local_offset = *(unsigned long *)(central_buf + 42); // Read name entry->name = malloc(name_len + 1); lseek(fd, local_offset + 30, SEEK_SET); // After local header read(fd, entry->name, name_len); entry->name[name_len] = '\0'; entry_idx++; central_offset += 46 + name_len; // Skip extra/comment } ggb->num_entries = entry_idx; close(fd); return ggb; } void ggb_print_properties(GGBFile *ggb) { if (!ggb) return; printf("=== .GGB File Properties ===\n"); printf("Archive Format: ZIP\n"); printf("Number of Files: %d\n\n", ggb->num_entries); printf("Files in Archive:\n"); for (int i = 0; i < ggb->num_entries; i++) { ZipEntry *e = &ggb->entries[i]; printf("- %s (Uncompressed: %lu bytes, Compressed: %lu bytes)\n", e->name, e->uncompressed_size, e->compressed_size); } // geogebra.xml (read raw text, assume uncompressed for simplicity; extend for deflate) int xml_found = 0; for (int i = 0; i < ggb->num_entries; i++) { if (strcmp(ggb->entries[i].name, "geogebra.xml") == 0) { printf("\ngeogebra.xml: Present\n"); // Simple version parse (read first line) FILE *fp = fopen("temp.ggb", "rb"); // Reopen file fseek(fp, ggb->entries[i].compressed_size ? /* deflate offset */ 0 : 0, SEEK_SET); // Simplified char xml_buf[501]; fread(xml_buf, 1, 500, fp); xml_buf[500] = '\0'; // Find version char *ver = strstr(xml_buf, "format=\""); if (ver) { ver += 8; char *end = strchr(ver, '"'); if (end) *end = '\0'; printf(" Version: %s\n", ver); } printf(" Content (first 500 chars): %s...\n", xml_buf); fclose(fp); remove("temp.ggb"); xml_found = 1; break; } } if (!xml_found) printf("\ngeogebra.xml: Missing\n"); // Similar for thumbnail (size only) int thumb_found = 0; for (int i = 0; i < ggb->num_entries; i++) { if (strcmp(ggb->entries[i].name, "geogebra_thumbnail.png") == 0) { printf("\ngeogebra_thumbnail.png: Present (Size: %lu bytes)\n", ggb->entries[i].uncompressed_size); thumb_found = 1; break; } } if (!thumb_found) printf("\ngeogebra_thumbnail.png: Missing\n"); // geogebra.js int js_found = 0; for (int i = 0; i < ggb->num_entries; i++) { if (strcmp(ggb->entries[i].name, "geogebra.js") == 0 || strcmp(ggb->entries[i].name, "geogebra_main.js") == 0) { printf("\ngeogebra.js: Present (Size: %lu bytes)\n", ggb->entries[i].uncompressed_size); js_found = 1; break; } } if (!js_found) printf("\ngeogebra.js: Missing\n"); // images/ int img_count = 0; printf("\nImages Directory Files: "); for (int i = 0; i < ggb->num_entries; i++) { if (strncmp(ggb->entries[i].name, "images/", 7) == 0) { img_count++; printf("%s (%lu bytes) ", ggb->entries[i].name + 7, ggb->entries[i].uncompressed_size); } } printf("(%d total)\n", img_count); } void ggb_write(GGBFile *ggb, const char *output_path) { // Simple copy FILE *in = fopen(ggb ? ggb->path : "input.ggb", "rb"); // Assume path stored FILE *out = fopen(output_path, "wb"); char buf[BUFFER_SIZE]; size_t bytes; while ((bytes = fread(buf, 1, BUFFER_SIZE, in)) > 0) { fwrite(buf, 1, bytes, out); } fclose(in); fclose(out); printf("\nWritten to %s\n", output_path); } void ggb_close(GGBFile *ggb) { if (!ggb) return; for (int i = 0; i < ggb->num_entries; i++) { free(ggb->entries[i].name); } free(ggb->entries); free(ggb); } // Usage: // GGBFile *ggb = ggb_open("example.ggb"); // ggb_print_properties(ggb); // ggb_write(ggb, "output.ggb"); // ggb_close(ggb); // ===== end task-258 .GGB ===== // ===== task-259 .GIF [C] ===== #include #include #include #include typedef struct { char signature[4]; char version[4]; uint16_t width; uint16_t height; uint8_t gct_flag; uint8_t color_res; uint8_t g_sort; uint8_t gct_size; uint8_t bg_index; uint8_t aspect; // Simplified: no full color arrays int frame_count; int loop_count; char** comments; } GIFProperties; void read_gif(const char* filename, GIFProperties* props) { FILE* f = fopen(filename, "rb"); if (!f) { perror("File open error"); return; } fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); int pos = 0; // Header memcpy(props->signature, data + pos, 3); props->signature[3] = '\0'; pos += 3; memcpy(props->version, data + pos, 3); props->version[3] = '\0'; pos += 3; printf("Signature: %s\n", props->signature); printf("Version: %s\n", props->version); // Logical Screen props->width = data[pos] | (data[pos+1] << 8); pos += 2; props->height = data[pos] | (data[pos+1] << 8); pos += 2; uint8_t packed = data[pos++]; props->gct_flag = !!(packed & 0x80); props->color_res = ((packed >> 4) & 0x07) + 1; props->g_sort = !!(packed & 0x08); props->gct_size = 1 << ((packed & 0x07) + 1); props->bg_index = data[pos++]; props->aspect = data[pos++]; printf("Logical Screen Width: %d, Height: %d\n", props->width, props->height); printf("Global Color Table Flag: %d, Color Resolution: %d bits\n", props->gct_flag, props->color_res); printf("Global Sort Flag: %d, Global Color Table Size: %d colors\n", props->g_sort, props->gct_size); printf("Background Index: %d, Pixel Aspect Ratio: %d\n", props->bg_index, props->aspect); // Skip Global Color Table for brevity if (props->gct_flag) { pos += 3 * props->gct_size; printf("Global Color Table skipped (size: %d colors)\n", props->gct_size); } props->frame_count = 0; props->loop_count = 1; // Comments array init props->comments = NULL; while (pos < size) { uint8_t block = data[pos]; if (block == 0x3B) break; // Trailer else if (block == 0x21) { // Extension pos++; uint8_t ext = data[pos++]; if (ext == 0xF9) { // GCE pos++; // Size uint8_t packed_gce = data[pos++]; int disposal = (packed_gce >> 2) & 0x07; int user_input = !!(packed_gce & 0x02); int trans_flag = !!(packed_gce & 0x01); uint16_t delay = data[pos] | (data[pos+1] << 8); pos += 2; int trans_index = data[pos++]; pos++; // Terminator printf("\n--- Frame %d Graphic Control ---\n", ++props->frame_count); printf("Disposal: %d, User Input: %d, Transparent Flag: %d\n", disposal, user_input, trans_flag); printf("Delay: %d cs, Transparent Index: %d\n", delay, trans_index); } else if (ext == 0xFF) { // App pos++; // Size if (strncmp((char*)(data + pos), "NETSCAPE2.0", 11) == 0) { pos += 11; pos++; // Data size props->loop_count = data[pos] | (data[pos+1] << 8); pos += 2; pos++; // Terminator printf("Loop Count: %d\n", props->loop_count); } // Skip sub-blocks while (data[pos] != 0) { pos += data[pos] + 1; } pos++; } else if (ext == 0xFE) { // Comment char* comment = malloc(1024); // Simple alloc int comment_len = 0; while (1) { uint8_t sub_len = data[pos++]; if (sub_len == 0) break; memcpy(comment + comment_len, data + pos, sub_len); comment_len += sub_len; pos += sub_len; } comment[comment_len] = '\0'; // Add to list (simplified, no realloc) printf("Comment: %s\n", comment); free(comment); } else { // Skip while (data[pos] != 0) pos += data[pos] + 1; pos++; } } else if (block == 0x2C) { // Image props->frame_count++; printf("\n--- Frame %d Image Descriptor ---\n", props->frame_count); pos++; uint16_t left = data[pos] | (data[pos+1] << 8); pos += 2; uint16_t top = data[pos] | (data[pos+1] << 8); pos += 2; uint16_t i_width = data[pos] | (data[pos+1] << 8); pos += 2; uint16_t i_height = data[pos] | (data[pos+1] << 8); pos += 2; uint8_t packed_img = data[pos++]; int lct_flag = !!(packed_img & 0x80); int interlace = !!(packed_img & 0x40); int l_sort = !!(packed_img & 0x20); int lct_size = 1 << ((packed_img & 0x07) + 1); printf("Left: %d, Top: %d, Width: %d, Height: %d\n", left, top, i_width, i_height); printf("Local Color Table Flag: %d, Interlace: %d, Local Sort: %d\n", lct_flag, interlace, l_sort); printf("Local Color Table Size: %d\n", lct_size); if (lct_flag) { pos += 3 * lct_size; // Skip printf("Local Color Table skipped\n"); } int lzw_min = data[pos++]; printf("LZW Min Code Size: %d bits\n", lzw_min); int data_size = 0; while (data[pos] != 0) { data_size += data[pos] + 1; pos += data[pos] + 1; } pos++; printf("Compressed Data Size: %d bytes\n", data_size); } else { printf("Unknown block 0x%02x\n", block); break; } } printf("\nTotal Frames: %d\n", props->frame_count); free(data); } void write_gif(const char* input_filename, const char* output_filename) { // Simple copy FILE* in = fopen(input_filename, "rb"); FILE* out = fopen(output_filename, "wb"); if (!in || !out) { perror("Copy error"); return; } fseek(in, 0, SEEK_END); long fsize = ftell(in); fseek(in, 0, SEEK_SET); uint8_t* buf = malloc(fsize); fread(buf, 1, fsize, in); fwrite(buf, 1, fsize, out); fclose(in); fclose(out); free(buf); printf("Wrote GIF to %s\n", output_filename); } int main() { GIFProperties props = {0}; read_gif("sample.gif", &props); write_gif("sample.gif", "output.gif"); return 0; } // ===== end task-259 .GIF ===== // ===== task-260 .GM9 [C] ===== #include #include #include typedef struct { char *filename; char *properties[6][2]; // [name][desc] char *found_values[6]; } GM9Decoder; void init_decoder(GM9Decoder *decoder, const char *filename) { decoder->filename = strdup(filename); // Initialize properties strcpy(decoder->properties[0][0], "CURRDIR"); strcpy(decoder->properties[0][1], "Path to the directory containing the script file (no trailing forward slash)."); strcpy(decoder->properties[1][0], "GM9OUT"); strcpy(decoder->properties[1][1], "GodMode9's output directory path for dumps and logs."); strcpy(decoder->properties[2][0], "EMUBASE"); strcpy(decoder->properties[2][1], "Base sector number of the current EmuNAND partition (integer value, or empty if no EmuNAND)."); strcpy(decoder->properties[3][0], "SDSIZE"); strcpy(decoder->properties[3][1], "Total size of the SD card, formatted with units (bytes if <1 KiB, KiB/MiB/GiB otherwise, rounded down to nearest tenth)."); strcpy(decoder->properties[4][0], "SDFREE"); strcpy(decoder->properties[4][1], "Free space on the SD card, formatted like SDSIZE (never exceeds SDSIZE)."); strcpy(decoder->properties[5][0], "NANDSIZE"); strcpy(decoder->properties[5][1], "Total size of SysNAND (including all partitions and bonus drive), formatted like SDSIZE."); for (int i = 0; i < 6; i++) { decoder->found_values[i] = NULL; } } void read_gm9(GM9Decoder *decoder) { FILE *file = fopen(decoder->filename, "r"); if (!file) { printf("Error: %s not found.\n", decoder->filename); return; } char line[1024]; while (fgets(line, sizeof(line), file)) { char *trimmed = line; while (*trimmed == ' ' || *trimmed == '\t') trimmed++; if (strncmp(trimmed, "set ", 4) == 0) { char *second = strtok(trimmed + 4, " \t"); if (second) { char *value = strtok(NULL, "\n"); if (value) { value += strspn(value, " \t"); // Skip spaces for (int i = 0; i < 6; i++) { if (strcmp(second, decoder->properties[i][0]) == 0) { decoder->found_values[i] = strdup(value); break; } } } } } } fclose(file); print_properties(decoder); } void print_properties(GM9Decoder *decoder) { printf("File System Properties:\n"); for (int i = 0; i < 6; i++) { char *value = decoder->found_values[i] ? decoder->found_values[i] : "Not set in script (runtime value)"; printf("%s: %s\n", decoder->properties[i][0], value); printf("Description: %s\n\n", decoder->properties[i][1]); } } void write_gm9(GM9Decoder *decoder, const char *output_filename) { char *out_name = strdup(output_filename ? output_filename : decoder->filename); FILE *in_file = fopen(decoder->filename, "r"); FILE *out_file = fopen(out_name, "w"); if (!in_file || !out_file) { printf("Write error.\n"); free(out_name); if (in_file) fclose(in_file); return; } char line[1024]; int modified = 0; while (fgets(line, sizeof(line), in_file)) { char *trimmed = line; while (*trimmed == ' ' || *trimmed == '\t') trimmed++; if (strncmp(trimmed, "set ", 4) == 0) { char *second = strtok(trimmed + 4, " \t\n"); if (second) { for (int i = 0; i < 6; i++) { if (strcmp(second, decoder->properties[i][0]) == 0) { char new_line[1024]; snprintf(new_line, sizeof(new_line), "set %s %s\n", second, decoder->found_values[i] ? decoder->found_values[i] : "default_value"); fputs(new_line, out_file); modified = 1; break; } } continue; } } fputs(line, out_file); } if (!modified) { for (int i = 0; i < 6; i++) { fprintf(out_file, "set %s default_value # Example\n", decoder->properties[i][0]); } } fclose(in_file); fclose(out_file); printf("Written to %s\n", out_name); free(out_name); } void free_decoder(GM9Decoder *decoder) { free(decoder->filename); for (int i = 0; i < 6; i++) { if (decoder->found_values[i]) free(decoder->found_values[i]); } } // Usage int main() { GM9Decoder decoder; init_decoder(&decoder, "example.gm9"); read_gm9(&decoder); write_gm9(&decoder, NULL); free_decoder(&decoder); return 0; } // ===== end task-260 .GM9 ===== // ===== task-261 .GMI [C] ===== #include #include #include #include // For regex, or implement simple matching // Simple struct for properties (simplified, no full lists for brevity) typedef struct { int total_lines; int text_lines; int link_lines; int heading_lines[3]; // Index 0: #, 1: ##, 2: ### int list_items; int quote_lines; int pre_blocks; int links_count; // Count only, no list int pre_alt_count; int final_pre_mode; char encoding[8]; } GMIProperties; typedef struct { char *filepath; char **lines; int line_count; GMIProperties props; } GMIFile; void read_gmi(GMIFile *gmi) { FILE *f = fopen(gmi->filepath, "r"); if (!f) return; char *line = NULL; size_t len = 0; gmi->line_count = 0; while (getline(&line, &len, f) != -1) { gmi->lines = realloc(gmi->lines, (gmi->line_count + 1) * sizeof(char*)); gmi->lines[gmi->line_count] = strdup(line); gmi->line_count++; } free(line); fclose(f); parse_properties(gmi); print_properties(&gmi->props); } void parse_properties(GMIFile *gmi) { memset(&gmi->props, 0, sizeof(GMIProperties)); gmi->props.total_lines = gmi->line_count; strcpy(gmi->props.encoding, "UTF-8"); int in_pre = 0; for (int i = 0; i < gmi->line_count; i++) { char *line = gmi->lines[i]; char *trimmed = line; while (*trimmed == ' ' || *trimmed == '\t') trimmed++; if (!*trimmed || *trimmed == '\n') continue; char *stripped = line; while (*stripped == ' ' || *stripped == '\t') stripped++; if (strncmp(stripped, "```", 3) == 0) { in_pre = !in_pre; gmi->props.pre_blocks++; // Simple alt text count (no extraction) gmi->props.pre_alt_count++; continue; } if (in_pre) continue; if (strncmp(stripped, "=>", 2) == 0) { gmi->props.link_lines++; gmi->props.links_count++; // Simplified } else if (stripped[0] == '#') { int hashes = 0; while (stripped[hashes] == '#') hashes++; if (hashes <= 3) gmi->props.heading_lines[hashes - 1]++; } else if (strncmp(stripped, "* ", 2) == 0) { gmi->props.list_items++; } else if (stripped[0] == '>') { gmi->props.quote_lines++; } else { gmi->props.text_lines++; } } gmi->props.final_pre_mode = in_pre; } void print_properties(GMIProperties *props) { printf("total_lines: %d\n", props->total_lines); printf("text_lines: %d\n", props->text_lines); printf("link_lines: %d\n", props->link_lines); printf("heading_lines: [%d, %d, %d]\n", props->heading_lines[0], props->heading_lines[1], props->heading_lines[2]); printf("list_items: %d\n", props->list_items); printf("quote_lines: %d\n", props->quote_lines); printf("pre_blocks: %d\n", props->pre_blocks); printf("links_count: %d\n", props->links_count); printf("pre_alt_count: %d\n", props->pre_alt_count); printf("final_pre_mode: %d\n", props->final_pre_mode); printf("encoding: %s\n", props->encoding); } void write_gmi(GMIFile *gmi, char *output_path) { FILE *f = fopen(output_path, "w"); if (!f) return; for (int i = 0; i < gmi->line_count; i++) { fprintf(f, "%s\r\n", gmi->lines[i]); // Canonical CRLF } fclose(f); } void free_gmi(GMIFile *gmi) { for (int i = 0; i < gmi->line_count; i++) free(gmi->lines[i]); free(gmi->lines); } // Usage example in main: // int main() { // GMIFile gmi = { .filepath = "example.gmi", .lines = NULL, .line_count = 0 }; // read_gmi(&gmi); // write_gmi(&gmi, "output.gmi"); // free_gmi(&gmi); // return 0; // } // ===== end task-261 .GMI ===== // ===== task-262 .GMK [C] ===== #include #include #include #include #include // For potential decompression, but skipped here typedef struct { int32_t form_id; int32_t version; int32_t game_id; uint8_t guid[16]; // Add other properties as needed int32_t gmver_settings; int32_t len_settings; int32_t gmver_triggers; int32_t num_triggers; double last_triggers; int32_t len_triggers; // ... (similar for constants, resources, etc.) int32_t num_resources[10]; // 0=sounds, 1=sprites, etc. double last_changed[10]; int32_t gmver_incl; int32_t num_incl; int32_t len_incl; int32_t gmver_ext; int32_t num_ext; int32_t gmver_info; int32_t len_info; int32_t last_instance; int32_t last_tile; int32_t gmver_exec; int32_t num_exec; int32_t exec_rooms[100]; // Assume max 100 int32_t gmver_tree; } GMKProperties; typedef struct { uint8_t* data; size_t size; size_t pos; GMKProperties props; } GMK; int32_t read_int(GMK* gmk) { int32_t v = (gmk->data[gmk->pos] << 24) | (gmk->data[gmk->pos + 1] << 16) | (gmk->data[gmk->pos + 2] << 8) | gmk->data[gmk->pos + 3]; gmk->pos += 4; return v; } double read_double(GMK* gmk) { // Simplified; use full double parse uint64_t bits = 0; for (int i = 0; i < 8; i++) { bits = (bits << 8) | gmk->data[gmk->pos + i]; } gmk->pos += 8; return *(double*)&bits; // Unsafe; use proper union } void read_guid(GMK* gmk) { memcpy(gmk->props.guid, &gmk->data[gmk->pos], 16); gmk->pos += 16; } void skip(GMK* gmk, size_t len) { gmk->pos += len; } void parse(GMK* gmk) { gmk->props.form_id = read_int(gmk); gmk->props.version = read_int(gmk); gmk->props.game_id = read_int(gmk); read_guid(gmk); gmk->props.gmver_settings = read_int(gmk); if (gmk->props.version >= 800) { gmk->props.len_settings = read_int(gmk); skip(gmk, gmk->props.len_settings); } gmk->props.gmver_triggers = read_int(gmk); gmk->props.num_triggers = read_int(gmk); if (gmk->props.version >= 800) { gmk->props.last_triggers = read_double(gmk); gmk->props.len_triggers = read_int(gmk); skip(gmk, gmk->props.len_triggers); } // Similar for constants... gmk->props.gmver_constants = read_int(gmk); gmk->props.num_constants = read_int(gmk); if (gmk->props.version >= 800) { gmk->props.last_constants = read_double(gmk); gmk->props.len_constants = read_int(gmk); skip(gmk, gmk->props.len_constants); } const char* kinds[10] = {"sounds", "sprites", "backgrounds", "paths", "scripts", "shaders", "fonts", "timelines", "objects", "rooms"}; for (int i = 0; i < 10; i++) { read_int(gmk); // gmver gmk->props.num_resources[i] = read_int(gmk); if (gmk->props.version >= 800) { gmk->props.last_changed[i] = read_double(gmk); skip(gmk, read_int(gmk)); } } // Similar for included, extensions (skip names), info, options, exec rooms, tree... gmk->props.gmver_incl = read_int(gmk); gmk->props.num_incl = read_int(gmk); if (gmk->props.version >= 800) { gmk->props.len_incl = read_int(gmk); skip(gmk, gmk->props.len_incl); } gmk->props.gmver_ext = read_int(gmk); gmk->props.num_ext = read_int(gmk); for (int i = 0; i < gmk->props.num_ext; i++) { skip(gmk, read_int(gmk)); } gmk->props.gmver_info = read_int(gmk); gmk->props.len_info = read_int(gmk); skip(gmk, gmk->props.len_info); gmk->props.last_instance = read_int(gmk); gmk->props.last_tile = read_int(gmk); gmk->props.gmver_exec = read_int(gmk); gmk->props.num_exec = read_int(gmk); for (int i = 0; i < gmk->props.num_exec; i++) { gmk->props.exec_rooms[i] = read_int(gmk); } gmk->props.gmver_tree = read_int(gmk); skip(gmk, gmk->size - gmk->pos); } void print_properties(GMK* gmk) { printf("Form ID: %d\n", gmk->props.form_id); printf("Version: %d\n", gmk->props.version); // ... print all printf("Game ID: %d\n", gmk->props.game_id); // GUID as hex... for (int i = 0; i < 10; i++) printf("Num %s: %d\n", /*kind*/, gmk->props.num_resources[i]); // etc. } void write(GMK* gmk, const char* output) { FILE* f = fopen(output, "wb"); fwrite(gmk->data, 1, gmk->size, f); fclose(f); printf("Wrote to %s\n", output); } int main() { GMK gmk; // Load file into gmk.data, gmk.size FILE* f = fopen("example.gmk", "rb"); fseek(f, 0, SEEK_END); gmk.size = ftell(f); fseek(f, 0, SEEK_SET); gmk.data = malloc(gmk.size); fread(gmk.data, 1, gmk.size, f); fclose(f); gmk.pos = 0; parse(&gmk); print_properties(&gmk); write(&gmk, "output.gmk"); free(gmk.data); return 0; } // ===== end task-262 .GMK ===== // ===== task-263 .GML [C] ===== #include #include #include #include #define MAX_LINE 1024 #define MAX_KEYS 12 typedef struct { char *keys[MAX_KEYS]; char *values[MAX_KEYS]; } GMLProperties; typedef struct { GMLProperties properties; char *data; // Raw content for simplicity size_t data_size; } GMLHandler; void init_properties(GMLHandler *handler) { handler->properties.keys[0] = "File extension"; handler->properties.values[0] = ".gml"; handler->properties.keys[1] = "MIME type"; handler->properties.values[1] = "text/vnd.gml"; handler->properties.keys[2] = "Encoding"; handler->properties.values[2] = "7-bit ASCII"; handler->properties.keys[3] = "File type"; handler->properties.values[3] = "Text/plain"; handler->properties.keys[4] = "Structure"; handler->properties.values[4] = "Hierarchical key-value pairs"; handler->properties.keys[5] = "Data types supported"; handler->properties.values[5] = "Integers, floats, strings, lists"; handler->properties.keys[6] = "Byte order"; handler->properties.values[6] = "Not applicable"; handler->properties.keys[7] = "Magic number or signature"; handler->properties.values[7] = "None"; handler->properties.keys[8] = "Portability"; handler->properties.values[8] = "High"; handler->properties.keys[9] = "Extensibility"; handler->properties.values[9] = "Allows user-defined keys"; handler->properties.keys[10] = "Compression"; handler->properties.values[10] = "Not built-in"; handler->properties.keys[11] = "Typical file size"; handler->properties.values[11] = "Variable"; } GMLHandler *create_gml_handler(const char *filepath) { GMLHandler *handler = malloc(sizeof(GMLHandler)); init_properties(handler); handler->data = NULL; handler->data_size = 0; if (filepath) { read_gml(handler, filepath); } return handler; } void read_gml(GMLHandler *handler, const char *filepath) { FILE *fp = fopen(filepath, "r"); if (!fp) { perror("Failed to open file"); return; } fseek(fp, 0, SEEK_END); handler->data_size = ftell(fp); fseek(fp, 0, SEEK_SET); handler->data = malloc(handler->data_size + 1); fread(handler->data, 1, handler->data_size, fp); handler->data[handler->data_size] = '\0'; fclose(fp); char size_str[32]; sprintf(size_str, "%zu bytes", handler->data_size); handler->properties.values[11] = strdup(size_str); handler->properties.values[2] = "7-bit ASCII (verified)"; // Basic parsing could be added here if needed } void write_gml(GMLHandler *handler, const char *filepath) { FILE *fp = fopen(filepath, "w"); if (!fp) { perror("Failed to open file for writing"); return; } fwrite(handler->data, 1, handler->data_size, fp); fclose(fp); } void print_properties(GMLHandler *handler) { for (int i = 0; i < MAX_KEYS; i++) { printf("%s: %s\n", handler->properties.keys[i], handler->properties.values[i]); } } void destroy_gml_handler(GMLHandler *handler) { free(handler->data); free(handler->properties.values[11]); // Dynamic allocation for size free(handler); } // Example usage: // int main() { // GMLHandler *handler = create_gml_handler("example.gml"); // print_properties(handler); // write_gml(handler, "output.gml"); // destroy_gml_handler(handler); // return 0; // } // ===== end task-263 .GML ===== // ===== task-264 .GO [C++] ===== #include #include #include #include #include #include class GoFile { private: std::string filename; std::map> header; std::vector> stanzas; // type + tags (tags as map>) public: GoFile(const std::string& fn) : filename(fn) { parse(); } void parse() { std::ifstream file(filename); if (!file.is_open()) { std::cerr << "Error opening file: " << filename << std::endl; return; } std::string line; std::map> currentStanzaTags; std::string currentStanzaType; bool inHeader = true; while (std::getline(file, line)) { line.erase(0, line.find_first_not_of(" \t")); // Trim left line.erase(line.find_last_not_of(" \t") + 1); // Trim right if (line.empty() || line[0] == '!') continue; if (line[0] == '[') { inHeader = false; if (!currentStanzaType.empty()) { std::map stanza; stanza["type"] = currentStanzaType; for (const auto& pair : currentStanzaTags) { std::stringstream ss; for (const auto& val : pair.second) { ss << val << "; "; } stanza[pair.first] = ss.str(); } stanzas.push_back(stanza); } currentStanzaType = line; currentStanzaTags.clear(); } else { size_t colonPos = line.find(':'); if (colonPos != std::string::npos) { std::string tag = line.substr(0, colonPos); tag.erase(tag.find_last_not_of(" \t") + 1); // Trim std::string value = line.substr(colonPos + 1); value.erase(0, value.find_first_not_of(" \t")); size_t commentPos = value.find('!'); if (commentPos != std::string::npos) value = value.substr(0, commentPos); value.erase(value.find_last_not_of(" \t") + 1); if (inHeader) { header[tag].push_back(value); } else { currentStanzaTags[tag].push_back(value); } } } } if (!currentStanzaType.empty()) { std::map stanza; stanza["type"] = currentStanzaType; for (const auto& pair : currentStanzaTags) { std::stringstream ss; for (const auto& val : pair.second) { ss << val << "; "; } stanza[pair.first] = ss.str(); } stanzas.push_back(stanza); } file.close(); } std::map> getHeader() const { return header; } std::vector> getStanzas() const { return stanzas; } void printProperties() const { std::cout << "Header Properties:" << std::endl; for (const auto& pair : header) { for (const auto& value : pair.second) { std::cout << pair.first << ": " << value << std::endl; } } std::cout << "\nStanzas:" << std::endl; for (size_t i = 0; i < stanzas.size(); ++i) { const auto& stanza = stanzas[i]; std::cout << "Stanza " << (i + 1) << ": " << stanza.at("type") << std::endl; for (const auto& pair : stanza) { if (pair.first != "type") { std::cout << " " << pair.first << ": " << pair.second << std::endl; } } } } void write(const std::string& outputFilename) const { std::ofstream outFile(outputFilename); if (!outFile.is_open()) { std::cerr << "Error opening output file: " << outputFilename << std::endl; return; } // Write header for (const auto& pair : header) { for (const auto& value : pair.second) { outFile << pair.first << ": " << value << "\n"; } } outFile << "\n"; // Write stanzas for (const auto& stanza : stanzas) { outFile << stanza.at("type") << "\n"; for (const auto& pair : stanza) { if (pair.first != "type") { // Split semi-colon for multi-values std::string values = pair.second; size_t pos = 0; while ((pos = values.find("; ")) != std::string::npos) { outFile << pair.first << ": " << values.substr(0, pos) << "\n"; values.erase(0, pos + 2); } if (!values.empty()) outFile << pair.first << ": " << values << "\n"; } } outFile << "\n"; } outFile.close(); } }; // ===== end task-264 .GO ===== // ===== task-265 .GODOT [C] ===== #include #include #include #include #define MAX_LINE 1024 #define MAX_SECTIONS 100 #define MAX_KEYS 200 typedef struct { char sections[MAX_SECTIONS][MAX_LINE]; char keys[MAX_SECTIONS][MAX_KEYS][MAX_LINE]; char values[MAX_SECTIONS][MAX_KEYS][MAX_LINE]; int num_sections; int num_keys[MAX_SECTIONS]; } GodotProject; void init_godot_project(GodotProject *proj) { proj->num_sections = 0; memset(proj->num_keys, 0, sizeof(proj->num_keys)); } void load_godot_project(GodotProject *proj, const char *file_path) { FILE *file = fopen(file_path, "r"); if (!file) { fprintf(stderr, "Error opening file: %s\n", file_path); return; } char line[MAX_LINE]; char *current_section = NULL; int section_idx = -1; while (fgets(line, sizeof(line), file)) { // Trim trailing newline line[strcspn(line, "\n")] = 0; // Trim spaces char *start = line; while (isspace(*start)) start++; char *end = start + strlen(start) - 1; while (end > start && isspace(*end)) end--; *(end + 1) = 0; if (!*start || start[0] == ';' || start[0] == '#') continue; if (start[0] == '[' && end[0] == ']') { // New section current_section = start + 1; current_section[end - start - 1] = 0; section_idx = proj->num_sections++; strcpy(proj->sections[section_idx], current_section); proj->num_keys[section_idx] = 0; continue; } char *eq = strchr(start, '='); if (eq && section_idx >= 0) { *eq = 0; char *key_start = start; while (isspace(*key_start)) key_start++; char *key_end = eq - 1; while (isspace(*key_end)) key_end--; *(key_end + 1) = 0; char *val_start = eq + 1; while (isspace(*val_start)) val_start++; char *val = val_start; if (*val_start == '"' && val_start[strlen(val_start) - 1] == '"') { val_start++; val_start[strlen(val_start) - 1] = 0; val = val_start; } int key_idx = proj->num_keys[section_idx]++; strcpy(proj->keys[section_idx][key_idx], key_start); strcpy(proj->values[section_idx][key_idx], val); } } fclose(file); } void print_properties(const GodotProject *proj) { printf("Parsed .GODOT Properties:\n"); for (int s = 0; s < proj->num_sections; s++) { printf("[%s]\n", proj->sections[s]); for (int k = 0; k < proj->num_keys[s]; k++) { printf(" %s = %s\n", proj->keys[s][k], proj->values[s][k]); } printf("\n"); } } void write_properties(const GodotProject *proj, const char *output_path) { FILE *file = fopen(output_path, "w"); if (!file) { fprintf(stderr, "Error writing file: %s\n", output_path); return; } for (int s = 0; s < proj->num_sections; s++) { fprintf(file, "[%s]\n", proj->sections[s]); for (int k = 0; k < proj->num_keys[s]; k++) { fprintf(file, "%s = %s\n", proj->keys[s][k], proj->values[s][k]); } fprintf(file, "\n"); } fclose(file); printf("Wrote properties to %s.\n", output_path); } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } GodotProject proj; init_godot_project(&proj); load_godot_project(&proj, argv[1]); print_properties(&proj); write_properties(&proj, "output.godot"); return 0; } // ===== end task-265 .GODOT ===== // ===== task-266 .GPX [C] ===== #include #include #include typedef struct { xmlDocPtr doc; } GPXParser; void gpx_parser_init(GPXParser *parser, const char *file_path) { parser->doc = xmlReadFile(file_path, NULL, 0); if (parser->doc == NULL) { fprintf(stderr, "Error parsing file\n"); } } void print_properties(GPXParser *parser) { if (!parser->doc) return; xmlNodePtr root = xmlDocGetRootElement(parser->doc); print_recursive(root, 0); } void print_recursive(xmlNodePtr node, int indent) { if (node == NULL || node->type != XML_ELEMENT_NODE) return; // Print indent for (int i = 0; i < indent; i++) printf(" "); printf("%s:\n", node->name); // Attributes xmlAttrPtr attr = node->properties; if (attr != NULL) { for (int i = 0; i < indent + 1; i++) printf(" "); printf("Attributes: "); while (attr != NULL) { printf("%s=%s ", attr->name, xmlNodeListGetString(parser->doc, attr->children, 1)); attr = attr->next; } printf("\n"); } // Text xmlChar *text = xmlNodeListGetString(parser->doc, node->children, 1); if (text && xmlStrlen(text) > 0) { for (int i = 0; i < indent + 1; i++) printf(" "); printf("Text: %s\n", text); xmlFree(text); } // Children for (xmlNodePtr child = node->children; child; child = child->next) { if (child->type == XML_ELEMENT_NODE) { print_recursive(child, indent + 1); } } } void gpx_parser_write(GPXParser *parser, const char *output_path) { if (!parser->doc) return; xmlSaveFormatFileEnc(output_path, parser->doc, "UTF-8", 1); } void gpx_parser_free(GPXParser *parser) { xmlFreeDoc(parser->doc); xmlCleanupParser(); } // Usage: // GPXParser parser = {0}; // gpx_parser_init(&parser, "sample.gpx"); // print_properties(&parser); // gpx_parser_write(&parser, "output.gpx"); // gpx_parser_free(&parser); // ===== end task-266 .GPX ===== // ===== task-267 .GRAPHML [C] ===== #include #include #include #include #include typedef struct { xmlDocPtr doc; xmlNodePtr root; // Properties (simplified; use arrays for lists) char* namespace; char* root_element; int num_keys; // For simplicity, print during extract; expand as needed int num_graphs; int num_data; int num_desc; int supports_hierarchy; int num_hyperedges; int num_endpoints; int num_ports; int num_locators; } GraphML; GraphML* graphml_new(const char* file_path) { GraphML* g = malloc(sizeof(GraphML)); g->doc = xmlReadFile(file_path, NULL, 0); if (!g->doc) { fprintf(stderr, "Failed to load file.\n"); free(g); return NULL; } g->root = xmlDocGetRootElement(g->doc); graphml_extract_properties(g); return g; } GraphML* graphml_new_from_string(const char* xml_str) { GraphML* g = malloc(sizeof(GraphML)); g->doc = xmlReadMemory(xml_str, strlen(xml_str), NULL, NULL, 0); if (!g->doc) { fprintf(stderr, "Failed to parse string.\n"); free(g); return NULL; } g->root = xmlDocGetRootElement(g->doc); graphml_extract_properties(g); return g; } void graphml_read(GraphML* g, const char* source, int is_file) { // Reuse new logic; omitted for brevity } void graphml_write(GraphML* g, const char* file_path) { if (!g->doc || !file_path) return; xmlSaveFormatFileEnc(file_path, g->doc, "UTF-8", 1); // Pretty print } void graphml_extract_properties(GraphML* g) { if (!g->root) return; g->namespace = xmlGetNsList(g->doc, g->root) ? (char*)"http://graphml.graphdrawing.org/xmlns" : (char*)"Default"; g->root_element = (char*)g->root->name; // Count keys xmlNodePtr cur = g->root->children; int key_count = 0; while (cur) { if (cur->type == XML_ELEMENT_NODE && xmlStrEqual(cur->name, (xmlChar*)"key")) key_count++; cur = cur->next; } g->num_keys = key_count; // Similar for others (pseudocode-like for brevity; full traversal needed) g->num_graphs = xmlGetNsProp(g->root, (xmlChar*)"graph", NULL) ? 1 : 0; // Simplified; use xpath for counts // Use libxml XPath for accurate counts: e.g., xmlXPathEval((xmlChar*)"count(//graph)", ctx) // Assume implementation: g->num_data = count_nodes(g->root, "data"); // etc. // Hierarchy: check for node/graph or edge/graph g->supports_hierarchy = 0; // Set via traversal } void graphml_print_properties(GraphML* g) { if (!g) { printf("No properties loaded.\n"); return; } printf("GRAPHML Properties:\n"); printf("Namespace: %s\n", g->namespace); printf("Root Element: %s\n", g->root_element); printf("\nNumber of Keys: %d\n", g->num_keys); // Traverse and print keys: cur = g->root->children; while(cur) { if key: printf("Key: id=%s, for=%s\n", xmlGetProp(cur, "id"), xmlGetProp(cur, "for")); cur=cur->next; } printf("\nNumber of Graphs: %d\n", g->num_graphs); // Similar traversal for graphs, nodes, edges (use xmlGetProp for attrs) printf("\nData Elements: %d\n", g->num_data); printf("Desc Elements: %d\n", g->num_desc); printf("Supports Hierarchy: %s\n", g->supports_hierarchy ? "Yes" : "No"); printf("Hyperedges: %d\n", g->num_hyperedges); printf("Endpoints: %d\n", g->num_endpoints); printf("Ports: %d\n", g->num_ports); printf("Locators: %d\n", g->num_locators); } void graphml_free(GraphML* g) { if (g) { xmlFreeDoc(g->doc); free(g->namespace); free(g->root_element); free(g); } xmlCleanupParser(); } // Example usage: // GraphML* g = graphml_new("example.graphml"); // graphml_print_properties(g); // graphml_write(g, "output.graphml"); // graphml_free(g); // ===== end task-267 .GRAPHML ===== // ===== task-268 .GRB [C] ===== #include #include #include #include typedef struct { uint64_t msg_len; char grib_id[5]; // Sec1 uint32_t sec1_len; uint16_t center; uint16_t subcenter; uint8_t master_ver; uint8_t local_ver; uint8_t ref_sig; uint16_t year; uint8_t month; uint8_t day; uint8_t hour; uint8_t minute; uint8_t second; uint8_t prod_status; uint8_t data_type; // Sec3 (Template 3.0) uint32_t sec3_len; uint8_t source; uint32_t ndp; uint16_t temp_num; uint8_t shape; double scale_lat; uint32_t ni; uint32_t nj; double la1; double lo1; uint8_t res; double dx; double dy; uint8_t scan; // Add Sec4/Sec5 similarly } GRIBProperties; typedef struct { uint8_t* data; size_t size; GRIBProperties props; } GRIB2File; uint32_t read_uint32(const uint8_t* data, size_t* pos) { uint32_t v = (data[*pos] << 24) | (data[(*pos)+1] << 16) | (data[(*pos)+2] << 8) | data[(*pos)+3]; *pos += 4; return v; } uint16_t read_uint16(const uint8_t* data, size_t* pos) { uint16_t v = (data[*pos] << 8) | data[(*pos)+1]; *pos += 2; return v; } uint8_t read_uint8(const uint8_t* data, size_t* pos) { uint8_t v = data[*pos]; *pos += 1; return v; } int16_t read_int16(const uint8_t* data, size_t* pos) { int16_t v = (int16_t)read_uint16(data, pos); return v; } float read_float32(const uint8_t* data, size_t* pos) { // Simple IEEE unpack (big-endian) uint32_t bits = read_uint32(data, pos); float* pf = (float*)&bits; return *pf; } void read_grb(GRIB2File* g, const char* filename) { FILE* f = fopen(filename, "rb"); fseek(f, 0, SEEK_END); g->size = ftell(f); fseek(f, 0, SEEK_SET); g->data = malloc(g->size); fread(g->data, 1, g->size, f); fclose(f); size_t pos = 0; // Section 0 memcpy(g->props.grib_id, g->data, 4); g->props.grib_id[4] = '\0'; pos += 8; uint32_t len_high = read_uint32(g->data, &pos); uint32_t len_low = read_uint32(g->data, &pos); g->props.msg_len = ((uint64_t)len_high << 32) | len_low; // Section 1 g->props.sec1_len = read_uint32(g->data, &pos); read_uint8(g->data, &pos); // sec num g->props.center = read_uint16(g->data, &pos); g->props.subcenter = read_uint16(g->data, &pos); g->props.master_ver = read_uint8(g->data, &pos); g->props.local_ver = read_uint8(g->data, &pos); g->props.ref_sig = read_uint8(g->data, &pos); g->props.year = read_uint16(g->data, &pos); g->props.month = read_uint8(g->data, &pos); g->props.day = read_uint8(g->data, &pos); g->props.hour = read_uint8(g->data, &pos); g->props.minute = read_uint8(g->data, &pos); g->props.second = read_uint8(g->data, &pos); g->props.prod_status = read_uint8(g->data, &pos); g->props.data_type = read_uint8(g->data, &pos); pos += (g->props.sec1_len - 21); // Section 3 Template 3.0 g->props.sec3_len = read_uint32(g->data, &pos); read_uint8(g->data, &pos); // sec num g->props.source = read_uint8(g->data, &pos); g->props.ndp = read_uint32(g->data, &pos); read_uint8(g->data, &pos); // oct_list read_uint8(g->data, &pos); // interp g->props.temp_num = read_uint16(g->data, &pos); g->props.shape = read_uint8(g->data, &pos); int32_t scale_lat_raw = (int32_t)read_uint32(g->data, &pos); g->props.scale_lat = (double)scale_lat_raw / (1 << 8); g->props.ni = read_uint32(g->data, &pos); g->props.nj = read_uint32(g->data, &pos); g->props.la1 = read_uint32(g->data, &pos) / 1e7; g->props.lo1 = read_uint32(g->data, &pos) / 1e7; g->props.res = read_uint8(g->data, &pos); g->props.dx = read_uint32(g->data, &pos) / 1e6; g->props.dy = read_uint32(g->data, &pos) / 1e6; g->props.scan = read_uint8(g->data, &pos); pos += (g->props.sec3_len - 40); // Similar for Sec4/Sec5 // ... } void write_grb(const GRIB2File* g, const char* filename) { FILE* f = fopen(filename, "wb"); // Section 0 fwrite("GRIB", 1, 4, f); fwrite("\x00\x00\x00\x02", 1, 4, f); // Reserved + edition uint64_t dummy_len = 1000; uint32_t high = dummy_len >> 32; uint32_t low = dummy_len & 0xFFFFFFFF; fwrite(&high, 4, 1, f); fwrite(&low, 4, 1, f); // Section 1 uint32_t sec1_len = 21; fwrite(&sec1_len, 4, 1, f); uint8_t sec_num = 1; fwrite(&sec_num, 1, 1, f); uint16_t center = g->props.center; fwrite(¢er, 2, 1, f); // Continue packing other fields... // End uint32_t end = 0x77777777; fwrite(&end, 4, 1, f); fclose(f); } void print_properties(const GRIBProperties* p) { printf("GRIB ID: %s\n", p->grib_id); printf("Msg Len: %lu\n", p->msg_len); printf("Center: %u\n", p->center); printf("Year: %u\n", p->year); // Print all... printf("Scale Lat: %f\n", p->scale_lat); printf("NI: %u, NJ: %u\n", p->ni, p->nj); // ... } int main() { GRIB2File g = {0}; read_grb(&g, "test.grb"); print_properties(&g.props); write_grb(&g, "output.grb"); free(g.data); return 0; } // ===== end task-268 .GRB ===== // ===== task-269 .GREXLI [C] ===== #include #include #include #include #define MAGIC "GREXLI" #define VERSION 1 typedef struct { char filename[256]; // Max 255 + null uint64_t file_size; uint8_t* data; // Dynamic alloc } GrexliFile; typedef struct { char magic[7]; // Null-terminated uint8_t version; uint32_t num_files; GrexliFile* files; } GrexliArchive; void print_properties(GrexliArchive* arch) { printf("GREXLI Properties:\n"); printf("Magic: %s\n", arch->magic); printf("Version: %u\n", arch->version); printf("Num Files: %u\n", arch->num_files); for (uint32_t i = 0; i < arch->num_files; i++) { printf(" File: %s (size: %lu bytes)\n", arch->files[i].filename, arch->files[i].file_size); if (arch->files[i].data) { printf(" Preview: %.*s\n", (int)sizeof(arch->files[i].data), arch->files[i].data); } } printf("---\n"); } int read_grexli(const char* filepath, GrexliArchive* arch) { FILE* fp = fopen(filepath, "rb"); if (!fp) return -1; fread(arch->magic, 1, 6, fp); arch->magic[6] = '\0'; if (strncmp(arch->magic, MAGIC, 6) != 0) { fclose(fp); return -1; } fread(&arch->version, 1, 1, fp); if (arch->version != VERSION) { fclose(fp); return -1; } fread(&arch->num_files, 1, 4, fp); // Assume little-endian arch->files = malloc(arch->num_files * sizeof(GrexliFile)); for (uint32_t i = 0; i < arch->num_files; i++) { uint8_t name_len; fread(&name_len, 1, 1, fp); fread(arch->files[i].filename, 1, name_len, fp); arch->files[i].filename[name_len] = '\0'; fread(&arch->files[i].file_size, 1, 8, fp); arch->files[i].data = malloc(arch->files[i].file_size); fread(arch->files[i].data, 1, arch->files[i].file_size, fp); } fclose(fp); print_properties(arch); return 0; } int write_grexli(const char* filepath, GrexliArchive* arch) { FILE* fp = fopen(filepath, "wb"); if (!fp) return -1; fwrite(MAGIC, 1, 6, fp); fwrite(&VERSION, 1, 1, fp); fwrite(&arch->num_files, 1, 4, fp); // Little-endian print_properties(arch); for (uint32_t i = 0; i < arch->num_files; i++) { uint8_t name_len = strlen(arch->files[i].filename); fwrite(&name_len, 1, 1, fp); fwrite(arch->files[i].filename, 1, name_len, fp); fwrite(&arch->files[i].file_size, 1, 8, fp); if (arch->files[i].data) { fwrite(arch->files[i].data, 1, arch->files[i].file_size, fp); } } fclose(fp); printf("Written to %s\n", filepath); return 0; } void free_archive(GrexliArchive* arch) { for (uint32_t i = 0; i < arch->num_files; i++) { free(arch->files[i].data); } free(arch->files); } // Example usage in main: // GrexliArchive arch = {0}; // read_grexli("example.grexli", &arch); // free_archive(&arch); // ===== end task-269 .GREXLI ===== // ===== task-270 .GRIB [C] ===== #include #include #include #include typedef struct { uint8_t edition; uint8_t discipline; uint32_t total_length; uint32_t sec1_length; uint32_t sec2_length; uint32_t sec3_length; uint32_t sec4_length; uint32_t sec5_length; uint32_t sec6_length; uint32_t sec7_length; uint16_t center; uint16_t sub_center; uint8_t master_version; uint8_t local_version; uint8_t ref_time_sig; uint16_t ref_year; uint8_t ref_month; uint8_t ref_day; uint8_t ref_hour; uint8_t ref_minute; uint8_t ref_second; uint8_t production_status; uint8_t data_type; uint8_t grid_source; uint32_t num_points; uint16_t grid_template_num; // Add more as needed } GRIBProperties; typedef struct { FILE* file; GRIBProperties props; } GRIB2Parser; void read_grib2(GRIB2Parser* parser, const char* filename) { parser->file = fopen(filename, "rb"); if (!parser->file) { perror("File open error"); return; } fseek(parser->file, 0, SEEK_END); long size = ftell(parser->file); fseek(parser->file, 0, SEEK_SET); uint8_t* buffer = malloc(size); fread(buffer, 1, size, parser->file); int pos = 0; // Section 0 if (memcmp(buffer + pos, "GRIB", 4) != 0) { fprintf(stderr, "Not a GRIB file\n"); free(buffer); return; } pos += 4; parser->props.total_length = (buffer[pos] << 24) | (buffer[pos+1] << 16) | (buffer[pos+2] << 8) | buffer[pos+3]; pos += 4; parser->props.edition = buffer[pos]; pos += 1; if (parser->props.edition != 2) { fprintf(stderr, "Only GRIB2 supported\n"); free(buffer); return; } pos += 1; // Skip parser->props.discipline = buffer[pos]; pos += 1; parser->props.sec1_length = (buffer[pos] << 24) | (buffer[pos+1] << 16) | (buffer[pos+2] << 8) | buffer[pos+3]; pos += 4; parser->props.sec2_length = (buffer[pos] << 24) | (buffer[pos+1] << 16) | (buffer[pos+2] << 8) | buffer[pos+3]; pos += 4; parser->props.sec3_length = (buffer[pos] << 24) | (buffer[pos+1] << 16) | (buffer[pos+2] << 8) | buffer[pos+3]; pos += 4; parser->props.sec4_length = (buffer[pos] << 24) | (buffer[pos+1] << 16) | (buffer[pos+2] << 8) | buffer[pos+3]; pos += 4; parser->props.sec5_length = (buffer[pos] << 24) | (buffer[pos+1] << 16) | (buffer[pos+2] << 8) | buffer[pos+3]; pos += 4; parser->props.sec6_length = (buffer[pos] << 24) | (buffer[pos+1] << 16) | (buffer[pos+2] << 8) | buffer[pos+3]; pos += 4; parser->props.sec7_length = (buffer[pos] << 24) | (buffer[pos+1] << 16) | (buffer[pos+2] << 8) | buffer[pos+3]; pos += 4; if (memcmp(buffer + pos, "7777", 4) != 0) { fprintf(stderr, "Invalid end marker\n"); free(buffer); return; } // Section 1 (simplified) pos = 16; pos += 5; parser->props.center = (buffer[pos] << 8) | buffer[pos+1]; pos += 2; parser->props.sub_center = (buffer[pos] << 8) | buffer[pos+1]; pos += 2; parser->props.master_version = buffer[pos]; pos += 1; parser->props.local_version = buffer[pos]; pos += 1; parser->props.ref_time_sig = buffer[pos]; pos += 1; parser->props.ref_year = (buffer[pos] << 8) | buffer[pos+1]; pos += 2; parser->props.ref_month = buffer[pos]; pos += 1; parser->props.ref_day = buffer[pos]; pos += 1; parser->props.ref_hour = buffer[pos]; pos += 1; parser->props.ref_minute = buffer[pos]; pos += 1; parser->props.ref_second = buffer[pos]; pos += 1; parser->props.production_status = buffer[pos]; pos += 1; parser->props.data_type = buffer[pos]; // Sections 3-5 similar (bit shifts for big-endian) pos += parser->props.sec1_length - 21; if (parser->props.sec2_length > 0) pos += parser->props.sec2_length; pos += 5; parser->props.grid_source = buffer[pos]; pos += 1; parser->props.num_points = (buffer[pos] << 24) | (buffer[pos+1] << 16) | (buffer[pos+2] << 8) | buffer[pos+3]; pos += 4; parser->props.grid_template_num = (buffer[pos] << 8) | buffer[pos+1]; free(buffer); } void print_properties(GRIBProperties* props) { printf("edition: %d\n", props->edition); printf("discipline: %d\n", props->discipline); printf("total_length: %u\n", props->total_length); // ... print all fields similarly printf("center: %d\n", props->center); // Extend for all } void write_grib2(GRIB2Parser* parser, const char* output) { FILE* out = fopen(output, "wb"); if (!out) return; fseek(parser->file, 0, SEEK_SET); char buf[1024]; size_t len; while ((len = fread(buf, 1, sizeof(buf), parser->file)) > 0) { fwrite(buf, 1, len, out); } fclose(out); } int main(int argc, char** argv) { if (argc < 2) return 1; GRIB2Parser parser = {0}; read_grib2(&parser, argv[1]); print_properties(&parser.props); write_grib2(&parser, "output.grib2"); fclose(parser.file); return 0; } // ===== end task-270 .GRIB ===== // ===== task-271 .GRP [C] ===== #include #include #include #include typedef struct { uint8_t x_offset; uint8_t y_offset; uint16_t unknown; uint32_t data_offset; uint16_t* line_offsets; } Frame; typedef struct { char* filename; uint16_t frame_count; uint16_t width; uint16_t height; Frame* frames; } GRPFile; GRPFile* grp_create(const char* filename) { GRPFile* grp = malloc(sizeof(GRPFile)); grp->filename = strdup(filename); grp->frames = NULL; return grp; } void grp_destroy(GRPFile* grp) { if (grp->frames) { for (int i = 0; i < grp->frame_count; i++) { free(grp->frames[i].line_offsets); } free(grp->frames); } free(grp->filename); free(grp); } void grp_read(GRPFile* grp) { FILE* f = fopen(grp->filename, "rb"); if (!f) { perror("Open failed"); return; } fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); int offset = 0; grp->frame_count = *(uint16_t*)(data + offset); offset += 2; grp->width = *(uint16_t*)(data + offset); offset += 2; grp->height = *(uint16_t*)(data + offset); offset += 2; grp->frames = malloc(grp->frame_count * sizeof(Frame)); for (int i = 0; i < grp->frame_count; i++) { Frame* frame = &grp->frames[i]; frame->x_offset = data[offset++]; frame->y_offset = data[offset++]; frame->unknown = *(uint16_t*)(data + offset); offset += 2; frame->data_offset = *(uint32_t*)(data + offset); offset += 4; frame->line_offsets = malloc(grp->height * sizeof(uint16_t)); int line_off = frame->data_offset; for (int j = 0; j < grp->height; j++) { frame->line_offsets[j] = *(uint16_t*)(data + line_off); line_off += 2; } } free(data); grp_print_properties(grp); } void grp_print_properties(GRPFile* grp) { printf("Frame Count: %u\n", grp->frame_count); printf("Width: %u\n", grp->width); printf("Height: %u\n", grp->height); printf("\nFrame Table:\n"); for (int i = 0; i < grp->frame_count; i++) { Frame* frame = &grp->frames[i]; printf("Frame %d: X-Offset=%u, Y-Offset=%u, Unknown=%u, Data Offset=%u\n", i, frame->x_offset, frame->y_offset, frame->unknown, frame->data_offset); printf(" Line Offsets: "); for (int j = 0; j < grp->height; j++) { printf("%u ", frame->line_offsets[j]); } printf("\n"); } } void grp_write(GRPFile* grp, const char* output_filename) { FILE* f = fopen(output_filename, "wb"); if (!f) { perror("Write failed"); return; } int offset = 0; fwrite(&grp->frame_count, 2, 1, f); offset += 2; fwrite(&grp->width, 2, 1, f); offset += 2; fwrite(&grp->height, 2, 1, f); offset += 2; int frame_table_end = offset + (8 * grp->frame_count); int current_data_pos = frame_table_end; for (int i = 0; i < grp->frame_count; i++) { Frame* frame = &grp->frames[i]; fwrite(&frame->x_offset, 1, 1, f); offset += 1; fwrite(&frame->y_offset, 1, 1, f); offset += 1; fwrite(&frame->unknown, 2, 1, f); offset += 2; uint32_t pos = current_data_pos; fwrite(&pos, 4, 1, f); offset += 4; // Write line offsets int line_pos = current_data_pos; for (int j = 0; j < grp->height; j++) { fwrite(&frame->line_offsets[j], 2, 1, f); line_pos += 2; } current_data_pos += (2 * grp->height); // + line data } fclose(f); printf("Written to %s\n", output_filename); } // Usage int main() { GRPFile* grp = grp_create("example.grp"); grp_read(grp); // grp_write(grp, "output.grp"); grp_destroy(grp); return 0; } // ===== end task-271 .GRP ===== // ===== task-272 .GSF [C] ===== #include #include #include #include #include // Optional for decompression typedef struct { char filename[256]; uint8_t* data; size_t data_size; char signature[4]; // Null-terminated uint8_t version; uint32_t reserved_size; uint32_t compressed_size; uint32_t crc32; uint8_t* reserved_data; uint8_t* compressed_program; char tag_signature[6]; // Null-terminated char* tag_data; } GSFReader; void gsf_read(GSFReader* gsf) { FILE* f = fopen(gsf->filename, "rb"); if (!f) { perror("Error opening file"); return; } fseek(f, 0, SEEK_END); gsf->data_size = ftell(f); fseek(f, 0, SEEK_SET); gsf->data = malloc(gsf->data_size); fread(gsf->data, 1, gsf->data_size, f); fclose(f); uint8_t* ptr = gsf->data; memcpy(gsf->signature, ptr, 3); gsf->signature[3] = '\0'; ptr += 3; gsf->version = *ptr; ptr += 1; gsf->reserved_size = *(uint32_t*)ptr; ptr += 4; gsf->compressed_size = *(uint32_t*)ptr; ptr += 4; gsf->crc32 = *(uint32_t*)ptr; ptr += 4; gsf->reserved_data = malloc(gsf->reserved_size); memcpy(gsf->reserved_data, ptr, gsf->reserved_size); ptr += gsf->reserved_size; gsf->compressed_program = malloc(gsf->compressed_size); memcpy(gsf->compressed_program, ptr, gsf->compressed_size); ptr += gsf->compressed_size; if (ptr < gsf->data + gsf->data_size) { memcpy(gsf->tag_signature, ptr, 5); gsf->tag_signature[5] = '\0'; ptr += 5; gsf->tag_data = malloc(gsf->data_size - (ptr - gsf->data) + 1); memcpy(gsf->tag_data, ptr, gsf->data_size - (ptr - gsf->data)); gsf->tag_data[gsf->data_size - (ptr - gsf->data)] = '\0'; } print_properties(gsf); } void gsf_write(GSFReader* gsf, const char* output_filename) { FILE* f = fopen(output_filename, "wb"); if (!f) { perror("Error writing file"); return; } fwrite(gsf->data, 1, gsf->data_size, f); fclose(f); printf("Wrote to %s\n", output_filename); } void print_properties(GSFReader* gsf) { printf("Signature: %s\n", gsf->signature); printf("Version: 0x%02x (%s)\n", gsf->version, gsf->version == 0x22 ? "GSF" : "Unknown"); printf("Reserved size: %u bytes\n", gsf->reserved_size); printf("Compressed program size: %u bytes\n", gsf->compressed_size); printf("Compressed program CRC-32: 0x%08x\n", gsf->crc32); printf("Reserved area: %zu bytes (binary)\n", gsf->reserved_size); printf("Compressed program: %zu bytes (zlib)\n", gsf->compressed_size); if (gsf->tag_signature[0]) { printf("Tag signature: %s\n", gsf->tag_signature); printf("Tag data:\n%s\n", gsf->tag_data); } else { printf("No tags found.\n"); } } void gsf_free(GSFReader* gsf) { free(gsf->data); free(gsf->reserved_data); free(gsf->compressed_program); free(gsf->tag_data); } // Example usage // GSFReader gsf = { .filename = "example.gsf" }; // gsf_read(&gsf); // gsf_write(&gsf, "output.gsf"); // gsf_free(&gsf); // ===== end task-272 .GSF ===== // ===== task-273 .GTF [C] ===== #include #include #include typedef struct { char seqname[256]; char source[256]; char feature[256]; int start; int end; double score; char strand[2]; char frame[2]; char attributes[1024]; int is_valid; } Feature; typedef struct { char filename[256]; Feature* features; size_t count; size_t capacity; } GTFParser; void init_parser(GTFParser* parser, const char* filename) { strcpy(parser->filename, filename); parser->features = malloc(1000 * sizeof(Feature)); // Initial capacity parser->count = 0; parser->capacity = 1000; } void free_parser(GTFParser* parser) { free(parser->features); } int parse_int_or_null(const char* s, int* val) { if (strcmp(s, ".") == 0) return 0; *val = atoi(s); return 1; } double parse_double_or_null(const char* s, double* val) { if (strcmp(s, ".") == 0) return 0; *val = atof(s); return 1; } void read_gtf(GTFParser* parser) { FILE* file = fopen(parser->filename, "r"); if (!file) { perror("Error opening file"); return; } char line[4096]; int line_num = 0; while (fgets(line, sizeof(line), file)) { line_num++; if (line[0] == '#' || strncmp(line, "track ", 6) == 0 || strlen(line) < 2) continue; char* token = strtok(line, "\t"); if (!token || strstr(token, "\n")) continue; char* fields[9]; int field_count = 0; while (token && field_count < 9) { fields[field_count++] = token; token = strtok(NULL, "\t"); } if (field_count != 9) { fprintf(stderr, "Warning: Line %d has %d fields, skipping.\n", line_num, field_count); continue; } if (parser->count >= parser->capacity) { parser->capacity *= 2; parser->features = realloc(parser->features, parser->capacity * sizeof(Feature)); } Feature* f = &parser->features[parser->count++]; strncpy(f->seqname, fields[0], sizeof(f->seqname) - 1); strncpy(f->source, fields[1], sizeof(f->source) - 1); strncpy(f->feature, fields[2], sizeof(f->feature) - 1); f->start = 0; parse_int_or_null(fields[3], &f->start); f->end = 0; parse_int_or_null(fields[4], &f->end); f->score = 0.0; parse_double_or_null(fields[5], &f->score); strncpy(f->strand, fields[6], sizeof(f->strand) - 1); strncpy(f->frame, fields[7], sizeof(f->frame) - 1); strncpy(f->attributes, fields[8], sizeof(f->attributes) - 1); f->is_valid = 1; } fclose(file); printf("Parsed %zu features from %s.\n", parser->count, parser->filename); } void print_properties(GTFParser* parser) { for (size_t i = 0; i < parser->count; i++) { Feature* f = &parser->features[i]; printf("Line %zu:\n", i + 1); printf(" seqname: %s\n", f->seqname); printf(" source: %s\n", f->source); printf(" feature: %s\n", f->feature); printf(" start: %d\n", f->start); printf(" end: %d\n", f->end); printf(" score: %.2f\n", f->score); printf(" strand: %s\n", f->strand); printf(" frame: %s\n", f->frame); printf(" attributes: %s\n\n", f->attributes); } } void write_gtf(GTFParser* parser, const char* output_filename, Feature (*modify_callback)(Feature)) { FILE* file = fopen(output_filename, "w"); if (!file) { perror("Error opening output file"); return; } for (size_t i = 0; i < parser->count; i++) { Feature f = parser->features[i]; if (modify_callback) f = modify_callback(f); fprintf(file, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", f.seqname, f.source, f.feature, strcmp(fields[3], ".") == 0 ? "." : f.start ? "0" : itoa(f.start), wait, fix: use snprintf or something, but for simplicity assume no mod. Actually, since C is basic, print as is. fprintf(file, "%s\t%s\t%s\t%d\t%d\t%.2f\t%s\t%s\t%s\n", f.seqname, f.source, f.feature, f.start, f.end, f.score, f.strand, f.frame, f.attributes); } fclose(file); printf("Wrote %zu features to %s.\n", parser->count, output_filename); } int main(int argc, char* argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } GTFParser parser; init_parser(&parser, argv[1]); read_gtf(&parser); print_properties(&parser); // write_gtf(&parser, "output.gtf", NULL); free_parser(&parser); return 0; } // ===== end task-273 .GTF ===== // ===== task-274 .GV [C] ===== #include #include #include #include typedef struct { char *type; char *value; } Token; typedef struct { int strict; char *type; char *id; char **nodes; int node_count; // Simplified: edges and attrs as strings for demo char *edges; // Concatenated char *attrs; char *subgraphs; } Properties; typedef struct { Token *tokens; int count; int current; char *text; } Parser; Token *tokenize(char *text, int *token_count) { Token *tokens = malloc(1024 * sizeof(Token)); // Arbitrary max int t_idx = 0, i = 0; while (i < strlen(text)) { char ch = text[i]; if (isspace(ch)) { i++; continue; } if (isalpha(ch) || ch == '_') { char id[256] = {0}; int j = 0; while (i < strlen(text) && (isalnum(text[i]) || text[i] == '_')) { id[j++] = tolower(text[i++]); } tokens[t_idx].type = strdup("ID"); tokens[t_idx].value = strdup(id); t_idx++; continue; } // Skip numerals, strings, HTML, comments for brevity (add similar logic) if (isdigit(ch) || ch == '-') { while (i < strlen(text) && (isdigit(text[i]) || text[i] == '.')) i++; continue; } if (ch == '"') { i++; while (i < strlen(text) && text[i] != '"') { if (text[i] == '\\') i += 2; else i++; } i++; continue; } if (ch == '/' && i+1 < strlen(text) && (text[i+1] == '/' || text[i+1] == '*')) { if (text[i+1] == '/') { i += 2; while (i < strlen(text) && text[i] != '\n') i++; } else { i += 2; while (i < strlen(text) && !(text[i-1] == '*' && text[i] == '/')) i++; i++; } continue; } if (ch == '#') { while (i < strlen(text) && text[i] != '\n') i++; continue; } if (strchr("{}[]();,=+-<>", ch)) { char op[3] = {ch, 0, 0}; if (ch == '-' && i+1 < strlen(text) && (text[i+1] == '>' || text[i+1] == '-')) { op[1] = text[i+1]; i++; } tokens[t_idx].type = strdup(op); tokens[t_idx].value = strdup(op); t_idx++; i++; continue; } i++; } *token_count = t_idx; return tokens; } Token next(Parser *p) { if (p->current < p->count) return p->tokens[p->current++]; Token empty = {NULL, NULL}; return empty; } Token peek(Parser *p) { if (p->current < p->count) return p->tokens[p->current]; Token empty = {NULL, NULL}; return empty; } char *eat(Parser *p, char *typ) { Token t = peek(p); if (t.type && strcmp(t.type, typ) == 0) { p->current++; return t.value; } return NULL; } char *parse_id(Parser *p) { Token t = next(p); if (t.type && (strcmp(t.type, "ID") == 0 || strcmp(t.type, "NUM") == 0 || strcmp(t.type, "STRING") == 0)) { return t.value; } return NULL; } Properties parse(Parser *p) { Properties props = {0, NULL, NULL, NULL, 0, NULL, NULL, NULL}; Token t = peek(p); if (t.type && strcmp(t.type, "ID") == 0 && strcmp(t.value, "strict") == 0) { props.strict = 1; next(p); } t = next(p); if (t.type && strcmp(t.type, "ID") == 0 && (strcmp(t.value, "graph") == 0 || strcmp(t.value, "digraph") == 0)) { props.type = strdup(t.value); } if (peek(p).type && strcmp(peek(p).type, "{") != 0) { props.id = parse_id(p); } eat(p, "{"); // Simplified parsing: collect nodes, etc. (add stmt logic similar to others) // For demo, assume basic extraction while (peek(p).type) { // Parse stmts, add to props.nodes, etc. // Omitted full impl for brevity; extend as needed } eat(p, "}"); return props; } void print_properties(Properties *props) { printf("GV Properties:\n"); printf("Strict: %d\n", props->strict); printf("Type: %s\n", props->type ? props->type : "null"); printf("ID: %s\n", props->id ? props->id : "null"); printf("Nodes: %d\n", props->node_count); // Print others } void write_properties(Properties *props, char *output_path) { FILE *f = fopen(output_path, "w"); if (!f) return; if (props->strict) fprintf(f, "strict "); fprintf(f, "%s ", props->type); if (props->id) fprintf(f, "%s ", props->id); fprintf(f, "{\n"); // Reconstruct fprintf(f, "}\n"); fclose(f); } int main(int argc, char **argv) { if (argc < 2) return 1; FILE *file = fopen(argv[1], "r"); if (!file) return 1; fseek(file, 0, SEEK_END); long size = ftell(file); fseek(file, 0, SEEK_SET); char *text = malloc(size + 1); fread(text, 1, size, file); text[size] = 0; fclose(file); int token_count; Token *tokens = tokenize(text, &token_count); Parser p = {tokens, token_count, 0, text}; Properties props = parse(&p); print_properties(&props); // write_properties(&props, "output.gv"); // Cleanup for (int i = 0; i < token_count; i++) { free(p.tokens[i].type); free(p.tokens[i].value); } free(tokens); free(text); free(props.type); free(props.id); return 0; } // ===== end task-274 .GV ===== // ===== task-275 .GW [C] ===== #include #include #include typedef struct { char title[256]; double shallst; double deepst; double gw_delay; double alpha_bf; double gwqmn; double gw_revap; double revapmn; double rchrg_dp; double gwht; double gw_spyld; double shallst_n; double gwsolp; double hlife_ngw; double lat_orgn; double lat_orgp; double alpha_bf_d; } GWProperties; typedef struct { char filename[256]; GWProperties props; } GWFile; void read_gw(GWFile *gw) { FILE *fp = fopen(gw->filename, "r"); if (!fp) { printf("Error opening file %s\n", gw->filename); return; } char line[256]; int line_num = 0; while (fgets(line, sizeof(line), fp)) { char *trimmed = line; while (*trimmed == ' ' || *trimmed == '\t' || *trimmed == '\n') trimmed++; char *end = trimmed + strlen(trimmed) - 1; while (end > trimmed && (*end == ' ' || *end == '\t' || *end == '\n')) *end-- = '\0'; if (strlen(trimmed) == 0) continue; line_num++; switch (line_num) { case 1: strncpy(gw->props.title, trimmed, 255); break; case 2: sscanf(trimmed, "%lf", &gw->props.shallst); break; case 3: sscanf(trimmed, "%lf", &gw->props.deepst); break; case 4: sscanf(trimmed, "%lf", &gw->props.gw_delay); break; case 5: sscanf(trimmed, "%lf", &gw->props.alpha_bf); break; case 6: sscanf(trimmed, "%lf", &gw->props.gwqmn); break; case 7: sscanf(trimmed, "%lf", &gw->props.gw_revap); break; case 8: sscanf(trimmed, "%lf", &gw->props.revapmn); break; case 9: sscanf(trimmed, "%lf", &gw->props.rchrg_dp); break; case 10: sscanf(trimmed, "%lf", &gw->props.gwht); break; case 11: sscanf(trimmed, "%lf", &gw->props.gw_spyld); break; case 12: sscanf(trimmed, "%lf", &gw->props.shallst_n); break; case 13: sscanf(trimmed, "%lf", &gw->props.gwsolp); break; case 14: sscanf(trimmed, "%lf", &gw->props.hlife_ngw); break; case 15: sscanf(trimmed, "%lf", &gw->props.lat_orgn); break; case 16: sscanf(trimmed, "%lf", &gw->props.lat_orgp); break; case 17: sscanf(trimmed, "%lf", &gw->props.alpha_bf_d); break; } } fclose(fp); // Defaults if (gw->props.deepst == 0.0) gw->props.deepst = 1000.0; } void write_gw(GWFile *gw, char *output_filename) { FILE *fp = fopen(output_filename, "w"); if (!fp) { printf("Error opening output file %s\n", output_filename); return; } fprintf(fp, "%s\n", gw->props.title); fprintf(fp, "%.1f\n", gw->props.shallst); fprintf(fp, "%.1f\n", gw->props.deepst); fprintf(fp, "%.1f\n", gw->props.gw_delay); fprintf(fp, "%.3f\n", gw->props.alpha_bf); fprintf(fp, "%.1f\n", gw->props.gwqmn); fprintf(fp, "%.2f\n", gw->props.gw_revap); fprintf(fp, "%.1f\n", gw->props.revapmn); fprintf(fp, "%.2f\n", gw->props.rchrg_dp); fprintf(fp, "%.1f\n", gw->props.gwht); fprintf(fp, "%.3f\n", gw->props.gw_spyld); fprintf(fp, "%.2f\n", gw->props.shallst_n); fprintf(fp, "%.2f\n", gw->props.gwsolp); fprintf(fp, "%.1f\n", gw->props.hlife_ngw); fprintf(fp, "%.2f\n", gw->props.lat_orgn); fprintf(fp, "%.2f\n", gw->props.lat_orgp); fprintf(fp, "%.3f\n", gw->props.alpha_bf_d); fclose(fp); } void print_properties(GWFile *gw) { printf("TITLE: %s\n", gw->props.title); printf("SHALLST: %.1f\n", gw->props.shallst); printf("DEEPST: %.1f\n", gw->props.deepst); printf("GW_DELAY: %.1f\n", gw->props.gw_delay); printf("ALPHA_BF: %.3f\n", gw->props.alpha_bf); printf("GWQMN: %.1f\n", gw->props.gwqmn); printf("GW_REVAP: %.2f\n", gw->props.gw_revap); printf("REVAPMN: %.1f\n", gw->props.revapmn); printf("RCHRG_DP: %.2f\n", gw->props.rchrg_dp); printf("GWHT: %.1f\n", gw->props.gwht); printf("GW_SPYLD: %.3f\n", gw->props.gw_spyld); printf("SHALLST_N: %.2f\n", gw->props.shallst_n); printf("GWSOLP: %.2f\n", gw->props.gwsolp); printf("HLIFE_NGW: %.1f\n", gw->props.hlife_ngw); printf("LAT_ORGN: %.2f\n", gw->props.lat_orgn); printf("LAT_ORGP: %.2f\n", gw->props.lat_orgp); printf("ALPHA_BF_D: %.3f\n", gw->props.alpha_bf_d); } // Example usage: // int main() { // GWFile gw; // strcpy(gw.filename, "example.gw"); // read_gw(&gw); // print_properties(&gw); // write_gw(&gw, "output.gw"); // return 0; // } // ===== end task-275 .GW ===== // ===== task-276 .GXL [C++] ===== #include #include using namespace tinyxml2; class GXLHandler { private: XMLDocument doc; public: GXLHandler(const char* filepath) { read(filepath); } void read(const char* filepath) { if (doc.LoadFile(filepath) != XML_SUCCESS) { std::cerr << "Failed to load file." << std::endl; } if (std::string(doc.RootElement()->Name()) != "gxl") { std::cerr << "Invalid GXL file." << std::endl; } } void printProperties() { if (doc.Error()) { std::cout << "No file loaded." << std::endl; return; } std::cout << "GXL Properties:" << std::endl; std::cout << "- Root element: gxl" << std::endl; XMLElement* graph = doc.RootElement()->FirstChildElement("graph"); if (graph) { std::cout << "- Graph ID: " << graph->Attribute("id") << std::endl; std::cout << "- Edge mode: " << graph->Attribute("edgemode") << std::endl; std::cout << "- Edge IDs: " << graph->Attribute("edgeids") << std::endl; std::cout << "- Hypergraph: " << graph->Attribute("hypergraph") << std::endl; } int nodeCount = 0; for (XMLElement* node = doc.RootElement()->FirstChildElement("node"); node; node = node->NextSiblingElement("node")) { nodeCount++; std::cout << " - Node ID: " << node->Attribute("id") << std::endl; } std::cout << "- Number of nodes: " << nodeCount << std::endl; int edgeCount = 0; for (XMLElement* edge = doc.RootElement()->FirstChildElement("edge"); edge; edge = edge->NextSiblingElement("edge")) { edgeCount++; std::cout << " - Edge from: " << edge->Attribute("from") << " to: " << edge->Attribute("to") << std::endl; } std::cout << "- Number of edges: " << edgeCount << std::endl; std::cout << "- Attributes:" << std::endl; for (XMLElement* attr = doc.RootElement()->FirstChildElement("attr"); attr; attr = attr->NextSiblingElement("attr")) { std::cout << " - Name: " << attr->Attribute("name") << ", Value: " << attr->GetText() << std::endl; } } void write(const char* filepath) { if (doc.SaveFile(filepath) != XML_SUCCESS) { std::cerr << "Failed to save file." << std::endl; } } }; // Example usage: // int main() { // GXLHandler handler("example.gxl"); // handler.printProperties(); // handler.write("output.gxl"); // return 0; // } // ===== end task-276 .GXL ===== // ===== task-277 .GZ [C] ===== #include #include #include typedef struct { uint8_t data[1]; // Flexible array for full file } GZData; void parse_gz(const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) { printf("Cannot open file\n"); return; } fseek(f, 0, SEEK_END); long len = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(len); fread(data, 1, len, f); fclose(f); if (len < 10 || data[0] != 0x1F || data[1] != 0x8B) { printf("Invalid GZIP file\n"); free(data); return; } int pos = 2; uint8_t cm = data[pos++]; uint8_t flg = data[pos++]; uint32_t mtime = (data[pos] << 24) | (data[pos+1] << 16) | (data[pos+2] << 8) | data[pos+3]; pos += 4; uint8_t xfl = data[pos++]; uint8_t os = data[pos++]; printf("Magic: 0x1F 0x8B\n"); printf("CM: %u (deflate if 8)\n", cm); printf("FLG: 0x%02x (FTEXT:%u, FHCRC:%u, FEXTRA:%u, FNAME:%u, FCOMMENT:%u)\n", flg, flg&1, (flg>>1)&1, (flg>>2)&1, (flg>>3)&1, (flg>>4)&1); printf("MTIME: %u (Unix ts)\n", mtime); printf("XFL: %u\n", xfl); printf("OS: %u\n", os); if (flg & 2) { // FHCRC uint16_t hcrc = (data[pos] << 8) | data[pos+1]; pos += 2; printf("Header CRC16: 0x%04x\n", hcrc); } if (flg & 4) { // FEXTRA uint16_t xlen = (data[pos] << 8) | data[pos+1]; pos += 2; printf("XLEN: %u\n", xlen); printf("Extra Fields: "); for (int i = 0; i < xlen; i++) { printf("%02x ", data[pos + i]); } printf("\n"); pos += xlen; } if (flg & 8) { // FNAME printf("Filename: "); while (pos < len && data[pos] != 0) { putchar(data[pos++]); } putchar('\n'); pos++; } if (flg & 16) { // FCOMMENT printf("Comment: "); while (pos < len && data[pos] != 0) { putchar(data[pos++]); } putchar('\n'); pos++; } // Trailer pos = len - 8; uint32_t crc32 = (data[pos] << 24) | (data[pos+1] << 16) | (data[pos+2] << 8) | data[pos+3]; uint32_t isize = (data[pos+4] << 24) | (data[pos+5] << 16) | (data[pos+6] << 8) | data[pos+7]; printf("CRC32: 0x%08x\n", crc32); printf("ISIZE: %u\n", isize); free(data); } // Usage: parse_gz("example.gz"); int main(int argc, char** argv) { if (argc > 1) parse_gz(argv[1]); return 0; } // ===== end task-277 .GZ ===== // ===== task-278 .H [C] ===== #include #include #include #define MAX_LINE 512 #define MAX_PROPS 100 typedef struct { int line; char directive[256]; } Prop; typedef struct { Prop includes[MAX_PROPS]; int num_includes; Prop defines[MAX_PROPS]; int num_defines; Prop prototypes[MAX_PROPS]; int num_prototypes; int has_guard; char guard_name[256]; int total_lines; } HProperties; typedef struct { char filepath[256]; char *content; HProperties props; } HFileHandler; void init_handler(HFileHandler *handler, const char *filepath) { strcpy(handler->filepath, filepath); handler->content = NULL; handler->props.num_includes = 0; handler->props.num_defines = 0; handler->props.num_prototypes = 0; handler->props.has_guard = 0; handler->props.total_lines = 0; } int read_and_decode(HFileHandler *handler) { FILE *fp = fopen(handler->filepath, "r"); if (!fp || !strstr(handler->filepath, ".h")) { printf("Invalid .H file\n"); return 0; } fseek(fp, 0, SEEK_END); long size = ftell(fp); rewind(fp); handler->content = malloc(size + 1); fread(handler->content, 1, size, fp); handler->content[size] = '\0'; fclose(fp); parse_content(handler); print_properties(&handler->props); return 1; } void parse_content(HFileHandler *handler) { char *line = strtok(handler->content, "\n"); int idx = 0; int in_guard = 0; while (line != NULL) { char trimmed[512]; sscanf(line, "%511[^\n]", trimmed); char *p = trimmed; while (*p == ' ' || *p == '\t') p++; // Trim left char *end = p + strlen(p) - 1; while (end > p && (*end == ' ' || *end == '\t' || *end == '\r')) *end-- = '\0'; if (strncmp(p, "#include", 8) == 0) { if (handler->props.num_includes < MAX_PROPS) { handler->props.includes[handler->props.num_includes].line = idx + 1; strcpy(handler->props.includes[handler->props.num_includes].directive, p); handler->props.num_includes++; } } else if (strncmp(p, "#define", 7) == 0) { if (handler->props.num_defines < MAX_PROPS) { handler->props.defines[handler->props.num_defines].line = idx + 1; strcpy(handler->props.defines[handler->props.num_defines].directive, p); handler->props.num_defines++; } } else if (strncmp(p, "#ifndef", 7) == 0 && !in_guard) { handler->props.has_guard = 1; sscanf(p, "#ifndef %255s", handler->props.guard_name); in_guard = 1; } else if (strncmp(p, "#endif", 6) == 0 && in_guard) { in_guard = 0; } else if (strstr(p, "(") && strstr(p, ")") && strstr(p, ";") && !strstr(p, "=")) { // Basic proto check if (handler->props.num_prototypes < MAX_PROPS) { handler->props.prototypes[handler->props.num_prototypes].line = idx + 1; strcpy(handler->props.prototypes[handler->props.num_prototypes].directive, p); handler->props.num_prototypes++; } } line = strtok(NULL, "\n"); idx++; } handler->props.total_lines = idx; } void print_properties(HProperties *props) { printf("=== .H File Properties ===\n"); printf("Total lines: %d\n", props->total_lines); printf("\nIncludes:\n"); for (int i = 0; i < props->num_includes; i++) { printf(" Line %d: %s\n", props->includes[i].line, props->includes[i].directive); } printf("\nDefines:\n"); for (int i = 0; i < props->num_defines; i++) { printf(" Line %d: %s\n", props->defines[i].line, props->defines[i].directive); } printf("\nPrototypes:\n"); for (int i = 0; i < props->num_prototypes; i++) { printf(" Line %d: %s\n", props->prototypes[i].line, props->prototypes[i].directive); } printf("\nGuards: %s (Name: %s)\n", props->has_guard ? "Yes" : "No", props->guard_name); } void write_file(const char *output_path, HProperties *props) { FILE *fp = fopen(output_path, "w"); if (!fp) return; if (props->has_guard) { fprintf(fp, "#ifndef %s\n#define %s\n", props->guard_name, props->guard_name); } for (int i = 0; i < props->num_includes; i++) { fprintf(fp, "%s\n", props->includes[i].directive); } for (int i = 0; i < props->num_defines; i++) { fprintf(fp, "%s\n", props->defines[i].directive); } for (int i = 0; i < props->num_prototypes; i++) { fprintf(fp, "%s\n", props->prototypes[i].directive); } if (props->has_guard) { fprintf(fp, "#endif\n"); } fclose(fp); printf("Wrote .H file to %s\n", output_path); } /* Usage: int main() { HFileHandler handler; init_handler(&handler, "sample.h"); if (read_and_decode(&handler)) { write_file("output.h", &handler.props); } free(handler.content); return 0; } */ // ===== end task-278 .H ===== // ===== task-279 .HA [C] ===== #include #include #include #include #include #include #include typedef struct { uint8_t version; uint8_t comp_type; uint32_t comp_len; uint32_t uncomp_len; uint32_t crc32; uint32_t timestamp; char *path; char *filename; uint8_t msi_len; uint8_t msi_type; char *msi_data; } HAFile; typedef struct { char magic[3]; // Null-terminated uint16_t num_files; HAFile *files; } HAArchive; const char *comp_types[] = {"CPY", "ASC", "HSC", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "DIR", "Special"}; uint32_t crc32(const uint8_t *data, size_t len) { uint32_t crc = 0xFFFFFFFF; for (size_t i = 0; i < len; i++) { crc ^= data[i]; for (int j = 0; j < 8; j++) { crc = (crc >> 1) ^ ((crc & 1) ? 0xEDB88320 : 0); } } return crc ^ 0xFFFFFFFF; } void ha_read(const char *filename, HAArchive *arch) { FILE *f = fopen(filename, "rb"); if (!f) { perror("fopen"); return; } fread(arch->magic, 1, 2, f); arch->magic[2] = '\0'; if (strncmp(arch->magic, "HA", 2) != 0) { fprintf(stderr, "Invalid .HA magic\n"); fclose(f); return; } fread(&arch->num_files, 2, 1, f); // LE assumed by host arch->files = malloc(arch->num_files * sizeof(HAFile)); printf("Magic: %s\n", arch->magic); printf("Number of Files: %u\n\n", arch->num_files); for (uint16_t i = 0; i < arch->num_files; i++) { HAFile *file = &arch->files[i]; uint8_t ver_comp; fread(&ver_comp, 1, 1, f); file->version = (ver_comp >> 4) & 0xF; file->comp_type = ver_comp & 0xF; fread(&file->comp_len, 4, 1, f); fread(&file->uncomp_len, 4, 1, f); fread(&file->crc32, 4, 1, f); fread(&file->timestamp, 4, 1, f); printf("File %u:\n", i + 1); printf(" Version: %u\n", file->version); printf(" Compression Type: %s (%u)\n", comp_types[file->comp_type] ? comp_types[file->comp_type] : "Unknown", file->comp_type); printf(" Compressed Length: %u\n", file->comp_len); printf(" Uncompressed Length: %u\n", file->uncomp_len); printf(" CRC-32: 0x%08X\n", file->crc32); time_t ts = file->timestamp; printf(" Timestamp: %s (Unix: %u)\n", ctime(&ts), file->timestamp); // Null-terminated char buf[1024]; size_t path_len = fread(buf, 1, sizeof(buf) - 1, f); while (buf[path_len - 1] != '\0' && path_len < sizeof(buf) - 1) { path_len = fread(buf + path_len, 1, sizeof(buf) - path_len - 1, f); } buf[path_len] = '\0'; file->path = strdup(buf); fseek(f, -(long)(path_len - strlen(buf) - 1), SEEK_CUR); // Skip null if needed, but fread stops printf(" Pathname: %s\n", file->path ? file->path : "(empty)"); size_t name_len = fread(buf, 1, sizeof(buf) - 1, f); while (buf[name_len - 1] != '\0' && name_len < sizeof(buf) - 1) { name_len = fread(buf + name_len, 1, sizeof(buf) - name_len - 1, f); } buf[name_len] = '\0'; file->filename = strdup(buf); printf(" Filename: %s\n", file->filename ? file->filename : "(empty)"); fread(&file->msi_len, 1, 1, f); printf(" MSI Length: %u\n", file->msi_len); if (file->msi_len > 0) { fread(&file->msi_type, 1, 1, f); file->msi_data = malloc(file->msi_len - 1); fread(file->msi_data, 1, file->msi_len - 1, f); file->msi_data[file->msi_len - 1] = '\0'; printf(" MSI Type: %u\n", file->msi_type); printf(" MSI Data: %s\n", file->msi_data ? file->msi_data : "(none)"); } printf("\n"); } fclose(f); } void ha_write(const char *output_filename, char *files[], int num_files) { FILE *f = fopen(output_filename, "wb"); if (!f) { perror("fopen write"); return; } fwrite("HA", 1, 2, f); fwrite(&num_files, 2, 1, f); // LE for (int i = 0; i < num_files; i++) { FILE *src = fopen(files[i], "rb"); if (!src) continue; fseek(src, 0, SEEK_END); long len = ftell(src); fseek(src, 0, SEEK_SET); uint8_t *content = malloc(len); fread(content, 1, len, src); fclose(src); uint32_t uncomp_len = len; uint32_t comp_len = len; // CPY uint32_t crc_val = crc32(content, len); struct stat st; stat(files[i], &st); uint32_t timestamp = st.st_mtime; char *dir = dirname(strdup(files[i])); char *base = basename(files[i]); // Ver 0, CPY uint8_t ver_comp = 0x00; fwrite(&ver_comp, 1, 1, f); fwrite(&comp_len, 4, 1, f); fwrite(&uncomp_len, 4, 1, f); fwrite(&crc_val, 4, 1, f); fwrite(×tamp, 4, 1, f); fwrite(dir, 1, strlen(dir) + 1, f); fwrite(base, 1, strlen(base) + 1, f); uint8_t msi_len = 0; fwrite(&msi_len, 1, 1, f); fwrite(content, 1, len, f); free(content); free(dir); } fclose(f); printf("Wrote simple CPY .HA archive to %s\n", output_filename); } int main(int argc, char *argv[]) { if (argc < 2) return 1; HAArchive arch = {0}; ha_read(argv[1], &arch); // For write: char *files[] = {"file1.txt", "file2.txt"}; ha_write("new.ha", files, 2); // Free resources... for (uint16_t i = 0; i < arch.num_files; i++) { free(arch.files[i].path); free(arch.files[i].filename); free(arch.files[i].msi_data); } free(arch.files); return 0; } // ===== end task-279 .HA ===== // ===== task-280 .HACK [C] ===== #include #include #include #define MAX_INSTR 32768 #define INSTR_LEN 16 typedef struct { char binary[17]; // Null-terminated int decimal; int line; char type[2]; // 'A' or 'C' union { int value; // For A struct { char a; char comp[10]; // Mnemonic char dest[4]; char jump[4]; } c; }; } Instruction; typedef struct { char filename[256]; Instruction instructions[MAX_INSTR]; int count; } HackFile; // Static tables (simplified strings) static const char* comp_table[] = { // Keys are hardcoded checks for brevity; in full impl, use hash or array // For demo, we'll implement decoding inline }; static const char* dest_table[8] = {"null", "M", "D", "MD", "A", "AM", "AD", "AMD"}; static const char* jump_table[8] = {"null", "JGT", "JEQ", "JGE", "JLT", "JNE", "JLE", "JMP"}; // Comp decode function (hardcoded mappings for common cases) void decode_comp(char a, const char* comp_bin, char* out) { char key[8]; sprintf(key, "%c%s", a, comp_bin); if (strcmp(key, "0101010") == 0) strcpy(out, "0"); else if (strcmp(key, "0111111") == 0) strcpy(out, "1"); else if (strcmp(key, "0111010") == 0) strcpy(out, "-1"); else if (strcmp(key, "0001100") == 0) strcpy(out, "D"); else if (strcmp(key, "0110000") == 0) strcpy(out, "A"); else if (strcmp(key, "0001101") == 0) strcpy(out, "!D"); else if (strcmp(key, "0110001") == 0) strcpy(out, "!A"); else if (strcmp(key, "0001111") == 0) strcpy(out, "-D"); else if (strcmp(key, "0110011") == 0) strcpy(out, "-A"); else if (strcmp(key, "0011111") == 0) strcpy(out, "D+1"); else if (strcmp(key, "0110111") == 0) strcpy(out, "A+1"); else if (strcmp(key, "0001110") == 0) strcpy(out, "D-1"); else if (strcmp(key, "0110010") == 0) strcpy(out, "A-1"); else if (strcmp(key, "0000010") == 0) strcpy(out, "D+A"); else if (strcmp(key, "0010011") == 0) strcpy(out, "D-A"); else if (strcmp(key, "0000111") == 0) strcpy(out, "A-D"); else if (strcmp(key, "0000000") == 0) strcpy(out, "D&A"); else if (strcmp(key, "0010101") == 0) strcpy(out, "D|A"); else if (strcmp(key, "1110000") == 0) strcpy(out, "M"); else if (strcmp(key, "1110001") == 0) strcpy(out, "!M"); else if (strcmp(key, "1110011") == 0) strcpy(out, "-M"); else if (strcmp(key, "1110111") == 0) strcpy(out, "M+1"); else if (strcmp(key, "1110010") == 0) strcpy(out, "M-1"); else if (strcmp(key, "1000010") == 0) strcpy(out, "D+M"); else if (strcmp(key, "1010011") == 0) strcpy(out, "D-M"); else if (strcmp(key, "1000111") == 0) strcpy(out, "M-D"); else if (strcmp(key, "1000000") == 0) strcpy(out, "D&M"); else if (strcmp(key, "1010101") == 0) strcpy(out, "D|M"); else strcpy(out, "unknown"); } void read_hack(HackFile* hf) { FILE* f = fopen(hf->filename, "r"); if (!f) { printf("Error: File %s not found.\n", hf->filename); return; } hf->count = 0; char line[INSTR_LEN + 2]; int line_num = 1; while (fgets(line, sizeof(line), f) && hf->count < MAX_INSTR) { char* trimmed = strtok(line, "\n\r "); if (!trimmed || strlen(trimmed) == 0) { line_num++; continue; } if (strlen(trimmed) != INSTR_LEN || strpbrk(trimmed, "01") != trimmed) { printf("Warning: Invalid line %d: %s\n", line_num, trimmed); line_num++; continue; } strcpy(hf->instructions[hf->count].binary, trimmed); hf->instructions[hf->count].decimal = strtol(trimmed, NULL, 2); hf->instructions[hf->count].line = line_num; if (trimmed[0] == '0') { strcpy(hf->instructions[hf->count].type, "A"); hf->instructions[hf->count].value = strtol(trimmed + 1, NULL, 2); } else if (strncmp(trimmed, "111", 3) == 0) { strcpy(hf->instructions[hf->count].type, "C"); char a = trimmed[3]; char comp_bin[7]; strncpy(comp_bin, trimmed + 4, 6); comp_bin[6] = '\0'; char dest_bin[4], jump_bin[4]; strncpy(dest_bin, trimmed + 10, 3); dest_bin[3] = '\0'; strncpy(jump_bin, trimmed + 13, 3); jump_bin[3] = '\0'; hf->instructions[hf->count].c.a = a; decode_comp(a, comp_bin, hf->instructions[hf->count].c.comp); int d_idx = strtol(dest_bin, NULL, 2); strcpy(hf->instructions[hf->count].c.dest, dest_table[d_idx]); int j_idx = strtol(jump_bin, NULL, 2); strcpy(hf->instructions[hf->count].c.jump, jump_table[j_idx]); } else { printf("Warning: Invalid opcode line %d: %s\n", line_num, trimmed); line_num++; continue; } hf->count++; line_num++; } fclose(f); } void print_properties(HackFile* hf) { if (hf->count == 0) { printf("No valid instructions found.\n"); return; } printf("File: %s\n", hf->filename); printf("Number of instructions: %d\n\n", hf->count); for (int i = 0; i < hf->count; i++) { Instruction* instr = &hf->instructions[i]; printf("Instruction %d (line %d):\n", i + 1, instr->line); printf(" Binary: %s\n", instr->binary); printf(" Decimal: %d\n", instr->decimal); printf(" Type: %s\n", instr->type); if (strcmp(instr->type, "A") == 0) { printf(" Value: %d\n", instr->value); } else { printf(" a: %c, comp: %s, dest: %s, jump: %s\n", instr->c.a, instr->c.comp, instr->c.dest, instr->c.jump); } printf("\n"); } } void write_hack(HackFile* hf, const char* output_filename) { FILE* f = fopen(output_filename, "w"); if (!f) { printf("Error writing file %s.\n", output_filename); return; } for (int i = 0; i < hf->count; i++) { fprintf(f, "%s\n", hf->instructions[i].binary); } fclose(f); printf("Wrote %d instructions to %s\n", hf->count, output_filename); } int main(int argc, char* argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } HackFile hf; strcpy(hf.filename, argv[1]); read_hack(&hf); print_properties(&hf); write_hack(&hf, "output.hack"); return 0; } // ===== end task-280 .HACK ===== // ===== task-281 .HAR [C] ===== #include #include #include #include "cJSON.h" typedef struct { cJSON *data; } HARHandler; HARHandler *har_handler_new(const char *filepath) { FILE *f = fopen(filepath, "r"); if (!f) return NULL; fseek(f, 0, SEEK_END); long len = ftell(f); fseek(f, 0, SEEK_SET); char *buf = malloc(len + 1); fread(buf, 1, len, f); buf[len] = '\0'; fclose(f); HARHandler *handler = malloc(sizeof(HARHandler)); handler->data = cJSON_Parse(buf); free(buf); if (handler->data) { print_properties(handler->data, "log"); } return handler; } void har_handler_free(HARHandler *handler) { if (handler) { cJSON_Delete(handler->data); free(handler); } } void write_har(HARHandler *handler, const char *filepath) { if (!handler || !handler->data) return; char *json_str = cJSON_Print(handler->data); FILE *f = fopen(filepath, "w"); if (f) { fputs(json_str, f); fclose(f); } free(json_str); } void print_properties(cJSON *node, const char *path) { if (!node) return; if (cJSON_IsObject(node)) { cJSON *child; cJSON_ArrayForEach(child, node) { char new_path[1024]; snprintf(new_path, sizeof(new_path), "%s%s%s", path, strlen(path) ? "." : "", child->string); printf("%s: %s\n", new_path, cJSON_Print(child)); print_properties(child, new_path); } } else if (cJSON_IsArray(node)) { int i = 0; cJSON *child; cJSON_ArrayForEach(child, node) { char new_path[1024]; snprintf(new_path, sizeof(new_path), "%s[%d]", path, i++); printf("%s: %s (array item)\n", new_path, cJSON_GetStringValue(child) ? cJSON_GetStringValue(child) : "object"); print_properties(child, new_path); } } else { printf("%s: %s\n", path, cJSON_PrintUnformatted(node)); } } int main(int argc, char **argv) { if (argc > 1) { HARHandler *handler = har_handler_new(argv[1]); if (handler) { // write_har(handler, "output.har"); har_handler_free(handler); } } return 0; } // ===== end task-281 .HAR ===== // ===== task-283 .HDF5 [C++] ===== #include #include #include #include #include #include #include class HDF5Parser { private: std::string filepath; std::map properties; // Using uint64_t for simplicity; adjust for strings/large ints public: HDF5Parser(const std::string& fp) : filepath(fp) {} void readAndDecode() { std::ifstream file(filepath, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file"); } std::vector data(1024); file.read(reinterpret_cast(data.data()), 1024); uint8_t sig[8]; std::memcpy(sig, data.data(), 8); if (sig[0] != 137 || sig[1] != 72 || sig[2] != 68 || sig[3] != 70 || sig[4] != 13 || sig[5] != 10 || sig[6] != 26 || sig[7] != 10) { throw std::runtime_error("Invalid HDF5 signature"); } uint8_t version = data[8]; properties["Superblock Version"] = version; size_t pos = 9; if (version == 0 || version == 1) { properties["Free Space Version"] = data[pos++]; properties["Root Group Version"] = data[pos++]; pos++; // Reserved properties["Shared Header Message Version"] = data[pos++]; uint8_t offsetSize = data[pos++]; properties["Size of Offsets"] = offsetSize; uint8_t lengthSize = data[pos++]; properties["Size of Lengths"] = lengthSize; pos++; // Reserved uint16_t leafK; std::memcpy(&leafK, &data[pos], 2); properties["Group Leaf Node K"] = leafK; pos += 2; uint16_t internalK; std::memcpy(&internalK, &data[pos], 2); properties["Group Internal Node K"] = internalK; pos += 2; if (version == 0) { pos += 4; // Reserved } else { uint32_t flags; std::memcpy(&flags, &data[pos], 4); properties["File Consistency Flags"] = flags; pos += 4; } properties["Base Address"] = getUInt64(&data[pos], offsetSize); pos += offsetSize; properties["Free Space Address"] = getUInt64(&data[pos], offsetSize); pos += offsetSize; properties["End of File Address"] = getUInt64(&data[pos], offsetSize); pos += offsetSize; properties["Driver Info Address"] = getUInt64(&data[pos], offsetSize); pos += offsetSize; } else if (version == 2 || version == 3) { uint8_t offsetSize = data[pos++]; properties["Size of Offsets"] = offsetSize; uint8_t lengthSize = data[pos++]; properties["Size of Lengths"] = lengthSize; properties["File Consistency Flags"] = data[pos++]; properties["Base Address"] = getUInt64(&data[pos], offsetSize); pos += offsetSize; properties["Superblock Extension Address"] = getUInt64(&data[pos], offsetSize); pos += offsetSize; properties["End of File Address"] = getUInt64(&data[pos], offsetSize); pos += offsetSize; properties["Root Group Object Header Address"] = getUInt64(&data[pos], offsetSize); pos += offsetSize; uint32_t checksum; std::memcpy(&checksum, &data[pos], 4); properties["Superblock Checksum"] = checksum; } else { throw std::runtime_error("Unsupported superblock version"); } } uint64_t getUInt64(const uint8_t* ptr, size_t size) { uint64_t val = 0; for (size_t i = 0; i < size; ++i) { val |= static_cast(ptr[i]) << (i * 8); } return val; } void printProperties() { for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } void writeMinimal(const std::string& outputPath) { std::ofstream file(outputPath, std::ios::binary); if (!file) { throw std::runtime_error("Cannot create file"); } uint8_t sig[8] = {137, 72, 68, 70, 13, 10, 26, 10}; file.write(reinterpret_cast(sig), 8); file.put(3); // Version file.put(8); // Offset size file.put(8); // Length size file.put(0); // Flags setUInt64(file, 0, 8); // Base addr setUInt64(file, 0xFFFFFFFFFFFFFFFFULL, 8); // Ext addr setUInt64(file, 1024, 8); // EOF setUInt64(file, 96, 8); // Root addr uint32_t checksum = 0; file.write(reinterpret_cast(&checksum), 4); } void setUInt64(std::ofstream& file, uint64_t val, size_t size) { for (size_t i = 0; i < size; ++i) { file.put(static_cast(val >> (i * 8))); } } }; // ===== end task-283 .HDF5 ===== // ===== task-284 .HDI [C++] ===== #include #include #include #include #include class HDIFile { private: std::string filepath; uint32_t reserved = 0; uint32_t fddType = 0; uint32_t headerSize = 0; uint32_t dataSize = 0; uint32_t bytesPerSector = 0; uint32_t sectors = 0; uint32_t heads = 0; uint32_t cylinders = 0; std::vector comment; public: HDIFile(const std::string& fp = "") : filepath(fp) { if (!fp.empty()) { read(fp); } } void read(const std::string& fp) { filepath = fp; std::ifstream file(fp, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file"); } uint32_t header[8]; file.read(reinterpret_cast(header), 32); if (file.gcount() < 32) { throw std::runtime_error("Invalid HDI file: Header too short"); } reserved = header[0]; fddType = header[1]; headerSize = header[2]; dataSize = header[3]; bytesPerSector = header[4]; sectors = header[5]; heads = header[6]; cylinders = header[7]; if (reserved != 0) { std::cout << "Warning: Reserved field is not zero" << std::endl; } if (headerSize > 32) { comment.resize(headerSize - 32); file.read(reinterpret_cast(comment.data()), headerSize - 32); } } void printProperties() const { std::cout << "Reserved: " << reserved << std::endl; std::cout << "FDDType: " << fddType << std::endl; std::cout << "HeaderSize: " << headerSize << std::endl; std::cout << "DataSize: " << dataSize << std::endl; std::cout << "BytesPerSector: " << bytesPerSector << std::endl; std::cout << "Sectors: " << sectors << std::endl; std::cout << "Heads: " << heads << std::endl; std::cout << "Cylinders: " << cylinders << std::endl; std::string commentStr(comment.begin(), comment.end()); std::cout << "Comment: " << (commentStr.empty() ? "None" : commentStr) << std::endl; } void write(const std::string& outputPath = "") const { std::string out = outputPath.empty() ? (filepath.empty() ? "output.hdi" : filepath) : outputPath; std::ofstream file(out, std::ios::binary); if (!file) { throw std::runtime_error("Cannot write file"); } uint32_t header[8] = {reserved, fddType, headerSize, dataSize, bytesPerSector, sectors, heads, cylinders}; file.write(reinterpret_cast(header), 32); if (!comment.empty()) { file.write(reinterpret_cast(comment.data()), comment.size()); } // Note: Data segment not written; append if needed } }; // ===== end task-284 .HDI ===== // ===== task-282 .HAR [C] ===== #include #include #include #include #include typedef struct { char *filename; uint8_t *buffer; size_t file_size; struct DD *dds; int num_dds; } HDF4Handler; typedef struct { uint16_t tag; uint16_t ref; int32_t offset; int32_t length; } DD; void parse_signature(HDF4Handler *h) { uint8_t sig[4]; memcpy(sig, h->buffer, 4); uint8_t expected[4] = {0x0E, 0x03, 0x13, 0x01}; int valid = (sig[0] == expected[0] && sig[1] == expected[1] && sig[2] == expected[2] && sig[3] == expected[3]); printf("Signature: %s (0x%02X 0x%02X 0x%02X 0x%02X)\n", valid ? "Valid HDF4" : "Invalid", sig[0], sig[1], sig[2], sig[3]); } void parse_version(HDF4Handler *h) { for (int i = 0; i < h->num_dds; i++) { if (h->dds[i].tag == 30) { // 0x001E uint8_t *data = h->buffer + h->dds[i].offset; uint32_t ver_int = *(uint32_t *)data; // Big-endian assumed char ver_str[32]; strncpy(ver_str, (char *)(data + 4), h->dds[i].length - 4); ver_str[h->dds[i].length - 4] = '\0'; printf("Version: %u - %s\n", ver_int, ver_str); return; } } printf("Version not found\n"); } DD *parse_dd_blocks(HDF4Handler *h, int *num) { DD *dds = malloc(1024 * sizeof(DD)); // Arbitrary max int count = 0; size_t offset = 4; while (offset < h->file_size) { if (offset + 6 > h->file_size) break; uint16_t block_size = *(uint16_t *)(h->buffer + offset); uint32_t next_offset = *(uint32_t *)(h->buffer + offset + 2); offset += 6; for (int i = 0; i < block_size; i++) { if (offset + 12 > h->file_size) break; uint16_t tag = *(uint16_t *)(h->buffer + offset); uint16_t ref = *(uint16_t *)(h->buffer + offset + 2); int32_t data_offset = *(int32_t *)(h->buffer + offset + 4); int32_t length = *(int32_t *)(h->buffer + offset + 8); if (tag != 0) { dds[count].tag = tag; dds[count].ref = ref; dds[count].offset = data_offset; dds[count].length = length; count++; } offset += 12; } offset = next_offset; if (next_offset == 0) break; } *num = count; return dds; } void print_properties(HDF4Handler *h) { printf("File Size: %zu bytes\n", h->file_size); printf("Data Descriptors (%d total):\n", h->num_dds); for (int i = 0; i < h->num_dds; i++) { printf(" DD%d: Tag 0x%04X, Ref %d, Offset %d, Length %d\n", i, h->dds[i].tag, h->dds[i].ref, h->dds[i].offset, h->dds[i].length); } } char *parse_vgroup(HDF4Handler *h, uint16_t ref) { for (int i = 0; i < h->num_dds; i++) { if (h->dds[i].ref == ref && h->dds[i].tag == 1973) { // 0x07B5 char *str = malloc(100); snprintf(str, 100, "Offset %d, Length %d (hierarchy refs omitted)", h->dds[i].offset, h->dds[i].length); return str; } } return strdup("Vgroup not found"); } void hdf4_read(HDF4Handler *h) { FILE *f = fopen(h->filename, "rb"); if (!f) { printf("File not found.\n"); return; } fseek(f, 0, SEEK_END); h->file_size = ftell(f); fseek(f, 0, SEEK_SET); h->buffer = malloc(h->file_size); fread(h->buffer, 1, h->file_size, f); fclose(f); parse_signature(h); parse_version(h); h->dds = parse_dd_blocks(h, &h->num_dds); print_properties(h); if (h->num_dds > 0) { char *vg = parse_vgroup(h, 1); printf("Example Vgroup (ref 1): %s\n", vg); free(vg); } } void hdf4_write(HDF4Handler *h, char *output_filename) { FILE *f = fopen(output_filename, "wb"); if (!f) return; // Signature fwrite((uint8_t[]){0x0E, 0x03, 0x13, 0x01}, 1, 4, f); // DD block header uint16_t block_size = 2; uint32_t next = 0; fwrite(&block_size, 2, 1, f); fwrite(&next, 4, 1, f); // Version DD uint16_t tag1 = 30, ref1 = 1; int32_t off1 = 36, len1 = 8; fwrite(&tag1, 2, 1, f); fwrite(&ref1, 2, 1, f); fwrite(&off1, 4, 1, f); fwrite(&len1, 4, 1, f); // Vgroup DD uint16_t tag2 = 1973, ref2 = 2; int32_t off2 = 44, len2 = 4; fwrite(&tag2, 2, 1, f); fwrite(&ref2, 2, 1, f); fwrite(&off2, 4, 1, f); fwrite(&len2, 4, 1, f); // Dummy version uint32_t ver_int = 1; fwrite(&ver_int, 4, 1, f); fwrite("HDF4.0", 1, 6, f); // Dummy Vgroup uint32_t zero = 0; fwrite(&zero, 4, 1, f); fclose(f); printf("Simple .HDF written to %s\n", output_filename); } int main() { HDF4Handler h = { .filename = "sample.hdf" }; hdf4_read(&h); // Free resources... free(h.buffer); free(h.dds); hdf4_write(&h, "simple.hdf"); return 0; } // ===== end task-282 .HAR ===== // ===== task-285 .HDMP [C] ===== #include #include #include #include typedef struct { char signature[4]; uint8_t magic2[2]; uint16_t version; uint32_t num_streams; uint32_t dir_rva; uint32_t checksum; uint32_t timestamp; uint64_t flags; } HDMPHeader; typedef struct { uint32_t type; uint32_t size; uint32_t rva; } HDMPStream; typedef struct { FILE *file; HDMPHeader header; HDMPStream *streams; uint8_t *data; size_t data_size; } HDMPHandler; void hdmp_init(HDMPHandler *h, const char *filepath) { h->file = fopen(filepath, "rb"); if (!h->file) { perror("Failed to open file"); exit(1); } fseek(h->file, 0, SEEK_END); h->data_size = ftell(h->file); fseek(h->file, 0, SEEK_SET); h->data = malloc(h->data_size); fread(h->data, 1, h->data_size, h->file); fclose(h->file); } void hdmp_decode(HDMPHandler *h) { memcpy(h->header.signature, h->data, 4); if (strncmp(h->header.signature, "MDMP", 4) != 0) { fprintf(stderr, "Invalid signature\n"); exit(1); } memcpy(h->header.magic2, h->data + 4, 2); h->header.version = *(uint16_t*)(h->data + 6); h->header.num_streams = *(uint32_t*)(h->data + 8); h->header.dir_rva = *(uint32_t*)(h->data + 12); h->header.checksum = *(uint32_t*)(h->data + 16); h->header.timestamp = *(uint32_t*)(h->data + 20); h->header.flags = *(uint64_t*)(h->data + 24); h->streams = malloc(h->header.num_streams * sizeof(HDMPStream)); uint32_t offset = h->header.dir_rva; for (uint32_t i = 0; i < h->header.num_streams; i++) { h->streams[i].type = *(uint32_t*)(h->data + offset); h->streams[i].size = *(uint32_t*)(h->data + offset + 4); h->streams[i].rva = *(uint32_t*)(h->data + offset + 8); offset += 12; } // Decode specific streams as needed } void hdmp_print_properties(const HDMPHandler *h) { printf("HDMP Properties:\n"); printf("Signature: %.4s\n", h->header.signature); printf("Version (Magic2): 0x%02X 0x%02X\n", h->header.magic2[0], h->header.magic2[1]); printf("Version Number: %u\n", h->header.version); printf("Number of Streams: %u\n", h->header.num_streams); printf("Stream Directory RVA: 0x%X\n", h->header.dir_rva); printf("Checksum: 0x%X\n", h->header.checksum); printf("Time Date Stamp: %u\n", h->header.timestamp); printf("Flags: 0x%llX\n", (unsigned long long)h->header.flags); printf("Streams:\n"); for (uint32_t i = 0; i < h->header.num_streams; i++) { printf("Stream %u: Type = %u, Size = %u, RVA = 0x%X\n", i + 1, h->streams[i].type, h->streams[i].size, h->streams[i].rva); } // Print specific stream details as decoded } void hdmp_write(const HDMPHandler *h, const char *new_filepath) { FILE *out = fopen(new_filepath, "wb"); if (!out) { perror("Failed to write file"); exit(1); } if (h->data_size == 0) { // Create minimal HDMP uint8_t minimal[132] = {0}; memcpy(minimal, "MDMP", 4); minimal[4] = 0x93; minimal[5] = 0xA7; *(uint32_t*)(minimal + 12) = 32; // Dir RVA *(uint32_t*)(minimal + 20) = (uint32_t)time(NULL); // Timestamp fwrite(minimal, 1, 132, out); } else { fwrite(h->data, 1, h->data_size, out); } fclose(out); } void hdmp_free(HDMPHandler *h) { free(h->data); free(h->streams); } int main() { HDMPHandler h = {0}; hdmp_init(&h, "example.hdmp"); hdmp_decode(&h); hdmp_print_properties(&h); hdmp_write(&h, "new.hdmp"); hdmp_free(&h); return 0; } // ===== end task-285 .HDMP ===== // ===== task-286 .HEIC [C++] ===== #include #include #include #include #include #include class HeicHandler { private: std::string filepath; std::map properties; // Simplified to string values for demo. std::vector data; public: HeicHandler(const std::string& filepath) : filepath(filepath) { parse(); } void parse() { std::ifstream file(filepath, std::ios::binary); if (!file) return; file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(reinterpret_cast(data.data()), size); size_t offset = 0; while (offset < size) { uint32_t box_size; std::memcpy(&box_size, data.data() + offset, 4); box_size = __builtin_bswap32(box_size); // Big-endian. std::string type(reinterpret_cast(data.data() + offset + 4), 4); if (type == "ftyp") { std::string major_brand(reinterpret_cast(data.data() + offset + 8), 4); properties["Major Brand"] = major_brand; uint32_t minor_version; std::memcpy(&minor_version, data.data() + offset + 12, 4); minor_version = __builtin_bswap32(minor_version); properties["Minor Version"] = std::to_string(minor_version); std::string compat; for (size_t i = 16; i < box_size; i += 4) { compat += std::string(reinterpret_cast(data.data() + offset + i), 4) + " "; } properties["Compatible Brands"] = compat; } else if (type == "meta") { properties["Metadata Box Present"] = "Yes"; } // Extend for other boxes. offset += box_size; } properties["File Extension"] = ".heic"; properties["MIME Type"] = "image/heic"; } void printProperties() { for (const auto& [key, value] : properties) { std::cout << key << ": " << value << std::endl; } } void write(const std::string& newFilepath) { std::ofstream out(newFilepath, std::ios::binary); out.write(reinterpret_cast(data.data()), data.size()); } }; // Example usage: // int main() { // HeicHandler handler("sample.heic"); // handler.printProperties(); // handler.write("modified.heic"); // return 0; // } // ===== end task-286 .HEIC ===== // ===== task-287 .HEIF [C++] ===== #include #include #include #include #include #include #include class HEIFParser { private: std::string filepath; std::vector data; size_t offset = 0; std::map properties; // Use std::any for flexibility uint32_t readBE32() { uint32_t val = (data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]; offset += 4; return val; } uint64_t readBE64() { uint64_t hi = readBE32(); uint64_t lo = readBE32(); return (hi << 32) | lo; } std::string readString(size_t len) { std::string str(data.begin() + offset, data.begin() + offset + len); offset += len; return str; } uint8_t readU8() { return data[offset++]; } uint32_t readBE24() { return (readU8() << 16) | (readU8() << 8) | readU8(); } int32_t readSigned32() { int32_t val = (data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]; offset += 4; return val; } void parseBox() { size_t start = offset; uint64_t size = readBE32(); std::string type = readString(4); if (size == 1) size = readBE64(); size_t end = start + size; if (type == "uuid") offset += 16; if (type == "ftyp") { properties["majorBrand"] = readString(4); properties["minorVersion"] = readBE32(); std::vector brands; while (offset < end) brands.push_back(readString(4)); properties["compatibleBrands"] = brands; } else if (type == "meta") { offset += 4; while (offset < end) parseBox(); } else if (type == "hdlr") { offset += 4; offset += 4; properties["handlerType"] = readString(4); offset += 12; } else if (type == "pitm") { offset += 4; properties["primaryItemId"] = readBE32(); } // ... (similar to other languages; add remaining box parsing as in Python or Java) // For brevity, implement full parsing similarly to above examples offset = end; } public: HEIFParser(const std::string& fp) : filepath(fp) { std::ifstream file(fp, std::ios::binary); data = std::vector((std::istreambuf_iterator(file)), std::istreambuf_iterator()); parse(); } void parse() { while (offset < data.size()) parseBox(); } void printProperties() { // Implement printing recursively for map; for example: std::cout << "Properties:" << std::endl; // Traverse and print; use a custom printer for std::any } void write(const std::string& newFilepath, const std::map& updates = {}) { std::vector newData = data; if (!updates.empty()) { // Modify bytes for updates; omitted } std::ofstream out(newFilepath, std::ios::binary); out.write(reinterpret_cast(newData.data()), newData.size()); } }; // Example usage: // int main() { // HEIFParser parser("sample.heif"); // parser.printProperties(); // parser.write("modified.heif"); // return 0; // } // ===== end task-287 .HEIF ===== // ===== task-288 .HH [C++] ===== #include #include #include #include typedef struct { char* filename; char* content; bool includeGuards; // Simplified: count properties for demo (full list would need dynamic arrays) int includeCount; int macroCount; int typedefCount; int enumCount; int classCount; int funcCount; int varCount; int nsCount; } HHFileHandler; HHFileHandler* hh_create(const char* filename) { HHFileHandler* handler = malloc(sizeof(HHFileHandler)); handler->filename = strdup(filename); handler->content = NULL; handler->includeGuards = false; handler->includeCount = 0; handler->macroCount = 0; handler->typedefCount = 0; handler->enumCount = 0; handler->classCount = 0; handler->funcCount = 0; handler->varCount = 0; handler->nsCount = 0; return handler; } void hh_destroy(HHFileHandler* handler) { free(handler->filename); free(handler->content); free(handler); } void hh_read_decode(HHFileHandler* handler) { FILE* f = fopen(handler->filename, "r"); if (!f) return; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); handler->content = malloc(size + 1); fread(handler->content, 1, size, f); handler->content[size] = '\0'; fclose(f); char* line = strtok(handler->content, "\n"); int lineNum = 1; while (line) { char trimmed[1024]; strcpy(trimmed, line); // Trim (simple) char* end = trimmed + strlen(trimmed) - 1; while (end > trimmed && (*end == ' ' || *end == '\t')) end--; *(end + 1) = '\0'; if (strstr(trimmed, "#ifndef") || (strstr(trimmed, "#define") && strstr(trimmed, "_H")) || strstr(trimmed, "#endif")) { handler->includeGuards = true; } if (strstr(trimmed, "#include")) handler->includeCount++; if (strstr(trimmed, "#define")) handler->macroCount++; if (strstr(trimmed, "typedef")) handler->typedefCount++; if (strstr(trimmed, "enum")) handler->enumCount++; if (strstr(trimmed, "class ") || strstr(trimmed, "struct ")) handler->classCount++; if (strstr(trimmed, ";") && strstr(trimmed, "(") && !strstr(trimmed, "{")) handler->funcCount++; // Rough prototype match if (strstr(trimmed, ";") && !strstr(trimmed, "(") && strstr(trimmed, " ")) handler->varCount++; if (strstr(trimmed, "namespace")) handler->nsCount++; line = strtok(NULL, "\n"); lineNum++; } } void hh_print_properties(HHFileHandler* handler) { printf("{\n"); printf(" \"includeGuards\": %s,\n", handler->includeGuards ? "true" : "false"); printf(" \"includeDirectives\": %d,\n", handler->includeCount); printf(" \"macros\": %d,\n", handler->macroCount); printf(" \"typedefs\": %d,\n", handler->typedefCount); printf(" \"enums\": %d,\n", handler->enumCount); printf(" \"classesStructs\": %d,\n", handler->classCount); printf(" \"functionPrototypes\": %d,\n", handler->funcCount); printf(" \"variables\": %d,\n", handler->varCount); printf(" \"namespaces\": %d\n", handler->nsCount); printf("}\n"); } void hh_write(HHFileHandler* handler, const char* outputFilename) { FILE* f = fopen(outputFilename, "w"); if (!f) return; if (handler->includeGuards) { fprintf(f, "#ifndef EXAMPLE_H\n#define EXAMPLE_H\n"); } // Simplified: write placeholders based on counts for (int i = 0; i < handler->includeCount; i++) fprintf(f, "#include \n"); for (int i = 0; i < handler->macroCount; i++) fprintf(f, "#define MACRO %d\n", i); // ... (similar placeholders for others) if (handler->includeGuards) { fprintf(f, "#endif\n"); } fclose(f); } // Example usage: // HHFileHandler* handler = hh_create("example.hh"); // hh_read_decode(handler); // hh_print_properties(handler); // hh_write(handler, "reconstructed.hh"); // hh_destroy(handler); // ===== end task-288 .HH ===== // ===== task-289 .HIN [C] ===== #include #include #include #include #define MAX_LINE 1024 #define MAX_ATOMS 1000 #define MAX_MOLS 10 #define MAX_BONDS 12 typedef struct { int id; char name[65]; int num_atoms; // Simplified: atoms and residues as arrays; extend as needed // Atom struct: int num; char name[5], element[4], type[5], flags[10]; double charge, x,y,z; int coord_num; int bonds[MAX_BONDS][2]; // [to, type_code: 1=s,2=d,3=t,4=a] } Molecule; typedef struct { Molecule mols[MAX_MOLS]; int num_mols; char forcefield[32]; char sys[256]; // etc for seed, view, box } HinFile; HinFile hin; void parse_line(char* line, Molecule* current_mol) { if (strlen(line) == 0 || line[0] == ';') return; char keyword[16]; sscanf(line, "%s", keyword); if (strcmp(keyword, "forcefield") == 0) { sscanf(line + strlen(keyword) + 1, "%s", hin.forcefield); } else if (strcmp(keyword, "mol") == 0) { // Init new mol } else if (strcmp(keyword, "atom") == 0 && current_mol) { // Parse atom fields: sscanf(line + 5, "%d %s %s %s %s %lf %lf %lf %lf %d", &num, name, element, type, flags, &charge, &x, &y, &z, &coord_num); // Then parse bonds: manual loop with sscanf for pairs printf("Parsed atom line: %s\n", line); // Simplified dump } // ... extend for all keywords, res, vel, etc. Use strtok or sscanf for fields // For full impl, store in arrays } void read_hin(const char* filename) { FILE* fp = fopen(filename, "r"); if (!fp) return; char line[MAX_LINE]; Molecule* current_mol = NULL; while (fgets(line, MAX_LINE, fp)) { parse_line(line, current_mol); // Detect mol/endmol to switch current_mol if (strstr(line, "mol ")) current_mol = &hin.mols[hin.num_mols++]; // Print globals: printf("Forcefield: %s\n", hin.forcefield); // For atoms: print fields as parsed } fclose(fp); } void write_hin(const char* filename) { FILE* fp = fopen(filename, "w"); if (!fp) return; fprintf(fp, "forcefield %s\n", hin.forcefield); // Loop mols, fprintf atom lines from stored data fprintf(fp, "endmol 1\n"); // Example fclose(fp); printf("Wrote to %s\n", filename); } int main(int argc, char** argv) { if (argc < 2) return 1; read_hin(argv[1]); write_hin("output.hin"); return 0; } // ===== end task-289 .HIN ===== // ===== task-290 .HOF [C] ===== #include #include #include typedef struct { char name[256]; char serviceTrip[256]; char announcementFolder[256]; // Add other fields... int ibis900; int stringCountTerminus; } HofHeader; typedef struct { char code[10]; char name[256]; char** strings; int stringsLen; int allexit; } HofTerminus; typedef struct { HofHeader header; HofTerminus* termini; int terminiLen; // Add stops, routes... } HofFile; HofFile* hof_parse(const char* filename) { FILE* fp = fopen(filename, "r"); if (!fp) { perror("File open error"); return NULL; } HofFile* hof = malloc(sizeof(HofFile)); memset(hof, 0, sizeof(HofFile)); char line[512]; int currentTerminusIdx = -1; while (fgets(line, sizeof(line), fp)) { char* trimmed = line; while (*trimmed == '\t' || *trimmed == ' ' || *trimmed == '\n') trimmed++; if (strlen(trimmed) == 0) continue; if (strncmp(trimmed, "[name]", 6) == 0) { if (fgets(line, sizeof(line), fp)) { sscanf(line, "%s", hof->header.name); } } else if (strncmp(trimmed, "[servicetrip]", 13) == 0) { if (fgets(line, sizeof(line), fp)) { sscanf(line, "%s", hof->header.serviceTrip); } } else if (strstr(trimmed, "{announcement folder}")) { sscanf(trimmed, "{announcement folder} %s", hof->header.announcementFolder); } // Similar for other headers... else if (strstr(trimmed, "stringcount_terminus")) { sscanf(trimmed, "%*s %d", &hof->header.stringCountTerminus); } else if (strncmp(trimmed, "[addterminus]", 13) == 0 || strncmp(trimmed, "[addterminus_allexit]", 21) == 0) { hof->terminiLen++; hof->termini = realloc(hof->termini, hof->terminiLen * sizeof(HofTerminus)); currentTerminusIdx = hof->terminiLen - 1; HofTerminus* t = &hof->termini[currentTerminusIdx]; memset(t, 0, sizeof(HofTerminus)); t->allexit = (strstr(trimmed, "allexit") != NULL); if (fgets(line, sizeof(line), fp)) sscanf(line, "%s", t->code); if (fgets(line, sizeof(line), fp)) sscanf(line, "%s", t->name); t->strings = malloc(hof->header.stringCountTerminus * sizeof(char*)); for (int j = 0; j < hof->header.stringCountTerminus; j++) { if (fgets(line, sizeof(line), fp)) { t->strings[j] = malloc(256); sscanf(line, "%s", t->strings[j]); } } t->stringsLen = hof->header.stringCountTerminus; } } fclose(fp); return hof; } void hof_print(HofFile* hof) { printf("=== HOF Header ===\n"); printf("Name: %s\n", hof->header.name); printf("Service Trip: %s\n", hof->header.serviceTrip); // Similar... printf("\n=== Termini ===\n"); for (int i = 0; i < hof->terminiLen; i++) { HofTerminus* t = &hof->termini[i]; printf("Terminus (Allexit: %d): Code=%s, Name=%s\n", t->allexit, t->code, t->name); for (int j = 0; j < t->stringsLen; j++) { printf(" String: %s\n", t->strings[j]); } } // Similar for stops, routes... } void hof_write(HofFile* hof, const char* output) { FILE* fp = fopen(output, "w"); if (!fp) return; fprintf(fp, "[name]\n%s\n", hof->header.name); fprintf(fp, "[servicetrip]\n%s\n", hof->header.serviceTrip); // Reconstruct... for (int i = 0; i < hof->terminiLen; i++) { HofTerminus* t = &hof->termini[i]; const char* flag = t->allexit ? "[addterminus_allexit]\n" : "[addterminus]\n"; fprintf(fp, "%s%s\n%s\n", flag, t->code, t->name); for (int j = 0; j < t->stringsLen; j++) { fprintf(fp, "%s\n", t->strings[j]); } } // Add others... fclose(fp); printf("Written to %s\n", output); } void hof_free(HofFile* hof) { for (int i = 0; i < hof->terminiLen; i++) { for (int j = 0; j < hof->termini[i].stringsLen; j++) { free(hof->termini[i].strings[j]); } free(hof->termini[i].strings); } free(hof->termini); free(hof); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } HofFile* hof = hof_parse(argv[1]); if (hof) { hof_print(hof); // hof_write(hof, "output.hof"); hof_free(hof); } return 0; } // ===== end task-290 .HOF ===== // ===== task-291 .HOI4 [C++] ===== #include #include #include #include #include class HOI4FileHandler { private: std::string filepath; std::vector properties = { "File extension: .hoi4", "Container type: ZIP archive", "ZIP magic number: PK\\x03\\x04", "Contained files: meta, gamestate (required); rnsshot.png (optional)", "Format of contained files: plaintext or binary", "Plaintext header: HOI4txt", "Binary header: HOI4bin", "Syntax for plaintext: key = value or key = { nested key = value }", "Value types: strings, numbers, dates, arrays, nested objects", "Encoding: UTF-8 for plaintext" }; std::string metaContent; std::string gamestateContent; std::string readZipFile(zip_t* zip, const std::string& filename) { zip_file_t* f = zip_fopen(zip, filename.c_str(), 0); if (!f) return ""; std::string content; char buffer[1024]; zip_int64_t len; while ((len = zip_fread(f, buffer, sizeof(buffer))) > 0) { content.append(buffer, len); } zip_fclose(f); return content; } public: HOI4FileHandler(const std::string& fp) : filepath(fp) {} void readDecode() { int err = 0; zip_t* zip = zip_open(filepath.c_str(), ZIP_RDONLY, &err); if (!zip) { std::cout << "Error opening ZIP: " << err << std::endl; return; } std::string meta = readZipFile(zip, "meta"); if (!meta.empty()) { if (meta.substr(0, 7) == "HOI4bin") { std::cout << "Binary format detected for meta. Decoding not supported without token resolver." << std::endl; } else { metaContent = meta; } } std::string gamestate = readZipFile(zip, "gamestate"); if (!gamestate.empty()) { if (gamestate.substr(0, 7) == "HOI4bin") { std::cout << "Binary format detected for gamestate. Decoding not supported without token resolver." << std::endl; } else { gamestateContent = gamestate; } } zip_close(zip); } void printProperties() { for (const auto& prop : properties) { std::cout << prop << std::endl; } if (!metaContent.empty()) { std::cout << "\nMeta content:" << std::endl << metaContent << std::endl; } if (!gamestateContent.empty()) { std::cout << "\nGamestate content:" << std::endl << gamestateContent << std::endl; } } void write(const std::string& newFilepath, const std::string& newMeta = "", const std::string& newGamestate = "") { int err = 0; zip_t* zip = zip_open(newFilepath.c_str(), ZIP_CREATE | ZIP_TRUNCATE, &err); if (!zip) { std::cout << "Error creating ZIP: " << err << std::endl; return; } std::string useMeta = newMeta.empty() ? metaContent : newMeta; if (!useMeta.empty()) { zip_source_t* src = zip_source_buffer(zip, useMeta.c_str(), useMeta.size(), 0); zip_file_add(zip, "meta", src, ZIP_FL_OVERWRITE); } std::string useGamestate = newGamestate.empty() ? gamestateContent : newGamestate; if (!useGamestate.empty()) { zip_source_t* src = zip_source_buffer(zip, useGamestate.c_str(), useGamestate.size(), 0); zip_file_add(zip, "gamestate", src, ZIP_FL_OVERWRITE); } zip_close(zip); } }; // Example usage: // int main() { // HOI4FileHandler handler("example.hoi4"); // handler.readDecode(); // handler.printProperties(); // handler.write("new.hoi4", "HOI4txt\nplayer=\"NEW\""); // return 0; // } // ===== end task-291 .HOI4 ===== // ===== task-293 .HTA [C] ===== #include #include #include #include #define MAX_PROP_LEN 50 #define MAX_VALUE_LEN 256 #define NUM_PROPS 19 typedef struct { char *filepath; char *properties[NUM_PROPS][2]; // prop name, value char *originalContent; size_t contentLen; } HTAParser; void initProperties(HTAParser *parser) { const char *propList[NUM_PROPS] = { "applicationname", "border", "borderstyle", "caption", "contextmenu", "icon", "innerborder", "maximizebutton", "minimizebutton", "navigable", "scroll", "scrollflat", "selection", "showintaskbar", "singleinstance", "sysmenu", "version", "windowstate", "id" }; for (int i = 0; i < NUM_PROPS; i++) { parser->properties[i][0] = strdup(propList[i]); parser->properties[i][1] = strdup("Not set"); } } void loadFile(HTAParser *parser) { FILE *file = fopen(parser->filepath, "r"); if (!file) { perror("Failed to open file"); return; } fseek(file, 0, SEEK_END); parser->contentLen = ftell(file); fseek(file, 0, SEEK_SET); parser->originalContent = malloc(parser->contentLen + 1); fread(parser->originalContent, 1, parser->contentLen, file); parser->originalContent[parser->contentLen] = '\0'; fclose(file); // Basic parse: find char *start = strcasestr(parser->originalContent, "'); if (end) { char tagContent[4096]; strncpy(tagContent, start + 16, end - start - 16); // Skip properties[i][0], prop) == 0) { free(parser->properties[i][1]); parser->properties[i][1] = strdup(value); break; } } } token = strtok(NULL, " "); } } } } void printProperties(HTAParser *parser) { printf("Extracted HTA Properties:\n"); for (int i = 0; i < NUM_PROPS; i++) { printf("%s: %s\n", parser->properties[i][0], parser->properties[i][1]); } } void setProperty(HTAParser *parser, const char *prop, const char *value) { for (int i = 0; i < NUM_PROPS; i++) { if (strcasecmp(parser->properties[i][0], prop) == 0) { free(parser->properties[i][1]); parser->properties[i][1] = strdup(value); break; } } } void writeFile(HTAParser *parser, const char *outputPath) { // Rebuild tag char newTag[4096] = "properties[i][1], "Not set") != 0) { strcat(newTag, " "); strcat(newTag, parser->properties[i][0]); strcat(newTag, "=\""); strcat(newTag, parser->properties[i][1]); strcat(newTag, "\""); } } strcat(newTag, ">"); // Replace in content char *newContent = malloc(parser->contentLen + 1024); char *start = strcasestr(parser->originalContent, "'); if (end) { strncpy(newContent, parser->originalContent, start - parser->originalContent); newContent[start - parser->originalContent] = '\0'; strcat(newContent, newTag); strcat(newContent, end + 1); } else { strcpy(newContent, parser->originalContent); } } else { strcpy(newContent, parser->originalContent); } FILE *out = fopen(outputPath, "w"); if (out) { fwrite(newContent, 1, strlen(newContent), out); fclose(out); printf("Written updated HTA to %s\n", outputPath); } free(newContent); } void freeParser(HTAParser *parser) { for (int i = 0; i < NUM_PROPS; i++) { free(parser->properties[i][0]); free(parser->properties[i][1]); } free(parser->originalContent); free(parser->filepath); } // Example usage: // int main() { // HTAParser parser; // parser.filepath = strdup("example.hta"); // initProperties(&parser); // loadFile(&parser); // printProperties(&parser); // setProperty(&parser, "applicationname", "NewApp"); // writeFile(&parser, "modified.hta"); // freeParser(&parser); // return 0; // } // ===== end task-293 .HTA ===== // ===== task-294 .HTM [C++] ===== #include #include #include #include #include #include #include class HtmFileHandler { private: std::string filepath; struct stat stats; public: HtmFileHandler(const std::string& fp) : filepath(fp) { if (filepath.substr(filepath.find_last_of(".") + 1) != "htm") { throw std::invalid_argument("File must have .htm extension"); } if (stat(filepath.c_str(), &stats) != 0) { throw std::runtime_error("Failed to get file stats"); } } void readAndPrintProperties() { std::cout << "File Name: " << filepath.substr(filepath.find_last_of("/\\") + 1) << std::endl; std::cout << "File Size: " << stats.st_size << " bytes" << std::endl; std::cout << "MIME Type: text/html (inferred for .htm)" << std::endl; std::cout << "Last Modified Time: " << std::ctime(&stats.st_mtime); std::cout << "Creation Time: " << std::ctime(&stats.st_ctime); // On Unix, ctime is status change; no standard birth time std::cout << "Last Access Time: " << std::ctime(&stats.st_atime); std::cout << "Permissions: " << std::oct << (stats.st_mode & 0777) << std::dec << std::endl; std::cout << "Owner User ID: " << stats.st_uid << std::endl; std::cout << "Owner Group ID: " << stats.st_gid << std::endl; std::cout << "Inode Number: " << stats.st_ino << std::endl; std::cout << "Device ID: " << stats.st_dev << std::endl; std::cout << "Number of Hard Links: " << stats.st_nlink << std::endl; } void writeSampleHtm(const std::string& content = "Hello World") { std::ofstream file(filepath); if (file.is_open()) { file << content; file.close(); std::cout << "Written sample content to " << filepath << std::endl; } else { throw std::runtime_error("Failed to write file"); } } }; // Example usage: // int main() { // try { // HtmFileHandler handler("example.htm"); // handler.readAndPrintProperties(); // handler.writeSampleHtm(); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-294 .HTM ===== // ===== task-295 .HTML [C++] ===== #include #include #include #include #include #include #include class HtmFileHandler { private: std::string filepath; struct stat stats; public: HtmFileHandler(const std::string& fp) : filepath(fp) { if (filepath.substr(filepath.find_last_of(".") + 1) != "htm") { throw std::invalid_argument("File must have .htm extension"); } if (stat(filepath.c_str(), &stats) != 0) { throw std::runtime_error("Failed to get file stats"); } } void readAndPrintProperties() { std::cout << "File Name: " << filepath.substr(filepath.find_last_of("/\\") + 1) << std::endl; std::cout << "File Size: " << stats.st_size << " bytes" << std::endl; std::cout << "MIME Type: text/html (inferred for .htm)" << std::endl; std::cout << "Last Modified Time: " << std::ctime(&stats.st_mtime); std::cout << "Creation Time: " << std::ctime(&stats.st_ctime); // On Unix, ctime is status change; no standard birth time std::cout << "Last Access Time: " << std::ctime(&stats.st_atime); std::cout << "Permissions: " << std::oct << (stats.st_mode & 0777) << std::dec << std::endl; std::cout << "Owner User ID: " << stats.st_uid << std::endl; std::cout << "Owner Group ID: " << stats.st_gid << std::endl; std::cout << "Inode Number: " << stats.st_ino << std::endl; std::cout << "Device ID: " << stats.st_dev << std::endl; std::cout << "Number of Hard Links: " << stats.st_nlink << std::endl; } void writeSampleHtm(const std::string& content = "Hello World") { std::ofstream file(filepath); if (file.is_open()) { file << content; file.close(); std::cout << "Written sample content to " << filepath << std::endl; } else { throw std::runtime_error("Failed to write file"); } } }; // Example usage: // int main() { // try { // HtmFileHandler handler("example.htm"); // handler.readAndPrintProperties(); // handler.writeSampleHtm(); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-295 .HTML ===== // ===== task-296 .HUM [C++] ===== #include #include #include #include #include #include class HumFile { private: std::string filepath; std::map> properties; public: HumFile(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file: " << filepath << std::endl; return; } std::string line; std::string currentKey; std::vector bodyPositions; while (std::getline(file, line)) { line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); if (line.empty()) continue; if (line.front() == '[' && line.back() == ']') { currentKey = line.substr(1, line.size() - 2); std::transform(currentKey.begin(), currentKey.end(), currentKey.begin(), ::tolower); if (currentKey == "left") { bodyPositions.clear(); } else { properties[currentKey] = {}; } } else if (!currentKey.empty()) { if (currentKey == "left") { bodyPositions.push_back(line); } else { properties[currentKey].push_back(line); } } } if (!bodyPositions.empty()) { properties["body part positions"] = bodyPositions; } file.close(); } void printProperties() const { for (const auto& pair : properties) { std::string key = pair.first; key[0] = std::toupper(key[0]); std::cout << key << ": "; for (size_t i = 0; i < pair.second.size(); ++i) { std::cout << pair.second[i]; if (i < pair.second.size() - 1) std::cout << ", "; } std::cout << std::endl; } } void write(const std::string& newFilepath = "") const { std::string outPath = newFilepath.empty() ? filepath : newFilepath; std::ofstream file(outPath); if (!file.is_open()) { std::cerr << "Error writing file: " << outPath << std::endl; return; } for (const auto& pair : properties) { std::string key = pair.first; if (key == "body part positions") { file << "[left]\n"; } else { file << "[" << key << "]\n"; } for (const auto& val : pair.second) { file << val << "\n"; } } file.close(); } }; int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Usage: " << argv[0] << " " << std::endl; return 1; } HumFile hum(argv[1]); hum.read(); hum.printProperties(); // To write: hum.write("output.hum"); return 0; } // ===== end task-296 .HUM ===== // ===== task-297 .HXX [C] ===== #include #include #include #include #include #include #include typedef struct { char *file_path; char *content; } HXXFileHandler; HXXFileHandler* create_hxx_handler(const char *file_path) { HXXFileHandler *handler = malloc(sizeof(HXXFileHandler)); handler->file_path = strdup(file_path); handler->content = NULL; return handler; } void destroy_hxx_handler(HXXFileHandler *handler) { free(handler->file_path); free(handler->content); free(handler); } char* open_and_read(HXXFileHandler *handler) { FILE *fp = fopen(handler->file_path, "r"); if (!fp) { perror("Failed to open file"); return NULL; } fseek(fp, 0, SEEK_END); long size = ftell(fp); fseek(fp, 0, SEEK_SET); handler->content = malloc(size + 1); fread(handler->content, 1, size, fp); handler->content[size] = '\0'; fclose(fp); return handler->content; } void write_file(HXXFileHandler *handler, const char *new_content, const char *output_path) { const char *path = output_path ? output_path : handler->file_path; FILE *fp = fopen(path, "w"); if (!fp) { perror("Failed to write file"); return; } fprintf(fp, "%s", new_content); fclose(fp); } void print_properties(HXXFileHandler *handler) { struct stat st; if (stat(handler->file_path, &st) != 0) { perror("Failed to get file stats"); return; } printf("File Size (in bytes): %ld\n", st.st_size); printf("Last Modification Time: %s", ctime(&st.st_mtime)); printf("Last Access Time: %s", ctime(&st.st_atime)); printf("Last Status Change Time: %s", ctime(&st.st_ctime)); printf("File Mode (permissions): %o\n", st.st_mode); printf("Owner User ID (UID): %d\n", st.st_uid); printf("Owner Group ID (GID): %d\n", st.st_gid); printf("Inode Number: %ld\n", st.st_ino); printf("Number of Hard Links: %ld\n", st.st_nlink); printf("Device ID: %ld\n", st.st_dev); } // Example usage: // int main() { // HXXFileHandler *handler = create_hxx_handler("example.hxx"); // open_and_read(handler); // print_properties(handler); // write_file(handler, "New content", "new.hxx"); // destroy_hxx_handler(handler); // return 0; // } // ===== end task-297 .HXX ===== // ===== task-298 .ICAL [C++] ===== #include #include #include #include #include #include class ICalHandler { private: std::string filepath; std::map properties; std::map> components; void parse() { std::ifstream file(filepath); std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); // Unfold lines size_t pos; while ((pos = content.find("\r\n ")) != std::string::npos) content.erase(pos + 2, 1); while ((pos = content.find("\n ")) != std::string::npos) content.erase(pos + 1, 1); std::istringstream iss(content); std::string line; std::string currentComponent; while (std::getline(iss, line)) { if (line.rfind("BEGIN:", 0) == 0) { currentComponent = line.substr(6); components[currentComponent] = {}; } else if (line.rfind("END:", 0) == 0) { currentComponent = ""; } else { size_t colon = line.find(':'); if (colon != std::string::npos) { std::string keyPart = line.substr(0, colon); std::string value = line.substr(colon + 1); size_t semi = keyPart.find(';'); std::string key = (semi == std::string::npos) ? keyPart : keyPart.substr(0, semi); std::string params = (semi == std::string::npos) ? "" : keyPart.substr(semi); std::string full = key + params + ":" + value; if (!currentComponent.empty()) { components[currentComponent][key] = full; } else { properties[key] = full; } } } } } public: ICalHandler(const std::string& fp) : filepath(fp) { parse(); } void printProperties() { std::cout << "Global Properties:" << std::endl; for (const auto& p : properties) { std::cout << p.second << std::endl; } for (const auto& c : components) { std::cout << "\nComponent " << c.first << ":" << std::endl; for (const auto& p : c.second) { std::cout << " " << p.second << std::endl; } } } void write(const std::string& newFilepath = "") { std::string outPath = newFilepath.empty() ? filepath : newFilepath; std::ofstream file(outPath); file << "BEGIN:VCALENDAR\n"; for (const auto& p : properties) { file << p.second << "\n"; } for (const auto& c : components) { file << "BEGIN:" << c.first << "\n"; for (const auto& p : c.second) { file << p.second << "\n"; } file << "END:" << c.first << "\n"; } file << "END:VCALENDAR\n"; file.close(); } }; // Example usage: // int main() { // ICalHandler handler("sample.ical"); // handler.printProperties(); // handler.write("output.ical"); // return 0; // } // ===== end task-298 .ICAL ===== // ===== task-299 .ICAL [C++] ===== #include #include #include #include #include #pragma pack(1) typedef struct { uint32_t size; char cmm[4]; uint32_t version; char class_sig[4]; char color_space[4]; char pcs[4]; uint16_t year, month, day, hour, min, sec; char file_sig[4]; char platform[4]; uint32_t flags; char manufacturer[4]; char model[4]; uint64_t attributes; uint32_t intent; int32_t illum_x, illum_y, illum_z; // s15Fixed16 char creator[4]; uint8_t id[16]; uint8_t reserved[28]; } ICCHeader; #pragma pack() typedef struct { ICCHeader header; } ICCProfile; void read_icc(ICCProfile *profile, const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) { perror("Failed to open file"); exit(1); } fread(&profile->header, sizeof(ICCHeader), 1, f); fclose(f); // Note: In C, big-endian conversion may be needed if host is little-endian (use htonl/ntohl etc. if required) } void print_properties(const ICCProfile *profile) { printf("Profile size: %u\n", profile->header.size); printf("Preferred CMM type: %.4s\n", profile->header.cmm); uint8_t major = (profile->header.version >> 24) & 0xFF; uint8_t minor = (profile->header.version >> 20) & 0xF; uint8_t bugfix = (profile->header.version >> 16) & 0xF; printf("Profile version number: %u.%u.%u.0\n", major, minor, bugfix); printf("Profile/Device class: %.4s\n", profile->header.class_sig); printf("Data color space: %.4s\n", profile->header.color_space); printf("Profile Connection Space (PCS): %.4s\n", profile->header.pcs); printf("Creation date and time: %04u-%02u-%02u %02u:%02u:%02u\n", profile->header.year, profile->header.month, profile->header.day, profile->header.hour, profile->header.min, profile->header.sec); printf("Profile file signature: %.4s\n", profile->header.file_sig); printf("Primary platform: %.4s\n", profile->header.platform); printf("Profile flags: 0x%08x\n", profile->header.flags); printf("Device manufacturer: %.4s\n", profile->header.manufacturer); printf("Device model: %.4s\n", profile->header.model); printf("Device attributes: 0x%016llx\n", (unsigned long long)profile->header.attributes); printf("Rendering intent: %u\n", profile->header.intent); double x = profile->header.illum_x / 65536.0; double y = profile->header.illum_y / 65536.0; double z = profile->header.illum_z / 65536.0; printf("PCS illuminant: X=%.4f, Y=%.4f, Z=%.4f\n", x, y, z); printf("Profile creator: %.4s\n", profile->header.creator); printf("Profile ID: "); for (int i = 0; i < 16; i++) printf("%02x", profile->header.id[i]); printf("\n"); printf("Reserved: "); for (int i = 0; i < 28; i++) printf("%02x", profile->header.reserved[i]); printf("\n"); } void write_icc(const ICCProfile *profile, const char *filename) { FILE *f = fopen(filename, "wb"); if (!f) { perror("Failed to write file"); exit(1); } fwrite(&profile->header, sizeof(ICCHeader), 1, f); fclose(f); printf("Wrote basic header to %s (full write requires tag data)\n", filename); } // Example usage: // int main() { // ICCProfile icc; // read_icc(&icc, "example.icc"); // print_properties(&icc); // write_icc(&icc, "new.icc"); // return 0; // } // ===== end task-299 .ICAL ===== // ===== task-301 .ICL [C++] ===== #include #include #include #include #include #include // For bigendian #include // For EBCDIC conversion struct Field { std::string name; int start, length; std::string type; }; class ICLHandler { private: std::string filepath; std::map> recordMaps; public: ICLHandler(const std::string& fp) : filepath(fp) { // Example for 01 recordMaps["01"] = { {"Standard Level", 2, 2, "N"}, {"Test File Indicator", 4, 1, "A"}, // Add all }; // Add for other types } std::string ebcdicToAscii(const char* bytes, size_t len) { iconv_t cd = iconv_open("UTF-8", "IBM037"); char* in = const_cast(bytes); char outBuf[1024]; size_t outLen = sizeof(outBuf); char* out = outBuf; iconv(cd, &in, &len, &out, &outLen); iconv_close(cd); return std::string(outBuf, sizeof(outBuf) - outLen).substr(0, outBuf + sizeof(outBuf) - out - outLen); } void* parseField(const char* bytes, const std::string& type) { std::string str = ebcdicToAscii(bytes, length).erase(std::remove(str.begin(), str.end(), ' '), str.end()); if (type == "N" || type == "NB" || type == "NBSM" || type == "NBSMOS") { return reinterpret_cast(std::stol(str)); } return reinterpret_cast(new std::string(str)); } void read() { std::ifstream file(filepath, std::ios::binary); std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); size_t position = 0; while (position < data.size()) { uint32_t length = be32toh(*reinterpret_cast(&data[position])); position += 4; std::vector recordData(data.begin() + position, data.begin() + position + length); position += length; std::string type = ebcdicToAscii(&recordData[0], 2); std::cout << "Record Type: " << type << std::endl; auto fields = recordMaps[type]; for (const auto& field : fields) { const char* fieldBytes = &recordData[field.start]; void* value = parseField(fieldBytes, field.type); if (field.type[0] == 'N') { std::cout << field.name << ": " << *reinterpret_cast(value) << std::endl; } else { std::cout << field.name << ": " << *reinterpret_cast(value) << std::endl; delete reinterpret_cast(value); } } std::cout << std::endl; } } void write(const std::map>& records) { std::ofstream file(filepath, std::ios::binary); for (const auto& entry : records) { // Build recordData from values, convert to EBCDIC std::vector recordData; // Stub uint32_t length = htobe32(recordData.size()); file.write(reinterpret_cast(&length), 4); file.write(recordData.data(), recordData.size()); } } }; // Example usage: // ICLHandler handler("sample.icl"); // handler.read(); // ===== end task-301 .ICL ===== // ===== task-302 .ICN [C++] ===== #include #include #include #include #include #include // For big-endian conversion, may need on some systems struct IconEntry { std::string osType; uint32_t entryLength; std::vector data; }; class ICNSHandler { private: std::string filepath; std::string magic; uint32_t fileLength; std::vector entries; public: ICNSHandler(const std::string& filepath) : filepath(filepath) { readFile(); } void readFile() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { throw std::runtime_error("Could not open file"); } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); std::vector data(size); if (!file.read(reinterpret_cast(data.data()), size)) { throw std::runtime_error("Could not read file"); } magic = std::string(data.begin(), data.begin() + 4); if (magic != "icns") { throw std::runtime_error("Not a valid ICNS file"); } fileLength = be32toh(*reinterpret_cast(&data[4])); uint32_t offset = 8; while (offset < fileLength) { std::string osType(data.begin() + offset, data.begin() + offset + 4); uint32_t entryLength = be32toh(*reinterpret_cast(&data[offset + 4])); std::vector entryData(data.begin() + offset + 8, data.begin() + offset + entryLength); entries.push_back({osType, entryLength, entryData}); offset += entryLength; } } void printProperties() const { std::cout << "File Extension: .icns" << std::endl; std::cout << "MIME Type: image/x-icns" << std::endl; std::cout << "Developer: Apple Inc." << std::endl; std::cout << "Magic Number: 'icns'" << std::endl; std::cout << "Endianness: Big-endian" << std::endl; std::cout << "Total File Length: " << fileLength << " bytes" << std::endl; std::cout << "Icon Entries:" << std::endl; for (const auto& entry : entries) { std::string size = getSizeFromOSType(entry.osType); std::string format = getFormatFromOSType(entry.osType); std::cout << " - OSType: " << entry.osType << ", Entry Length: " << entry.entryLength << " bytes, Size: " << size << ", Format: " << format << std::endl; } std::cout << "Supported Sizes: 16x12, 16x16, 32x32, 48x48, 128x128, etc." << std::endl; std::cout << "Data Formats: Uncompressed bitmap, RLE, PNG, JPEG 2000" << std::endl; std::cout << "Alpha Channels: Supported (1-bit/8-bit masks or embedded)" << std::endl; } std::string getSizeFromOSType(const std::string& osType) const { if (osType == "ICON" || osType == "ICN#") return "32x32"; if (osType == "icm#" || osType == "icm4" || osType == "icm8") return "16x12"; if (osType == "ics#" || osType == "ics4" || osType == "ics8" || osType == "is32" || osType == "s8mk") return "16x16"; if (osType == "icl4" || osType == "icl8" || osType == "il32" || osType == "l8mk") return "32x32"; if (osType == "ich#" || osType == "ich4" || osType == "ich8" || osType == "ih32" || osType == "h8mk") return "48x48"; if (osType == "it32" || osType == "t8mk") return "128x128"; if (osType == "icp4") return "16x16"; if (osType == "icp5") return "32x32"; if (osType == "icp6") return "48x48"; return "Unknown"; } std::string getFormatFromOSType(const std::string& osType) const { if (osType == "ICON") return "1-bit mono"; if (osType == "ICN#" || osType == "icm#" || osType == "ics#" || osType == "ich#") return "1-bit mono with mask"; if (osType == "icm4" || osType == "ics4" || osType == "icl4" || osType == "ich4") return "4-bit color"; if (osType == "icm8" || osType == "ics8" || osType == "icl8" || osType == "ich8") return "8-bit color"; if (osType == "is32" || osType == "il32" || osType == "ih32" || osType == "it32") return "24-bit RGB RLE"; if (osType == "s8mk" || osType == "l8mk" || osType == "h8mk" || osType == "t8mk") return "8-bit mask"; if (osType == "icp4" || osType == "icp5" || osType == "icp6") return "PNG/JPEG2000/24-bit RGB"; return "Unknown"; } void writeFile(const std::string& newFilepath) const { std::ofstream file(newFilepath, std::ios::binary); if (!file) { throw std::runtime_error("Could not open file for writing"); } file.write(magic.c_str(), 4); uint32_t beFileLength = htobe32(fileLength); file.write(reinterpret_cast(&beFileLength), 4); for (const auto& entry : entries) { file.write(entry.osType.c_str(), 4); uint32_t beEntryLength = htobe32(entry.entryLength); file.write(reinterpret_cast(&beEntryLength), 4); file.write(reinterpret_cast(entry.data.data()), entry.data.size()); } } }; // Example usage: // int main() { // try { // ICNSHandler handler("path/to/file.icns"); // handler.printProperties(); // handler.writeFile("path/to/new_file.icns"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-302 .ICN ===== // ===== task-303 .ICO [C++] ===== #include #include #include #include #include #include struct IcoEntry { uint8_t width; // adjusted to 256 if 0 uint8_t height; uint8_t color_count; uint8_t reserved; uint16_t planes; uint16_t bit_count; uint32_t data_size; uint32_t data_offset; std::string format; std::vector image_data; }; class IcoHandler { private: std::string filename; uint16_t reserved; uint16_t type; uint16_t count; std::vector entries; public: IcoHandler(const std::string& fn) : filename(fn) { read(); } void read() { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) { throw std::runtime_error("Cannot open file"); } size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(reinterpret_cast(data.data()), size); file.close(); if (size < 6) throw std::runtime_error("Invalid ICO file"); memcpy(&reserved, data.data(), 2); memcpy(&type, data.data() + 2, 2); memcpy(&count, data.data() + 4, 2); if (reserved != 0 || type != 1) { throw std::runtime_error("Invalid ICO header"); } size_t offset = 6; for (uint16_t i = 0; i < count; ++i) { if (offset + 16 > size) throw std::runtime_error("Truncated entry"); IcoEntry entry; entry.width = data[offset]; entry.width = (entry.width == 0) ? 256 : entry.width; entry.height = data[offset + 1]; entry.height = (entry.height == 0) ? 256 : entry.height; entry.color_count = data[offset + 2]; entry.reserved = data[offset + 3]; memcpy(&entry.planes, data.data() + offset + 4, 2); memcpy(&entry.bit_count, data.data() + offset + 6, 2); memcpy(&entry.data_size, data.data() + offset + 8, 4); memcpy(&entry.data_offset, data.data() + offset + 12, 4); size_t img_start = entry.data_offset; size_t img_end = img_start + entry.data_size; if (img_end > size) throw std::runtime_error("Invalid image data"); entry.image_data.assign(data.begin() + img_start, data.begin() + img_end); entry.format = "Unknown"; if (entry.data_size >= 2 && entry.image_data[0] == 0x42 && entry.image_data[1] == 0x4D) { entry.format = "BMP"; } else if (entry.data_size >= 8 && entry.image_data[0] == 0x89 && entry.image_data[1] == 0x50 && entry.image_data[2] == 0x4E && entry.image_data[3] == 0x47 && entry.image_data[4] == 0x0D && entry.image_data[5] == 0x0A && entry.image_data[6] == 0x1A && entry.image_data[7] == 0x0A) { entry.format = "PNG"; } entries.push_back(entry); offset += 16; } } void printProperties() const { std::cout << "ICO Properties:" << std::endl; std::cout << "- Reserved: " << reserved << std::endl; std::cout << "- Type: " << type << std::endl; std::cout << "- Image Count: " << count << std::endl << std::endl; for (size_t i = 0; i < entries.size(); ++i) { const auto& entry = entries[i]; std::cout << "Image " << (i + 1) << ":" << std::endl; std::cout << " - Width: " << static_cast(entry.width) << std::endl; std::cout << " - Height: " << static_cast(entry.height) << std::endl; std::cout << " - Color Count: " << static_cast(entry.color_count) << std::endl; std::cout << " - Reserved: " << static_cast(entry.reserved) << std::endl; std::cout << " - Color Planes: " << entry.planes << std::endl; std::cout << " - Bits Per Pixel: " << entry.bit_count << std::endl; std::cout << " - Image Data Size: " << entry.data_size << std::endl; std::cout << " - Image Data Offset: " << entry.data_offset << std::endl; std::cout << " - Image Format: " << entry.format << std::endl << std::endl; } } void write(const std::string& outputFilename) { // Recompute offsets size_t header_size = 6 + entries.size() * 16; uint32_t current_offset = static_cast(header_size); for (auto& entry : entries) { entry.data_offset = current_offset; entry.data_size = static_cast(entry.image_data.size()); current_offset += entry.data_size; } std::vector buffer(current_offset); // Write header memcpy(buffer.data(), &reserved, 2); memcpy(buffer.data() + 2, &type, 2); uint16_t new_count = static_cast(entries.size()); memcpy(buffer.data() + 4, &new_count, 2); // Write entries size_t offset = 6; for (const auto& entry : entries) { uint8_t w = (entry.width < 256) ? entry.width : 0; uint8_t h = (entry.height < 256) ? entry.height : 0; buffer[offset] = w; buffer[offset + 1] = h; buffer[offset + 2] = entry.color_count; buffer[offset + 3] = entry.reserved; memcpy(buffer.data() + offset + 4, &entry.planes, 2); memcpy(buffer.data() + offset + 6, &entry.bit_count, 2); memcpy(buffer.data() + offset + 8, &entry.data_size, 4); memcpy(buffer.data() + offset + 12, &entry.data_offset, 4); offset += 16; } // Write image data for (const auto& entry : entries) { memcpy(buffer.data() + entry.data_offset, entry.image_data.data(), entry.data_size); } std::ofstream out_file(outputFilename, std::ios::binary); if (!out_file) { throw std::runtime_error("Cannot write file"); } out_file.write(reinterpret_cast(buffer.data()), buffer.size()); out_file.close(); std::cout << "Wrote ICO to " << outputFilename << std::endl; } }; int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Usage: " << argv[0] << " input.ico [output.ico]" << std::endl; return 1; } try { IcoHandler handler(argv[1]); handler.printProperties(); if (argc > 2) { handler.write(argv[2]); } } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } // ===== end task-303 .ICO ===== // ===== task-304 .ICS [C++] ===== #include #include #include #include #include class IcsHandler { private: std::string filepath; std::string content; std::map properties; public: IcsHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::in | std::ios::binary); if (!file) { throw std::runtime_error("Failed to open file."); } std::string line; content.clear(); while (std::getline(file, line, '\n')) { if (!line.empty() && line.back() == '\r') line.pop_back(); content += line + "\r\n"; } file.close(); decode(); } void decode() { if (content.empty()) { throw std::runtime_error("No content read from file."); } size_t dotPos = filepath.find_last_of('.'); std::string ext = (dotPos != std::string::npos) ? filepath.substr(dotPos + 1) : ""; std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); properties["File Extension"] = (ext == "ics") ? ".ics" : "Invalid"; properties["MIME Type"] = "text/calendar"; properties["Character Encoding"] = "UTF-8"; properties["Line Terminator"] = (content.find("\r\n") != std::string::npos) ? "CRLF" : "Unknown"; std::string::size_type pos = 0; int maxLength = 0; bool hasFolding = false; while ((pos = content.find("\r\n", pos)) != std::string::npos) { std::string::size_type start = (pos == 0) ? 0 : content.rfind("\r\n", pos - 2) + 2; int len = pos - start; if (len > maxLength) maxLength = len; if (start < content.size() && (content[start] == ' ' || content[start] == '\t')) hasFolding = true; pos += 2; } properties["Line Length Limit"] = "Observed max: " + std::to_string(maxLength) + " octets (recommended <=75)"; properties["Line Folding"] = hasFolding ? "Yes" : "No"; std::string trimmed = content; trimmed.erase(0, trimmed.find_first_not_of(" \t\r\n")); trimmed.erase(trimmed.find_last_not_of(" \t\r\n") + 1); properties["File Signature"] = (trimmed.rfind("BEGIN:VCALENDAR", 0) == 0) ? "BEGIN:VCALENDAR" : "Invalid/Missing"; properties["File Trailer"] = (trimmed.find("END:VCALENDAR", trimmed.size() - 13) != std::string::npos) ? "END:VCALENDAR" : "Invalid/Missing"; } void printProperties() const { if (properties.empty()) { std::cout << "No properties decoded." << std::endl; return; } std::cout << "ICS File Properties:" << std::endl; for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& outputPath = "") const { if (content.empty()) { throw std::runtime_error("No content to write."); } std::string path = outputPath.empty() ? filepath : outputPath; std::ofstream file(path, std::ios::out | std::ios::binary); if (!file) { throw std::runtime_error("Failed to write file."); } file << content; file.close(); std::cout << "File written to " << path << std::endl; } }; // Example usage: // int main() { // try { // IcsHandler handler("sample.ics"); // handler.read(); // handler.printProperties(); // handler.write("output.ics"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-304 .ICS ===== // ===== task-305 .IFB [C++] ===== #include #include #include #include #include class IFBHandler { private: std::string filepath; std::map properties; public: IFBHandler(const std::string& fp) : filepath(fp) {} void read() { properties.clear(); std::ifstream file(filepath); if (!file) { std::cerr << "Error opening file." << std::endl; return; } std::string line, currentSection; while (std::getline(file, line)) { // Handle line continuation while (line.back() == '\\') { line.pop_back(); std::string nextLine; std::getline(file, nextLine); line += nextLine; } std::istringstream iss(line); std::string trimmed; std::getline(iss >> std::ws, trimmed, '\n'); if (trimmed.empty() || trimmed[0] == ';') continue; if (trimmed[0] == '[' && trimmed.back() == ']') { currentSection = trimmed.substr(1, trimmed.size() - 2); } else { size_t eqPos = trimmed.find('='); if (eqPos != std::string::npos) { std::string key = trimmed.substr(0, eqPos); std::string value = trimmed.substr(eqPos + 1); // Trim spaces key.erase(0, key.find_first_not_of(" \t")); key.erase(key.find_last_not_of(" \t") + 1); value.erase(0, value.find_first_not_of(" \t")); value.erase(value.find_last_not_of(" \t") + 1); std::string fullKey = currentSection.empty() ? key : currentSection + "." + key; properties[fullKey] = value; } } } printProperties(); } void printProperties() { std::cout << "Properties:" << std::endl; for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::map& newProperties) { for (const auto& pair : newProperties) { properties[pair.first] = pair.second; } std::map> sections; for (const auto& pair : properties) { std::string fullKey = pair.first; std::string value = pair.second; std::string section, key; size_t dotPos = fullKey.find('.'); if (dotPos != std::string::npos) { section = fullKey.substr(0, dotPos); key = fullKey.substr(dotPos + 1); } else { key = fullKey; } sections[section][key] = value; } std::ofstream file(filepath); if (!file) { std::cerr << "Error writing file." << std::endl; return; } for (const auto& secPair : sections) { if (!secPair.first.empty()) { file << "[" << secPair.first << "]" << std::endl; } for (const auto& propPair : secPair.second) { file << propPair.first << " = " << propPair.second << std::endl; } } } }; // Example usage: // int main() { // IFBHandler handler("example.ifb"); // handler.read(); // std::map updates = {{"Siebel Interface Manager.PROCESS", "NewValue"}}; // handler.write(updates); // return 0; // } // ===== end task-305 .IFB ===== // ===== task-306 .IFC [C++] ===== #include #include #include #include #include #include #include class IFCFileHandler { private: std::string filepath; std::map> properties; // Use vector for lists std::string fullText; std::string header; public: IFCFileHandler(const std::string& fp) : filepath(fp) { readAndDecode(); } void readAndDecode() { std::ifstream file(filepath); if (!file) { throw std::runtime_error("Error opening file"); } std::stringstream buffer; buffer << file.rdbuf(); fullText = buffer.str(); if (fullText.find("ISO-10303-21;") != 0) { throw std::invalid_argument("Invalid .IFC file: Missing magic string."); } size_t headerStart = fullText.find("HEADER;"); size_t headerEnd = fullText.find("ENDSEC;", headerStart); if (headerStart == std::string::npos || headerEnd == std::string::npos) { throw std::invalid_argument("Invalid .IFC file: Missing HEADER section."); } header = fullText.substr(headerStart + 7, headerEnd - headerStart - 7); std::regex fileDescRegex(R"(FILE_DESCRIPTION\(\((.*?)\),'([\d;]+)'\);)"); std::smatch fileDescMatch; if (std::regex_search(header, fileDescMatch, fileDescRegex)) { std::string descStr = fileDescMatch[1].str(); std::vector desc; std::regex descItem(R"('(.*?)')"); std::sregex_iterator iter(descStr.begin(), descStr.end(), descItem); for (; iter != std::sregex_iterator(); ++iter) { desc.push_back((*iter)[1].str()); } properties["Description"] = desc; properties["Implementation Level"] = {fileDescMatch[2].str()}; } std::regex fileNameRegex(R"(FILE_NAME\('(.*?)','(.*?)',\((.*?)\),\((.*?)\),'(.*?)','(.*?)','(.*?)'(.*))"); std::smatch fileNameMatch; if (std::regex_search(header, fileNameMatch, fileNameRegex)) { properties["File Name"] = {fileNameMatch[1].str()}; properties["Time Stamp"] = {fileNameMatch[2].str()}; std::string authorStr = fileNameMatch[3].str(); std::vector authors; std::sregex_iterator aIter(authorStr.begin(), authorStr.end(), descItem); for (; aIter != std::sregex_iterator(); ++aIter) { authors.push_back((*aIter)[1].str()); } properties["Author"] = authors; std::string orgStr = fileNameMatch[4].str(); std::vector orgs; std::sregex_iterator oIter(orgStr.begin(), orgStr.end(), descItem); for (; oIter != std::sregex_iterator(); ++oIter) { orgs.push_back((*oIter)[1].str()); } properties["Organization"] = orgs; properties["Preprocessor Version"] = {fileNameMatch[5].str()}; properties["Originating System"] = {fileNameMatch[6].str()}; properties["Authorization"] = {fileNameMatch[7].str()}; } std::regex fileSchemaRegex(R"(FILE_SCHEMA\(\((.*?)\)\);)"); std::smatch fileSchemaMatch; if (std::regex_search(header, fileSchemaMatch, fileSchemaRegex)) { std::string schemaStr = fileSchemaMatch[1].str(); std::vector schemas; std::sregex_iterator sIter(schemaStr.begin(), schemaStr.end(), descItem); for (; sIter != std::sregex_iterator(); ++sIter) { schemas.push_back((*sIter)[1].str()); } properties["Schema"] = schemas; } } void printProperties() const { for (const auto& pair : properties) { std::cout << pair.first << ": "; for (size_t i = 0; i < pair.second.size(); ++i) { std::cout << pair.second[i]; if (i < pair.second.size() - 1) std::cout << ", "; } std::cout << std::endl; } } void updateProperty(const std::string& key, const std::vector& newValue) { if (properties.count(key)) { properties[key] = newValue; } } void write(const std::string& outputPath) { std::string newHeader = buildHeader(); std::string newText = fullText; newText.replace(fullText.find(header), header.length(), newHeader); std::ofstream outFile(outputPath); if (!outFile) { throw std::runtime_error("Error writing file"); } outFile << newText; } private: std::string buildHeader() const { std::string fileDesc; auto it = properties.find("Description"); if (it != properties.end()) { std::string desc; for (const auto& d : it->second) { if (!desc.empty()) desc += ","; desc += "'" + d + "'"; } auto implIt = properties.find("Implementation Level"); std::string impl = (implIt != properties.end() && !implIt->second.empty()) ? implIt->second[0] : "2;1"; fileDesc = "FILE_DESCRIPTION((" + desc + "),'" + impl + "');"; } std::string fileName; std::string name = (properties.count("File Name") && !properties.at("File Name").empty()) ? properties.at("File Name")[0] : ""; std::string timestamp = (properties.count("Time Stamp") && !properties.at("Time Stamp").empty()) ? properties.at("Time Stamp")[0] : ""; std::string author; if (properties.count("Author")) { for (const auto& a : properties.at("Author")) { if (!author.empty()) author += ","; author += "'" + a + "'"; } } std::string org; if (properties.count("Organization")) { for (const auto& o : properties.at("Organization")) { if (!org.empty()) org += ","; org += "'" + o + "'"; } } std::string prepVer = (properties.count("Preprocessor Version") && !properties.at("Preprocessor Version").empty()) ? properties.at("Preprocessor Version")[0] : ""; std::string origSys = (properties.count("Originating System") && !properties.at("Originating System").empty()) ? properties.at("Originating System")[0] : ""; std::string auth = (properties.count("Authorization") && !properties.at("Authorization").empty()) ? properties.at("Authorization")[0] : ""; fileName = "FILE_NAME('" + name + "','" + timestamp + "',(" + author + "),(" + org + "),'" + prepVer + "','" + origSys + "','" + auth + "');"; std::string fileSchema; it = properties.find("Schema"); if (it != properties.end()) { std::string schema; for (const auto& s : it->second) { if (!schema.empty()) schema += ","; schema += "'" + s + "'"; } fileSchema = "FILE_SCHEMA((" + schema + "));"; } return fileDesc + "\n" + fileName + "\n" + fileSchema; } }; // Example usage: // int main() { // try { // IFCFileHandler handler("example.ifc"); // handler.printProperties(); // handler.updateProperty("Time Stamp", {"2025-09-27T12:00:00"}); // handler.write("modified.ifc"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-306 .IFC ===== // ===== task-307 .IGC [C] ===== #include #include #include #include #define MAX_LINES 10000 #define MAX_STR 256 #define MAX_LIST 1000 typedef struct { char manufacturerCode[4]; char serialNumber[11]; char extension[MAX_STR]; } ARecord; typedef struct { char key[MAX_STR]; char value[MAX_STR]; } HPair; typedef struct { int numAdditions; char additions[MAX_LIST][8]; int additionsCount; } IRecord; // Similar for J typedef struct { char dateTime[15]; char lat[9]; char lon[10]; char desc[MAX_STR]; } CRecord; typedef struct { char stationID[5]; char type[MAX_STR]; } DRecord; typedef struct { char time[7]; char satellites[MAX_LIST][3]; int satellitesCount; } FRecord; typedef struct { char time[7]; char lat[9]; char lon[10]; char validity; int pressAlt; int gnssAlt; char extensions[MAX_STR]; } BRecord; typedef struct { char time[7]; char code[4]; char data[MAX_STR]; } ERecord; typedef struct { char time[7]; char extensions[MAX_STR]; } KRecord; typedef struct { char source[4]; char comment[MAX_STR]; } LRecord; typedef struct { char hash[MAX_STR]; } GRecord; typedef struct { char* filepath; ARecord a; HPair h[MAX_LIST]; int hCount; IRecord i; IRecord j; // Reuse struct for J CRecord c[MAX_LIST]; int cCount; DRecord d[MAX_LIST]; int dCount; FRecord f[MAX_LIST]; int fCount; BRecord b[MAX_LIST]; int bCount; ERecord e[MAX_LIST]; int eCount; KRecord k[MAX_LIST]; int kCount; LRecord l[MAX_LIST]; int lCount; GRecord g[MAX_LIST]; int gCount; } IGCData; void initIGCData(IGCData* data, const char* filepath) { data->filepath = filepath ? strdup(filepath) : NULL; memset(&data->a, 0, sizeof(ARecord)); data->hCount = 0; memset(&data->i, 0, sizeof(IRecord)); memset(&data->j, 0, sizeof(IRecord)); data->cCount = 0; data->dCount = 0; data->fCount = 0; data->bCount = 0; data->eCount = 0; data->kCount = 0; data->lCount = 0; data->gCount = 0; } void readIGC(IGCData* data) { if (!data->filepath) return; FILE* fp = fopen(data->filepath, "r"); if (!fp) { perror("File not found"); return; } char line[MAX_STR]; while (fgets(line, sizeof(line), fp)) { char* trim = strtok(line, "\r\n"); if (!trim || strlen(trim) == 0) continue; char type = toupper(trim[0]); switch (type) { case 'A': strncpy(data->a.manufacturerCode, trim + 1, 3); data->a.manufacturerCode[3] = '\0'; strncpy(data->a.serialNumber, trim + 4, strlen(trim + 4) > 3 ? 3 : strlen(trim + 4)); data->a.serialNumber[3] = '\0'; // Simplified if (strlen(trim) > 7) strncpy(data->a.extension, trim + 7, sizeof(data->a.extension) - 1); break; case 'H': { char* colon = strchr(trim + 2, ':'); int subtypeLen = colon ? colon - (trim + 2) : strlen(trim + 2); strncpy(data->h[data->hCount].key, trim + 2, subtypeLen); data->h[data->hCount].key[subtypeLen] = '\0'; if (colon) strncpy(data->h[data->hCount].value, colon + 1, sizeof(data->h[data->hCount].value) - 1); data->hCount++; } break; case 'I': data->i.numAdditions = atoi(trim + 1); data->i.additionsCount = 0; for (int idx = 3; idx < strlen(trim); idx += 7) { strncpy(data->i.additions[data->i.additionsCount++], trim + idx, 7); } break; case 'J': data->j.numAdditions = atoi(trim + 1); data->j.additionsCount = 0; for (int idx = 3; idx < strlen(trim); idx += 7) { strncpy(data->j.additions[data->j.additionsCount++], trim + idx, 7); } break; case 'C': strncpy(data->c[data->cCount].dateTime, trim + 1, 14); strncpy(data->c[data->cCount].lat, trim + 15, 8); strncpy(data->c[data->cCount].lon, trim + 23, 9); if (strlen(trim) > 33) strncpy(data->c[data->cCount].desc, trim + 33, sizeof(data->c[data->cCount].desc) - 1); data->cCount++; break; case 'D': strncpy(data->d[data->dCount].stationID, trim + 1, 4); if (strlen(trim) > 5) strncpy(data->d[data->dCount].type, trim + 5, sizeof(data->d[data->dCount].type) - 1); data->dCount++; break; case 'F': strncpy(data->f[data->fCount].time, trim + 1, 6); data->f[data->fCount].satellitesCount = 0; for (int idx = 7; idx < strlen(trim); idx += 2) { strncpy(data->f[data->fCount].satellites[data->f[data->fCount].satellitesCount++], trim + idx, 2); } data->fCount++; break; case 'B': strncpy(data->b[data->bCount].time, trim + 1, 6); strncpy(data->b[data->bCount].lat, trim + 7, 8); strncpy(data->b[data->bCount].lon, trim + 15, 9); data->b[data->bCount].validity = trim[24]; char altStr[6]; strncpy(altStr, trim + 25, 5); altStr[5] = '\0'; data->b[data->bCount].pressAlt = atoi(altStr); strncpy(altStr, trim + 30, 5); data->b[data->bCount].gnssAlt = atoi(altStr); if (strlen(trim) > 35) strncpy(data->b[data->bCount].extensions, trim + 35, sizeof(data->b[data->bCount].extensions) - 1); data->bCount++; break; case 'E': strncpy(data->e[data->eCount].time, trim + 1, 6); strncpy(data->e[data->eCount].code, trim + 7, 3); if (strlen(trim) > 10) strncpy(data->e[data->eCount].data, trim + 10, sizeof(data->e[data->eCount].data) - 1); data->eCount++; break; case 'K': strncpy(data->k[data->kCount].time, trim + 1, 6); if (strlen(trim) > 7) strncpy(data->k[data->kCount].extensions, trim + 7, sizeof(data->k[data->kCount].extensions) - 1); data->kCount++; break; case 'L': strncpy(data->l[data->lCount].source, trim + 1, 3); if (strlen(trim) > 4) strncpy(data->l[data->lCount].comment, trim + 4, sizeof(data->l[data->lCount].comment) - 1); data->lCount++; break; case 'G': strncpy(data->g[data->gCount].hash, trim + 1, sizeof(data->g[data->gCount].hash) - 1); data->gCount++; break; } } fclose(fp); } void printIGCProperties(const IGCData* data) { printf("{\n"); printf(" \"A\": {\n \"manufacturerCode\": \"%s\",\n \"serialNumber\": \"%s\",\n \"extension\": \"%s\"\n },\n", data->a.manufacturerCode, data->a.serialNumber, data->a.extension); printf(" \"H\": {\n"); for (int idx = 0; idx < data->hCount; idx++) { printf(" \"%s\": \"%s\"%s\n", data->h[idx].key, data->h[idx].value, idx < data->hCount - 1 ? "," : ""); } printf(" },\n"); printf(" \"I\": {\n \"numAdditions\": %d,\n \"additions\": [", data->i.numAdditions); for (int idx = 0; idx < data->i.additionsCount; idx++) { printf("\"%s\"%s", data->i.additions[idx], idx < data->i.additionsCount - 1 ? ", " : ""); } printf("]\n },\n"); // Similarly for J (reuse code pattern) printf(" \"J\": {\n \"numAdditions\": %d,\n \"additions\": [", data->j.numAdditions); for (int idx = 0; idx < data->j.additionsCount; idx++) { printf("\"%s\"%s", data->j.additions[idx], idx < data->j.additionsCount - 1 ? ", " : ""); } printf("]\n },\n"); printf(" \"C\": [\n"); for (int idx = 0; idx < data->cCount; idx++) { printf(" {\"dateTime\": \"%s\", \"lat\": \"%s\", \"lon\": \"%s\", \"desc\": \"%s\"}%s\n", data->c[idx].dateTime, data->c[idx].lat, data->c[idx].lon, data->c[idx].desc, idx < data->cCount - 1 ? "," : ""); } printf(" ],\n"); // Repeat similar printf patterns for D, F, B, E, K, L, G printf(" \"D\": [\n"); for (int idx = 0; idx < data->dCount; idx++) { printf(" {\"stationID\": \"%s\", \"type\": \"%s\"}%s\n", data->d[idx].stationID, data->d[idx].type, idx < data->dCount - 1 ? "," : ""); } printf(" ],\n"); printf(" \"F\": [\n"); for (int idx = 0; idx < data->fCount; idx++) { printf(" {\"time\": \"%s\", \"satellites\": [", data->f[idx].time); for (int s = 0; s < data->f[idx].satellitesCount; s++) { printf("\"%s\"%s", data->f[idx].satellites[s], s < data->f[idx].satellitesCount - 1 ? ", " : ""); } printf("]}%s\n", idx < data->fCount - 1 ? "," : ""); } printf(" ],\n"); printf(" \"B\": [\n"); for (int idx = 0; idx < data->bCount; idx++) { printf(" {\"time\": \"%s\", \"lat\": \"%s\", \"lon\": \"%s\", \"validity\": \"%c\", \"pressAlt\": %d, \"gnssAlt\": %d, \"extensions\": \"%s\"}%s\n", data->b[idx].time, data->b[idx].lat, data->b[idx].lon, data->b[idx].validity, data->b[idx].pressAlt, data->b[idx].gnssAlt, data->b[idx].extensions, idx < data->bCount - 1 ? "," : ""); } printf(" ],\n"); printf(" \"E\": [\n"); for (int idx = 0; idx < data->eCount; idx++) { printf(" {\"time\": \"%s\", \"code\": \"%s\", \"data\": \"%s\"}%s\n", data->e[idx].time, data->e[idx].code, data->e[idx].data, idx < data->eCount - 1 ? "," : ""); } printf(" ],\n"); printf(" \"K\": [\n"); for (int idx = 0; idx < data->kCount; idx++) { printf(" {\"time\": \"%s\", \"extensions\": \"%s\"}%s\n", data->k[idx].time, data->k[idx].extensions, idx < data->kCount - 1 ? "," : ""); } printf(" ],\n"); printf(" \"L\": [\n"); for (int idx = 0; idx < data->lCount; idx++) { printf(" {\"source\": \"%s\", \"comment\": \"%s\"}%s\n", data->l[idx].source, data->l[idx].comment, idx < data->lCount - 1 ? "," : ""); } printf(" ],\n"); printf(" \"G\": [\n"); for (int idx = 0; idx < data->gCount; idx++) { printf(" \"%s\"%s\n", data->g[idx].hash, idx < data->gCount - 1 ? "," : ""); } printf(" ]\n"); printf("}\n"); } void writeIGC(const IGCData* data, const char* newFilepath) { const char* path = newFilepath ? newFilepath : data->filepath; if (!path) return; FILE* fp = fopen(path, "w"); if (!fp) { perror("Cannot write file"); return; } // Write A fprintf(fp, "A%s%s%s\n", data->a.manufacturerCode, data->a.serialNumber, data->a.extension); // Write H for (int idx = 0; idx < data->hCount; idx++) { fprintf(fp, "H%s:%s\n", data->h[idx].key, data->h[idx].value); } // Write I if (data->i.numAdditions > 0) { fprintf(fp, "I%02d", data->i.numAdditions); for (int idx = 0; idx < data->i.additionsCount; idx++) { fprintf(fp, "%s", data->i.additions[idx]); } fprintf(fp, "\n"); } // Similarly for J if (data->j.numAdditions > 0) { fprintf(fp, "J%02d", data->j.numAdditions); for (int idx = 0; idx < data->j.additionsCount; idx++) { fprintf(fp, "%s", data->j.additions[idx]); } fprintf(fp, "\n"); } // Write C for (int idx = 0; idx < data->cCount; idx++) { fprintf(fp, "C%s%s%s%s\n", data->c[idx].dateTime, data->c[idx].lat, data->c[idx].lon, data->c[idx].desc); } // Write D for (int idx = 0; idx < data->dCount; idx++) { fprintf(fp, "D%s%s\n", data->d[idx].stationID, data->d[idx].type); } // Write F for (int idx = 0; idx < data->fCount; idx++) { fprintf(fp, "F%s", data->f[idx].time); for (int s = 0; s < data->f[idx].satellitesCount; s++) { fprintf(fp, "%s", data->f[idx].satellites[s]); } fprintf(fp, "\n"); } // Write B for (int idx = 0; idx < data->bCount; idx++) { fprintf(fp, "B%s%s%s%c%05d%05d%s\n", data->b[idx].time, data->b[idx].lat, data->b[idx].lon, data->b[idx].validity, data->b[idx].pressAlt, data->b[idx].gnssAlt, data->b[idx].extensions); } // Write E for (int idx = 0; idx < data->eCount; idx++) { fprintf(fp, "E%s%s%s\n", data->e[idx].time, data->e[idx].code, data->e[idx].data); } // Write K for (int idx = 0; idx < data->kCount; idx++) { fprintf(fp, "K%s%s\n", data->k[idx].time, data->k[idx].extensions); } // Write L for (int idx = 0; idx < data->lCount; idx++) { fprintf(fp, "L%s%s\n", data->l[idx].source, data->l[idx].comment); } // Write G for (int idx = 0; idx < data->gCount; idx++) { fprintf(fp, "G%s\n", data->g[idx].hash); } fclose(fp); } // Example usage: // int main() { // IGCData data; // initIGCData(&data, "example.igc"); // readIGC(&data); // printIGCProperties(&data); // // Modify example // strcpy(data.h[0].value, "New Pilot"); // Assume first H is pilot // writeIGC(&data, "modified.igc"); // free(data.filepath); // return 0; // } // ===== end task-307 .IGC ===== // ===== task-308 .IGES [C++] ===== #include #include #include #include #include #include class IGESParser { private: std::vector properties; std::string global_str; std::string other_content; public: void open_file(const std::string& filepath) { std::ifstream file(filepath); std::string line; global_str = ""; other_content = ""; bool in_global = false; while (std::getline(file, line)) { if (line.length() < 73) continue; if (line[72] == 'G') { in_global = true; global_str += line.substr(0, 72); } else { if (in_global) in_global = false; other_content += line + "\n"; } } file.close(); } void decode_properties() { size_t index = 0; char param_delim = ','; char record_delim = ';'; auto skip_spaces = [&]() { while (index < global_str.length() && global_str[index] == ' ') ++index; }; auto read_token = [&](char delim) -> std::string { skip_spaces(); std::string token; while (index < global_str.length() && global_str[index] != delim && global_str[index] != record_delim) { token += global_str[index++]; } if (index < global_str.length() && global_str[index] == delim) ++index; return token; }; auto parse_hollerith = [](const std::string& token) -> std::string { size_t h_pos = token.find('H'); if (h_pos != std::string::npos) { std::string num_str = token.substr(0, h_pos); if (std::regex_match(num_str, std::regex("\\d+"))) { int length = std::stoi(num_str); return token.substr(h_pos + 1, length); } } return token; }; // Parse first two with defaults std::string token = read_token(param_delim); param_delim = !token.empty() ? parse_hollerith(token)[0] : ','; token = read_token(record_delim); record_delim = !token.empty() ? parse_hollerith(token)[0] : ';'; // Parse rest properties.clear(); while (index < global_str.length()) { skip_spaces(); if (global_str[index] == record_delim) break; std::string token_str; bool in_hollerith = false; std::string h_count; int h_length = 0; while (index < global_str.length() && global_str[index] != param_delim && global_str[index] != record_delim) { char ch = global_str[index++]; if (!in_hollerith && isdigit(ch)) { h_count += ch; } else if (!in_hollerith && ch == 'H') { in_hollerith = true; h_length = !h_count.empty() ? std::stoi(h_count) : 0; h_count = ""; } else { token_str += ch; } } if (in_hollerith) token_str = token_str.substr(0, h_length); properties.push_back(token_str); if (index < global_str.length() && global_str[index] == param_delim) ++index; } } void print_properties() { std::vector labels = { "Parameter Delimiter", "Record Delimiter", "Sending Product ID", "File Name", "Native System ID", "Preprocessor Version", "Integer Bits", "Single Prec Magnitude", "Single Prec Significance", "Double Prec Magnitude", "Double Prec Significance", "Receiving Product ID", "Model Scale", "Units Flag", "Units Name", "Line Weight Gradations", "Max Line Width", "Generation Date", "Minimum Resolution", "Max Coordinate", "Author Name", "Organization", "IGES Version Flag", "Drafting Standard Flag", "Modified Date", "Application Protocol" }; for (size_t i = 0; i < properties.size(); ++i) { std::cout << (i < labels.size() ? labels[i] : "Extra") << ": " << properties[i] << std::endl; } } void write_file(const std::string& output_path, const std::vector& new_properties = {}) { if (!new_properties.empty()) properties = new_properties; // Reconstruct global_str (simplified) std::string global_rebuilt = "1H" + properties[0] + ",1H" + properties[1] + ","; for (size_t i = 2; i < properties.size(); ++i) { const std::string& prop = properties[i]; if (std::regex_match(prop, std::regex("[-+]?\\d*\\.?\\d+([eE][-+]?\\d+)?")) || std::regex_match(prop, std::regex("\\d+"))) { global_rebuilt += prop + ","; } else { global_rebuilt += std::to_string(prop.length()) + "H" + prop + ","; } } global_rebuilt = std::regex_replace(global_rebuilt, std::regex(",$"), ";"); // Pad and split into lines std::string global_lines; int seq = 1; for (size_t i = 0; i < global_rebuilt.length(); i += 72) { std::string chunk = global_rebuilt.substr(i, 72); chunk += std::string(72 - chunk.length(), ' '); std::ostringstream oss; oss << "G" << std::setw(7) << seq++; global_lines += chunk + oss.str() + "\n"; } std::ofstream out(output_path); out << global_lines << other_content; out.close(); } }; // Example usage: // int main() { // IGESParser parser; // parser.open_file("example.iges"); // parser.decode_properties(); // parser.print_properties(); // parser.write_file("modified.iges"); // return 0; // } // ===== end task-308 .IGES ===== // ===== task-309 .IMG [C++] ===== #include #include #include #include #include class IMGParser { private: std::string filename; uint8_t boot_sector[512]; std::unordered_map> properties; // Use vector for multi-byte or int values bool is_fat32; public: IMGParser(const std::string& fn) : filename(fn), is_fat32(false) { read(); } void read() { std::ifstream file(filename, std::ios::binary); if (file) { file.read(reinterpret_cast(boot_sector), 512); file.close(); decode(); } } void decode() { properties["Jump Instruction"] = {boot_sector[0], boot_sector[1], boot_sector[2]}; char oem[9]; memcpy(oem, boot_sector + 3, 8); oem[8] = '\0'; properties["OEM Name"] = {reinterpret_cast(strdup(oem))}; // Store as string pointer cast properties["Bytes per Sector"] = {*reinterpret_cast(boot_sector + 0x0B)}; properties["Sectors per Cluster"] = {boot_sector[0x0D]}; properties["Reserved Sectors"] = {*reinterpret_cast(boot_sector + 0x0E)}; properties["Number of FATs"] = {boot_sector[0x10]}; properties["Root Directory Entries"] = {*reinterpret_cast(boot_sector + 0x11)}; properties["Total Sectors"] = {*reinterpret_cast(boot_sector + 0x13)}; properties["Media Descriptor"] = {boot_sector[0x15]}; properties["Sectors per FAT"] = {*reinterpret_cast(boot_sector + 0x16)}; properties["Sectors per Track"] = {*reinterpret_cast(boot_sector + 0x18)}; properties["Number of Heads"] = {*reinterpret_cast(boot_sector + 0x1A)}; properties["Hidden Sectors"] = {*reinterpret_cast(boot_sector + 0x1C)}; properties["Large Total Sectors"] = {*reinterpret_cast(boot_sector + 0x20)}; is_fat32 = properties["Sectors per FAT"][0] == 0; int offset_drive = is_fat32 ? 0x40 : 0x24; int offset_reserved = offset_drive + 1; int offset_sig = offset_reserved + 1; int offset_vol_id = offset_sig + 1; int offset_vol_label = offset_vol_id + 4; int offset_fs_type = offset_vol_label + 11; properties["Physical Drive Number"] = {boot_sector[offset_drive]}; properties["Reserved"] = {boot_sector[offset_reserved]}; properties["Extended Boot Signature"] = {boot_sector[offset_sig]}; properties["Volume ID"] = {*reinterpret_cast(boot_sector + offset_vol_id)}; char vol_label[12]; memcpy(vol_label, boot_sector + offset_vol_label, 11); vol_label[11] = '\0'; properties["Volume Label"] = {reinterpret_cast(strdup(vol_label))}; char fs_type[9]; memcpy(fs_type, boot_sector + offset_fs_type, 8); fs_type[8] = '\0'; properties["File System Type"] = {reinterpret_cast(strdup(fs_type))}; if (is_fat32) { properties["Sectors per FAT Large"] = {*reinterpret_cast(boot_sector + 0x24)}; properties["FAT Flags"] = {*reinterpret_cast(boot_sector + 0x28)}; properties["Version"] = {*reinterpret_cast(boot_sector + 0x2A)}; properties["Root Cluster"] = {*reinterpret_cast(boot_sector + 0x2C)}; properties["FS Info Sector"] = {*reinterpret_cast(boot_sector + 0x30)}; properties["Backup Boot Sector"] = {*reinterpret_cast(boot_sector + 0x32)}; } properties["Boot Sector Signature"] = {*reinterpret_cast(boot_sector + 0x1FE)}; } void print_properties() { for (const auto& p : properties) { std::cout << p.first << ": "; if (p.first == "OEM Name" || p.first == "Volume Label" || p.first == "File System Type") { std::cout << reinterpret_cast(p.second[0]); } else if (p.first == "Jump Instruction") { std::cout << p.second[0] << " " << p.second[1] << " " << p.second[2]; } else { std::cout << p.second[0]; } std::cout << std::endl; } } void set_property(const std::string& key, const std::vector& value) { if (properties.count(key)) { properties[key] = value; encode(); } } void encode() { *reinterpret_cast(boot_sector + 0x0B) = properties["Bytes per Sector"][0]; boot_sector[0x0D] = properties["Sectors per Cluster"][0]; *reinterpret_cast(boot_sector + 0x0E) = properties["Reserved Sectors"][0]; boot_sector[0x10] = properties["Number of FATs"][0]; *reinterpret_cast(boot_sector + 0x11) = properties["Root Directory Entries"][0]; *reinterpret_cast(boot_sector + 0x13) = properties["Total Sectors"][0]; boot_sector[0x15] = properties["Media Descriptor"][0]; *reinterpret_cast(boot_sector + 0x16) = properties["Sectors per FAT"][0]; *reinterpret_cast(boot_sector + 0x18) = properties["Sectors per Track"][0]; *reinterpret_cast(boot_sector + 0x1A) = properties["Number of Heads"][0]; *reinterpret_cast(boot_sector + 0x1C) = properties["Hidden Sectors"][0]; *reinterpret_cast(boot_sector + 0x20) = properties["Large Total Sectors"][0]; // Similar for other fields... // For strings, memcpy memcpy(boot_sector + 3, reinterpret_cast(properties["OEM Name"][0]), 8); int offset_vol_label = (is_fat32 ? 0x47 : 0x2B); memcpy(boot_sector + offset_vol_label, reinterpret_cast(properties["Volume Label"][0]), 11); int offset_fs_type = (is_fat32 ? 0x52 : 0x36); memcpy(boot_sector + offset_fs_type, reinterpret_cast(properties["File System Type"][0]), 8); // Jump auto jump = properties["Jump Instruction"]; boot_sector[0] = jump[0]; boot_sector[1] = jump[1]; boot_sector[2] = jump[2]; *reinterpret_cast(boot_sector + 0x1FE) = properties["Boot Sector Signature"][0]; // Add similar for FAT32 fields if needed } void write(const std::string& new_filename = "") { std::string fn = new_filename.empty() ? filename : new_filename; std::ofstream file(fn, std::ios::binary | std::ios::in); if (file) { file.write(reinterpret_cast(boot_sector), 512); file.close(); } } }; // Example usage: // int main() { // IMGParser parser("example.img"); // parser.print_properties(); // parser.set_property("Volume Label", {reinterpret_cast(strdup("NEWLABEL"))}); // parser.write(); // return 0; // } // ===== end task-309 .IMG ===== // ===== task-310 .INFO [C] ===== #include #include #include typedef struct { char *data; long size; char *preamble; char *indirect_table; char *tag_table; char *local_variables; char **regular_nodes; int node_count; char *menu; char *image; char *printindex; char *cross_reference; } InfoFile; InfoFile *info_file_create(const char *filename) { InfoFile *info = malloc(sizeof(InfoFile)); FILE *f = fopen(filename, "r"); if (!f) return NULL; fseek(f, 0, SEEK_END); info->size = ftell(f); fseek(f, 0, SEEK_SET); info->data = malloc(info->size + 1); fread(info->data, 1, info->size, f); info->data[info->size] = 0; fclose(f); return info; } void info_file_decode(InfoFile *info) { // Preamble char *preamble_end = strchr(info->data + 1, 31); if (preamble_end) { info->preamble = strndup(info->data + 1, preamble_end - (info->data + 1)); } // Indirect table char *indirect_start = strstr(info->data, "\x1FIndirect\x1F"); if (indirect_start) { indirect_start += 11; char *end = strchr(indirect_start, 31); info->indirect_table = strndup(indirect_start, end - indirect_start); } // Tag table char *tag_start = strstr(info->data, "\x1FTag table:\x1F"); if (tag_start) { tag_start += 12; char *end = strchr(tag_start, 31); info->tag_table = strndup(tag_start, end - tag_start); } // Local variables char *local_start = strstr(info->data, "\x1FLocal Variables:\x1F"); if (local_start) { local_start += 19; char *end = strstr(local_start, "End:"); info->local_variables = strndup(local_start, end - local_start); } // Regular nodes (simple count) char *pos = info->data; info->node_count = 0; while ((pos = strstr(pos, "\x1FFile: ")) != NULL) { info->node_count++; pos += 8; } info->regular_nodes = malloc(info->node_count * sizeof(char*)); pos = info->data; int i = 0; while ((pos = strstr(pos, "\x1FFile: ")) != NULL) { pos += 1; char *end = strchr(pos, 31); info->regular_nodes[i++] = strndup(pos, end - pos); pos = end; } // Menu char *menu_start = strstr(info->data, "* Menu:"); if (menu_start) { char *end = strstr(menu_start, "\n\n"); info->menu = strndup(menu_start, end - menu_start); } // Image char *image_start = strstr(info->data, "* Image:"); if (image_start) { char *end = strchr(image_start, '.'); info->image = strndup(image_start, end - image_start + 1); } // Printindex char *printindex_start = strstr(info->data, "* printindex"); if (printindex_start) { char *end = strchr(printindex_start, '\n'); info->printindex = strndup(printindex_start, end - printindex_start); } // Cross-reference char *xref_start = strstr(info->data, "*note "); if (xref_start) { char *end = strstr(xref_start, "::"); info->cross_reference = strndup(xref_start, end - xref_start + 2); } } void info_file_print_properties(InfoFile *info) { printf("PREAMBLE: %s\n", info->preamble ? info->preamble : "Not found"); printf("INDIRECT_TABLE: %s\n", info->indirect_table ? info->indirect_table : "Not found"); printf("TAG_TABLE: %s\n", info->tag_table ? info->tag_table : "Not found"); printf("LOCAL_VARIABLES: %s\n", info->local_variables ? info->local_variables : "Not found"); printf("REGULAR_NODES:\n"); for (int i = 0; i < info->node_count; i++) { printf("Node %d: %s\n", i + 1, info->regular_nodes[i]); } printf("MENU: %s\n", info->menu ? info->menu : "Not found"); printf("IMAGE: %s\n", info->image ? info->image : "Not found"); printf("PRINTINDEX: %s\n", info->printindex ? info->printindex : "Not found"); printf("CROSS_REFERENCE: %s\n", info->cross_reference ? info->cross_reference : "Not found"); } void info_file_write(InfoFile *info, const char *new_filename) { FILE *f = fopen(new_filename, "w"); if (f) { fwrite(info->data, 1, info->size, f); fclose(f); } } void info_file_destroy(InfoFile *info) { free(info->data); free(info->preamble); free(info->indirect_table); free(info->tag_table); free(info->local_variables); for (int i = 0; i < info->node_count; i++) { free(info->regular_nodes[i]); } free(info->regular_nodes); free(info->menu); free(info->image); free(info->printindex); free(info->cross_reference); free(info); } // Example usage // int main() { // InfoFile *info = info_file_create("example.info"); // info_file_decode(info); // info_file_print_properties(info); // info_file_write(info, "new.info"); // info_file_destroy(info); // return 0; // } // ===== end task-310 .INFO ===== // ===== task-311 .INI [C++] ===== #include #include #include #include #include #include #include #include class IniHandler { private: std::string filepath; std::map globals; std::map> sections; std::vector comments; std::map metadata; public: IniHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath); if (!file.is_open()) { throw std::runtime_error("File " + filepath + " not found."); } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); parse(content); getMetadata(); } private: void parse(const std::string& content) { std::istringstream iss(content); std::string line; std::string currentSection = "globals"; std::regex sectionRegex(R"(^\[(.*)\]$)"); std::regex kvRegex(R"(^([^=|:]+)[=|:](.*)$)"); std::smatch match; while (std::getline(iss, line)) { line = std::regex_replace(line, std::regex("^ +| +$|( )+"), "$1"); // trim if (line.empty() || line[0] == ';' || line[0] == '#') { if (!line.empty()) comments.push_back(line); continue; } if (std::regex_match(line, match, sectionRegex)) { currentSection = match[1].str(); // trim currentSection currentSection.erase(0, currentSection.find_first_not_of(" \t")); currentSection.erase(currentSection.find_last_not_of(" \t") + 1); if (sections.find(currentSection) == sections.end()) { sections[currentSection] = {}; } continue; } if (std::regex_match(line, match, kvRegex)) { std::string key = match[1].str(); std::string value = match[2].str(); // trim key and value key.erase(0, key.find_first_not_of(" \t")); key.erase(key.find_last_not_of(" \t") + 1); value.erase(0, value.find_first_not_of(" \t")); value.erase(value.find_last_not_of(" \t") + 1); if (currentSection == "globals") { globals[key] = value; } else { sections[currentSection][key] = value; } } } } void getMetadata() { struct stat statbuf; if (stat(filepath.c_str(), &statbuf) == 0) { metadata["name"] = filepath.substr(filepath.find_last_of("/\\") + 1); metadata["size"] = std::to_string(statbuf.st_size); metadata["created"] = std::ctime(&statbuf.st_ctime); metadata["modified"] = std::ctime(&statbuf.st_mtime); metadata["accessed"] = std::ctime(&statbuf.st_atime); metadata["mode"] = std::to_string(statbuf.st_mode); } } public: void printProperties() { std::cout << "File Metadata:" << std::endl; for (const auto& [k, v] : metadata) { std::cout << "- " << k << ": " << v; } std::cout << "\nGlobals:" << std::endl; for (const auto& [k, v] : globals) { std::cout << k << " = " << v << std::endl; } std::cout << "\nSections:" << std::endl; for (const auto& [section, props] : sections) { std::cout << "[" << section << "]" << std::endl; for (const auto& [k, v] : props) { std::cout << k << " = " << v << std::endl; } } std::cout << "\nComments:" << std::endl; for (const auto& comment : comments) { std::cout << comment << std::endl; } } void write(const std::string& newFilepath = "") { std::string outPath = newFilepath.empty() ? filepath : newFilepath; std::ofstream out(outPath); if (!out.is_open()) { throw std::runtime_error("Cannot write to " + outPath); } // Write globals for (const auto& [k, v] : globals) { out << k << " = " << v << "\n"; } // Write sections for (const auto& [section, props] : sections) { out << "\n[" << section << "]\n"; for (const auto& [k, v] : props) { out << k << " = " << v << "\n"; } } // Append comments if (!comments.empty()) { out << "\n; Comments:\n"; for (const auto& comment : comments) { out << comment << "\n"; } } out.close(); } }; // Example usage: // int main() { // try { // IniHandler handler("sample.ini"); // handler.read(); // handler.printProperties(); // handler.write("output.ini"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-311 .INI ===== // ===== task-315 .IQBLOCKS [C] ===== #include #include #include typedef struct { char *filepath; char *data; // Raw JSON string } IQBlocksHandler; IQBlocksHandler* createIQBlocksHandler(const char *filepath) { IQBlocksHandler *handler = malloc(sizeof(IQBlocksHandler)); handler->filepath = strdup(filepath); handler->data = NULL; return handler; } void readIQBlocks(IQBlocksHandler *handler) { FILE *fp = fopen(handler->filepath, "r"); if (fp == NULL) { perror("File not found"); return; } fseek(fp, 0, SEEK_END); long size = ftell(fp); fseek(fp, 0, SEEK_SET); handler->data = malloc(size + 1); fread(handler->data, 1, size, fp); handler->data[size] = '\0'; fclose(fp); } void printProperties(IQBlocksHandler *handler) { if (handler->data == NULL) { readIQBlocks(handler); } printf("Properties from .IQBLOCKS file (simplified parse):\n"); // Simple parse: find top-level keys (assumes well-formed JSON) char *ptr = handler->data; while ((ptr = strstr(ptr, "\"")) != NULL) { ptr++; // Skip opening quote char *end = strstr(ptr, "\""); if (end) { *end = '\0'; printf("%s: (value type and example truncated)\n", ptr); ptr = end + 1; // Skip to value, but for simplicity, just print keys } else { break; } } } void writeIQBlocks(IQBlocksHandler *handler, const char *newData) { FILE *fp = fopen(handler->filepath, "w"); if (fp == NULL) { perror("Cannot write file"); return; } fprintf(fp, "%s", newData ? newData : handler->data); fclose(fp); printf("File written to %s\n", handler->filepath); } void destroyIQBlocksHandler(IQBlocksHandler *handler) { free(handler->filepath); free(handler->data); free(handler); } // Example usage: // int main() { // IQBlocksHandler *handler = createIQBlocksHandler("example.iqblocks"); // readIQBlocks(handler); // printProperties(handler); // writeIQBlocks(handler, "{\"meta\": \"new data\"}"); // destroyIQBlocksHandler(handler); // return 0; // } // ===== end task-315 .IQBLOCKS ===== // ===== task-316 .IRX [C] ===== #include #include #include #include typedef struct { uint32_t module; uint32_t start; uint32_t heap; uint32_t text_size; uint32_t data_size; uint32_t bss_size; uint32_t version; char name[8]; } IRXProperties; typedef struct { char *filepath; IRXProperties props; } IRXHandler; IRXHandler* createIRXHandler(const char *filepath) { IRXHandler *handler = malloc(sizeof(IRXHandler)); handler->filepath = strdup(filepath); return handler; } void readIRX(IRXHandler *handler) { FILE *f = fopen(handler->filepath, "rb"); if (!f) { perror("Cannot open file"); exit(1); } fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *buffer = malloc(size); fread(buffer, 1, size, f); fclose(f); // Parse ELF header (little-endian) if (*(uint32_t*)buffer != 0x464C457F) { fprintf(stderr, "Not a valid ELF file\n"); free(buffer); exit(1); } uint32_t shoff = *(uint32_t*)(buffer + 32); uint16_t shentsize = *(uint16_t*)(buffer + 46); uint16_t shnum = *(uint16_t*)(buffer + 48); uint16_t shstrndx = *(uint16_t*)(buffer + 50); uint32_t iopmodOffset = 0; for (uint16_t i = 0; i < shnum; i++) { uint32_t pos = shoff + i * shentsize; uint32_t sh_name = *(uint32_t*)(buffer + pos); uint32_t sh_type = *(uint32_t*)(buffer + pos + 4); uint32_t sh_offset = *(uint32_t*)(buffer + pos + 12); uint32_t strPos = shoff + shstrndx * shentsize + 12; uint32_t strTable = *(uint32_t*)(buffer + strPos); char *nameStr = (char*)(buffer + strTable + sh_name); if (strcmp(nameStr, ".iopmod") == 0 || sh_type == 0x70000080) { iopmodOffset = sh_offset; break; } } if (iopmodOffset == 0) { fprintf(stderr, "No .iopmod section found\n"); free(buffer); exit(1); } memcpy(&handler->props, buffer + iopmodOffset, sizeof(IRXProperties)); free(buffer); } void printIRXProperties(IRXHandler *handler) { printf("module: %u\n", handler->props.module); printf("start: %u\n", handler->props.start); printf("heap: %u\n", handler->props.heap); printf("text_size: %u\n", handler->props.text_size); printf("data_size: %u\n", handler->props.data_size); printf("bss_size: %u\n", handler->props.bss_size); printf("version: %u\n", handler->props.version); printf("name: %.8s\n", handler->props.name); } void writeIRX(IRXHandler *handler, IRXProperties newProps) { // Similar to read, load buffer, update at iopmodOffset, write back // Omitted full code for brevity; use fwrite printf("Write implemented by updating buffer at iopmodOffset and saving file\n"); } void destroyIRXHandler(IRXHandler *handler) { free(handler->filepath); free(handler); } // Example: // int main() { // IRXHandler *handler = createIRXHandler("example.irx"); // readIRX(handler); // printIRXProperties(handler); // destroyIRXHandler(handler); // return 0; // } // ===== end task-316 .IRX ===== // ===== task-317 .ISO [C++] ===== #include #include #include #include #include class ISOHandler { private: std::string filepath; const int sector_size = 2048; const long pvd_offset = 16 * sector_size; // 32768 uint8_t pvd_data[2048]; std::string get_string(long offset, int length) { std::string str(reinterpret_cast(pvd_data + offset), length); return str; } std::string get_date(long offset) { std::string date_str = get_string(offset, 16); int8_t gmt_offset_byte = static_cast(pvd_data[offset + 16]); int gmt_offset = gmt_offset_byte * 15; std::stringstream ss; ss << date_str.substr(0,4) << "-" << date_str.substr(4,2) << "-" << date_str.substr(6,2) << " " << date_str.substr(8,2) << ":" << date_str.substr(10,2) << ":" << date_str.substr(12,2) << "." << date_str.substr(14,2) << " GMT" << (gmt_offset >= 0 ? "+" : "") << gmt_offset; return ss.str(); } uint32_t get_uint32_le(long offset) { return *reinterpret_cast(pvd_data + offset); } uint32_t get_uint32_be(long offset) { uint32_t val; memcpy(&val, pvd_data + offset, 4); return __builtin_bswap32(val); } uint16_t get_uint16_le(long offset) { return *reinterpret_cast(pvd_data + offset); } public: ISOHandler(const std::string& fp) : filepath(fp) {} void read_properties() { std::ifstream file(filepath, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file"); } file.seekg(pvd_offset); file.read(reinterpret_cast(pvd_data), sector_size); file.close(); // Validate uint8_t type = pvd_data[0]; std::string id = get_string(1, 5); if (type != 1 || id != "CD001") { throw std::runtime_error("Invalid ISO file"); } } void print_properties() { read_properties(); // Ensure read std::cout << "ISO Properties:" << std::endl; std::cout << "System Identifier: " << get_string(8, 32) << std::endl; std::cout << "Volume Identifier: " << get_string(40, 32) << std::endl; std::cout << "Volume Space Size: " << get_uint32_le(80) << std::endl; std::cout << "Volume Set Size: " << get_uint16_le(120) << std::endl; std::cout << "Volume Sequence Number: " << get_uint16_le(124) << std::endl; std::cout << "Logical Block Size: " << get_uint16_le(128) << std::endl; std::cout << "Path Table Size: " << get_uint32_le(132) << std::endl; std::cout << "Location of Type-L Path Table: " << get_uint32_le(140) << std::endl; std::cout << "Location of Optional Type-L Path Table: " << get_uint32_le(144) << std::endl; std::cout << "Location of Type-M Path Table: " << get_uint32_be(148) << std::endl; std::cout << "Location of Optional Type-M Path Table: " << get_uint32_be(152) << std::endl; std::cout << "Volume Set Identifier: " << get_string(190, 128) << std::endl; std::cout << "Publisher Identifier: " << get_string(318, 128) << std::endl; std::cout << "Data Preparer Identifier: " << get_string(446, 128) << std::endl; std::cout << "Application Identifier: " << get_string(574, 128) << std::endl; std::cout << "Copyright File Identifier: " << get_string(702, 37) << std::endl; std::cout << "Abstract File Identifier: " << get_string(739, 37) << std::endl; std::cout << "Bibliographic File Identifier: " << get_string(776, 37) << std::endl; std::cout << "Volume Creation Date and Time: " << get_date(813) << std::endl; std::cout << "Volume Modification Date and Time: " << get_date(830) << std::endl; std::cout << "Volume Expiration Date and Time: " << get_date(847) << std::endl; std::cout << "Volume Effective Date and Time: " << get_date(864) << std::endl; std::cout << "File Structure Version: " << static_cast(pvd_data[881]) << std::endl; } void write_property(const std::string& key, const std::string& new_value) { read_properties(); // Ensure read if (key == "Volume Identifier") { std::string padded = new_value; padded.resize(32, ' '); memcpy(pvd_data + 40, padded.c_str(), 32); } // Add similar for others... std::fstream file(filepath, std::ios::in | std::ios::out | std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file for writing"); } file.seekp(pvd_offset); file.write(reinterpret_cast(pvd_data), sector_size); file.close(); std::cout << "Updated " << key << " to " << new_value << std::endl; } }; // Example usage: // int main() { // ISOHandler handler("example.iso"); // handler.print_properties(); // handler.write_property("Volume Identifier", "NewVolumeName"); // return 0; // } // ===== end task-317 .ISO ===== // ===== task-318 .IT [C++] ===== #include #include #include #include #include #include using namespace std; class ITFile { private: string filename; map properties; // Using string for simplicity in printing public: ITFile(const string& fn) : filename(fn) { read(); } void read() { ifstream file(filename, ios::binary | ios::ate); if (!file) { throw runtime_error("Cannot open file"); } streamsize size = file.tellg(); file.seekg(0, ios::beg); vector buffer(size); if (!file.read(buffer.data(), size)) { throw runtime_error("Cannot read file"); } // Magic string magic(buffer.begin(), buffer.begin() + 4); if (magic != "IMPM") { throw runtime_error("Not a valid .IT file"); } properties["Magic"] = magic; // Song Name string songName(buffer.begin() + 4, buffer.begin() + 30); size_t nullPos = songName.find('\0'); if (nullPos != string::npos) songName = songName.substr(0, nullPos); properties["Song Name"] = songName; // Pattern Highlight unsigned char rowsBeat = static_cast(buffer[30]); unsigned char rowsMeasure = static_cast(buffer[31]); properties["Pattern Highlight"] = "Rows per beat: " + to_string(rowsBeat) + ", Rows per measure: " + to_string(rowsMeasure); // Order Number uint16_t ordnum = *reinterpret_cast(&buffer[32]); properties["Order Number"] = to_string(ordnum); // Instrument Number uint16_t insnum = *reinterpret_cast(&buffer[34]); properties["Instrument Number"] = to_string(insnum); // Sample Number uint16_t smpnum = *reinterpret_cast(&buffer[36]); properties["Sample Number"] = to_string(smpnum); // Pattern Number uint16_t patnum = *reinterpret_cast(&buffer[38]); properties["Pattern Number"] = to_string(patnum); // Created with Tracker uint16_t cwtv = *reinterpret_cast(&buffer[40]); stringstream ss; ss << "0x" << hex << cwtv; properties["Created with Tracker"] = ss.str(); // Compatible with Tracker uint16_t cmwt = *reinterpret_cast(&buffer[42]); ss.str(""); ss << "0x" << hex << cmwt; properties["Compatible with Tracker"] = ss.str(); // Flags uint16_t flags = *reinterpret_cast(&buffer[44]); ss.str(""); ss << "0x" << hex << flags; properties["Flags"] = ss.str(); // Special uint16_t special = *reinterpret_cast(&buffer[46]); ss.str(""); ss << "0x" << hex << special; properties["Special"] = ss.str(); // Global Volume properties["Global Volume"] = to_string(static_cast(buffer[48])); // Mix Volume properties["Mix Volume"] = to_string(static_cast(buffer[49])); // Initial Speed properties["Initial Speed"] = to_string(static_cast(buffer[50])); // Initial Tempo properties["Initial Tempo"] = to_string(static_cast(buffer[51])); // Pan Separation properties["Pan Separation"] = to_string(static_cast(buffer[52])); // Pitch Wheel Depth properties["Pitch Wheel Depth"] = to_string(static_cast(buffer[53])); // Message Length uint16_t msgLen = *reinterpret_cast(&buffer[54]); properties["Message Length"] = to_string(msgLen); // Message Offset uint32_t msgOff = *reinterpret_cast(&buffer[56]); properties["Message Offset"] = to_string(msgOff); // Reserved uint32_t reserved = *reinterpret_cast(&buffer[60]); ss.str(""); ss << "0x" << hex << reserved; properties["Reserved"] = ss.str(); // Initial Channel Pan ss.str(""); ss << "["; for (int i = 64; i < 128; i++) { ss << static_cast(static_cast(buffer[i])) << (i < 127 ? ", " : ""); } ss << "]"; properties["Initial Channel Pan"] = ss.str(); // Initial Channel Volume ss.str(""); ss << "["; for (int i = 128; i < 192; i++) { ss << static_cast(static_cast(buffer[i])) << (i < 191 ? ", " : ""); } ss << "]"; properties["Initial Channel Volume"] = ss.str(); // Orders ss.str(""); ss << "["; for (int i = 0; i < ordnum; i++) { ss << static_cast(static_cast(buffer[192 + i])) << (i < ordnum - 1 ? ", " : ""); } ss << "]"; properties["Orders"] = ss.str(); // Instrument Offsets int insStart = 192 + ordnum; ss.str(""); ss << "["; for (int i = 0; i < insnum; i++) { uint32_t offset = *reinterpret_cast(&buffer[insStart + i * 4]); ss << offset << (i < insnum - 1 ? ", " : ""); } ss << "]"; properties["Instrument Offsets"] = ss.str(); // Sample Header Offsets int smpStart = insStart + insnum * 4; ss.str(""); ss << "["; for (int i = 0; i < smpnum; i++) { uint32_t offset = *reinterpret_cast(&buffer[smpStart + i * 4]); ss << offset << (i < smpnum - 1 ? ", " : ""); } ss << "]"; properties["Sample Header Offsets"] = ss.str(); // Pattern Offsets int patStart = smpStart + smpnum * 4; ss.str(""); ss << "["; for (int i = 0; i < patnum; i++) { uint32_t offset = *reinterpret_cast(&buffer[patStart + i * 4]); ss << offset << (i < patnum - 1 ? ", " : ""); } ss << "]"; properties["Pattern Offsets"] = ss.str(); // Edit History if Special bit 1 set if (special & 2) { int editStart = patStart + patnum * 4; uint16_t editNum = *reinterpret_cast(&buffer[editStart]); properties["Edit History Number"] = to_string(editNum); ss.str(""); for (int i = 0; i < editNum; i++) { int off = editStart + 2 + i * 8; uint16_t fatDate = *reinterpret_cast(&buffer[off]); uint16_t fatTime = *reinterpret_cast(&buffer[off + 2]); uint32_t runtime = *reinterpret_cast(&buffer[off + 4]); ss << "Fat Date: " << fatDate << ", Fat Time: " << fatTime << ", Runtime: " << runtime << "\n"; } properties["Edit Histories"] = ss.str(); } } void printProperties() { for (const auto& prop : properties) { cout << prop.first << ": " << prop.second << endl; } } void write(const string& outputFilename) { ofstream file(outputFilename, ios::binary); if (!file) { throw runtime_error("Cannot open output file"); } // Magic file.write("IMPM", 4); // Song Name string songName = properties["Song Name"]; songName.resize(26, '\0'); file.write(songName.c_str(), 26); // Pattern Highlight string ph = properties["Pattern Highlight"]; unsigned char rowsBeat = stoi(ph.substr(ph.find(": ") + 2, ph.find(",") - ph.find(": ") - 2)); unsigned char rowsMeasure = stoi(ph.substr(ph.rfind(": ") + 2)); file.put(rowsBeat); file.put(rowsMeasure); // Order Number uint16_t ordnum = stoi(properties["Order Number"]); file.write(reinterpret_cast(&ordnum), sizeof(uint16_t)); // Instrument Number uint16_t insnum = stoi(properties["Instrument Number"]); file.write(reinterpret_cast(&insnum), sizeof(uint16_t)); // Sample Number uint16_t smpnum = stoi(properties["Sample Number"]); file.write(reinterpret_cast(&smpnum), sizeof(uint16_t)); // Pattern Number uint16_t patnum = stoi(properties["Pattern Number"]); file.write(reinterpret_cast(&patnum), sizeof(uint16_t)); // Created with Tracker uint16_t cwtv = static_cast(strtoul(properties["Created with Tracker"].c_str(), nullptr, 0)); file.write(reinterpret_cast(&cwtv), sizeof(uint16_t)); // Compatible with Tracker uint16_t cmwt = static_cast(strtoul(properties["Compatible with Tracker"].c_str(), nullptr, 0)); file.write(reinterpret_cast(&cmwt), sizeof(uint16_t)); // Flags uint16_t flags = static_cast(strtoul(properties["Flags"].c_str(), nullptr, 0)); file.write(reinterpret_cast(&flags), sizeof(uint16_t)); // Special uint16_t special = static_cast(strtoul(properties["Special"].c_str(), nullptr, 0)); file.write(reinterpret_cast(&special), sizeof(uint16_t)); // Global Volume unsigned char gv = static_cast(stoi(properties["Global Volume"])); file.put(gv); // Mix Volume unsigned char mv = static_cast(stoi(properties["Mix Volume"])); file.put(mv); // Initial Speed unsigned char is = static_cast(stoi(properties["Initial Speed"])); file.put(is); // Initial Tempo unsigned char it = static_cast(stoi(properties["Initial Tempo"])); file.put(it); // Pan Separation unsigned char sep = static_cast(stoi(properties["Pan Separation"])); file.put(sep); // Pitch Wheel Depth unsigned char pwd = static_cast(stoi(properties["Pitch Wheel Depth"])); file.put(pwd); // Message Length uint16_t msgLen = static_cast(stoi(properties["Message Length"])); file.write(reinterpret_cast(&msgLen), sizeof(uint16_t)); // Message Offset uint32_t msgOff = static_cast(stol(properties["Message Offset"])); file.write(reinterpret_cast(&msgOff), sizeof(uint32_t)); // Reserved uint32_t reserved = static_cast(strtoul(properties["Reserved"].c_str(), nullptr, 0)); file.write(reinterpret_cast(&reserved), sizeof(uint32_t)); // Initial Channel Pan string chnpanStr = properties["Initial Channel Pan"]; chnpanStr = chnpanStr.substr(1, chnpanStr.length() - 2); stringstream chnpanSs(chnpanStr); string token; for (int i = 0; i < 64; i++) { getline(chnpanSs, token, ','); unsigned char val = static_cast(stoi(token)); file.put(val); } // Initial Channel Volume string chnvolStr = properties["Initial Channel Volume"]; chnvolStr = chnvolStr.substr(1, chnvolStr.length() - 2); stringstream chnvolSs(chnvolStr); for (int i = 0; i < 64; i++) { getline(chnvolSs, token, ','); unsigned char val = static_cast(stoi(token)); file.put(val); } // Orders string ordersStr = properties["Orders"]; ordersStr = ordersStr.substr(1, ordersStr.length() - 2); stringstream ordersSs(ordersStr); for (int i = 0; i < ordnum; i++) { getline(ordersSs, token, ','); unsigned char val = static_cast(stoi(token)); file.put(val); } // Instrument Offsets string insOffsetsStr = properties["Instrument Offsets"]; insOffsetsStr = insOffsetsStr.substr(1, insOffsetsStr.length() - 2); stringstream insSs(insOffsetsStr); for (int i = 0; i < insnum; i++) { getline(insSs, token, ','); uint32_t offset = static_cast(stol(token)); file.write(reinterpret_cast(&offset), sizeof(uint32_t)); } // Sample Header Offsets string smpOffsetsStr = properties["Sample Header Offsets"]; smpOffsetsStr = smpOffsetsStr.substr(1, smpOffsetsStr.length() - 2); stringstream smpSs(smpOffsetsStr); for (int i = 0; i < smpnum; i++) { getline(smpSs, token, ','); uint32_t offset = static_cast(stol(token)); file.write(reinterpret_cast(&offset), sizeof(uint32_t)); } // Pattern Offsets string patOffsetsStr = properties["Pattern Offsets"]; patOffsetsStr = patOffsetsStr.substr(1, patOffsetsStr.length() - 2); stringstream patSs(patOffsetsStr); for (int i = 0; i < patnum; i++) { getline(patSs, token, ','); uint32_t offset = static_cast(stol(token)); file.write(reinterpret_cast(&offset), sizeof(uint32_t)); } // Edit History if Special bit 1 set if (special & 2) { uint16_t editNum = static_cast(stoi(properties["Edit History Number"])); file.write(reinterpret_cast(&editNum), sizeof(uint16_t)); string editHist = properties["Edit Histories"]; stringstream editSs(editHist); string line; while (getline(editSs, line)) { if (line.empty()) continue; uint16_t fatDate = static_cast(stoi(line.substr(line.find(": ") + 2, line.find(",") - line.find(": ") - 2))); size_t pos1 = line.find(", Fat Time: ") + 12; uint16_t fatTime = static_cast(stoi(line.substr(pos1, line.rfind(",") - pos1))); size_t pos2 = line.rfind(": ") + 2; uint32_t runtime = static_cast(stol(line.substr(pos2))); file.write(reinterpret_cast(&fatDate), sizeof(uint16_t)); file.write(reinterpret_cast(&fatTime), sizeof(uint16_t)); file.write(reinterpret_cast(&runtime), sizeof(uint32_t)); } } // Note: Full write would append data sections. } }; // Example usage: // int main() { // try { // ITFile it("example.it"); // it.printProperties(); // it.write("output.it"); // } catch (const exception& e) { // cerr << e.what() << endl; // } // return 0; // } // ===== end task-318 .IT ===== // ===== task-319 .J2C [C] ===== #include #include #include typedef struct { char* filepath; // Use a map or array for properties; for simplicity, use struct fields uint16_t Rsiz; uint32_t Xsiz; // Add fields for all properties uint8_t* data; size_t data_size; } J2CFile; J2CFile* j2c_new(const char* filepath) { J2CFile* j2c = malloc(sizeof(J2CFile)); j2c->filepath = strdup(filepath); j2c->data = NULL; j2c->data_size = 0; // Initialize properties to 0 return j2c; } void j2c_read(J2CFile* j2c) { FILE* f = fopen(j2c->filepath, "rb"); if (f == NULL) return; fseek(f, 0, SEEK_END); j2c->data_size = ftell(f); fseek(f, 0, SEEK_SET); j2c->data = malloc(j2c->data_size); fread(j2c->data, 1, j2c->data_size, f); fclose(f); j2c_decode(j2c); } void j2c_decode(J2CFile* j2c) { if (j2c->data == NULL) return; size_t offset = 0; if ((j2c->data[offset] << 8 | j2c->data[offset+1]) != 0xFF4F) { printf("Not a valid J2C file\n"); return; } offset += 2; while (offset < j2c->data_size) { uint16_t marker = (j2c->data[offset] << 8 | j2c->data[offset+1]); offset += 2; if (marker == 0xFFD9) break; if (marker < 0xFF00) continue; uint16_t length = 0; if (marker != 0xFF4F && marker != 0xFF93 && marker != 0xFFD9 && marker != 0xFF92) { length = (j2c->data[offset] << 8 | j2c->data[offset+1]); offset += 2; } if (marker == 0xFF51) { // SIZ j2c->Rsiz = (j2c->data[offset] << 8 | j2c->data[offset+1]); // Parse other with byte shifts } // Add for other markers offset += length - 2; } } void j2c_print_properties(J2CFile* j2c) { printf("Rsiz: %u\n", j2c->Rsiz); // Print all } void j2c_write(J2CFile* j2c, const char* new_filepath) { if (j2c->data == NULL) return; FILE* f = fopen(new_filepath, "wb"); if (f == NULL) return; fwrite(j2c->data, 1, j2c->data_size, f); fclose(f); } void j2c_free(J2CFile* j2c) { free(j2c->data); free(j2c->filepath); free(j2c); } // Example // J2CFile* j2c = j2c_new("example.j2c"); // j2c_read(j2c); // j2c_print_properties(j2c); // j2c_write(j2c, "output.j2c"); // j2c_free(j2c); // ===== end task-319 .J2C ===== // ===== task-320 .J2K [C++] ===== #include #include #include #include #include #include class J2KHandler { private: std::string filename; std::vector data; size_t pos = 0; std::map> properties; // Simplified for print public: J2KHandler(const std::string& fn) : filename(fn) { read(); } void read() { std::ifstream file(filename, std::ios::binary); if (file) { data = std::vector((std::istreambuf_iterator(file)), std::istreambuf_iterator()); pos = 0; parse(); } } uint8_t readUint8() { return data[pos++]; } uint16_t readUint16() { uint16_t val = (readUint8() << 8) | readUint8(); return val; } uint32_t readUint32() { uint32_t val = (static_cast(readUint16()) << 16) | readUint16(); return val; } void parse() { if (readUint16() != 0xFF4F) { properties["error"]["message"] = "Invalid SOC marker"; return; } properties["SOC"]["present"] = "true"; while (pos < data.size()) { uint16_t marker = readUint16(); if (marker == 0xFFD9) { properties["EOC"]["present"] = "true"; break; } if ((marker & 0xFF00) != 0xFF00 || marker <= 0xFF4F) { properties["error"]["message"] = "Invalid marker at pos " + std::to_string(pos); break; } std::string segName = getMarkerName(marker); properties[segName] = std::map{}; if (hasLength(marker)) { uint16_t len = readUint16() - 2; size_t startPos = pos; parseSegment(marker, properties[segName]); pos = startPos + len; } else { properties[segName]["present"] = "true"; } } } bool hasLength(uint16_t marker) { return marker != 0xFF93 && marker != 0xFF92 && marker != 0xFFD9; } std::string getMarkerName(uint16_t marker) { switch (marker) { case 0xFF51: return "SIZ"; case 0xFF52: return "COD"; case 0xFF53: return "COC"; case 0xFF5C: return "QCD"; case 0xFF5D: return "QCC"; case 0xFF5E: return "RGN"; case 0xFF5F: return "POC"; case 0xFF55: return "TLM"; case 0xFF57: return "PLM"; case 0xFF58: return "PLT"; case 0xFF60: return "PPM"; case 0xFF61: return "PPT"; case 0xFF63: return "CRG"; case 0xFF64: return "COM"; case 0xFF90: return "SOT"; case 0xFF91: return "SOP"; case 0xFF93: return "SOD"; case 0xFF92: return "EPH"; default: return "Unknown (0x" + std::to_string(marker) + ")"; } } void parseSegment(uint16_t marker, std::map& props) { if (marker == 0xFF51) { // SIZ props["Rsiz"] = std::to_string(readUint16()); props["Xsiz"] = std::to_string(readUint32()); props["Ys iz"] = std::to_string(readUint32()); props["XOsiz"] = std::to_string(readUint32()); props["YOsiz"] = std::to_string(readUint32()); props["XTsiz"] = std::to_string(readUint32()); props["YTsiz"] = std::to_string(readUint32()); props["XTOsiz"] = std::to_string(readUint32()); props["YTOsiz"] = std::to_string(readUint32()); uint16_t csiz = readUint16(); props["Csiz"] = std::to_string(csiz); for (uint16_t i = 0; i < csiz; ++i) { uint8_t ssiz = readUint8(); std::string compKey = "component_" + std::to_string(i); props[compKey + "_Ssiz"] = std::to_string(ssiz); props[compKey + "_signed"] = (ssiz & 0x80) ? "true" : "false"; props[compKey + "_bit_depth"] = std::to_string((ssiz & 0x7F) + 1); props[compKey + "_XRsiz"] = std::to_string(readUint8()); props[compKey + "_YRsiz"] = std::to_string(readUint8()); } } else if (marker == 0xFF52) { // COD props["Scod"] = std::to_string(readUint8()); props["progression_order"] = std::to_string(readUint8()); props["num_layers"] = std::to_string(readUint16()); props["mct"] = std::to_string(readUint8()); uint8_t numDecomp = readUint8(); props["num_decomp"] = std::to_string(numDecomp); props["cb_width_exp"] = std::to_string(readUint8() + 2); props["cb_height_exp"] = std::to_string(readUint8() + 2); props["cb_style"] = std::to_string(readUint8()); props["transformation"] = std::to_string(readUint8()); for (uint8_t i = 0; i < numDecomp + 1; ++i) { props["precinct_size_" + std::to_string(i)] = std::to_string(readUint8()); } } else if (marker == 0xFF5C) { // QCD uint8_t sqcd = readUint8(); props["Sqcd"] = std::to_string(sqcd); uint8_t quantType = sqcd & 0x1F; props["quant_type"] = std::to_string(quantType); props["guard_bits"] = std::to_string(sqcd >> 5); uint8_t numDecomp = 0; // Assume from COD if available // For simplicity, assume known numDecomp or skip detailed props["SPqcd"] = "Parsed (extend for details)"; } // Add similar for other markers else { props["raw"] = "Unhandled segment"; } } void printProperties() { for (const auto& seg : properties) { std::cout << seg.first << ":" << std::endl; for (const auto& prop : seg.second) { std::cout << " " << prop.first << ": " << prop.second << std::endl; } } } void write(const std::string& outputFilename) { std::ofstream file(outputFilename, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); } }; // Example usage: // int main() { // J2KHandler handler("sample.j2k"); // handler.printProperties(); // handler.write("output.j2k"); // return 0; // } // ===== end task-320 .J2K ===== // ===== task-321 .JAR [C] ===== #include #include #include #include typedef struct { char* filename; // Properties as array of strings for simplicity char* properties[9][2]; // key-value pairs } JarParser; void init_jar_parser(JarParser* parser, const char* filename) { parser->filename = strdup(filename); for (int i = 0; i < 9; i++) { parser->properties[i][0] = NULL; parser->properties[i][1] = NULL; } } void free_jar_parser(JarParser* parser) { free(parser->filename); for (int i = 0; i < 9; i++) { free(parser->properties[i][0]); free(parser->properties[i][1]); } } int read_properties(JarParser* parser) { FILE* f = fopen(parser->filename, "rb"); if (!f) return -1; fseek(f, 0, SEEK_END); long size = ftell(f); uint8_t* data = malloc(size); fseek(f, 0, SEEK_SET); fread(data, 1, size, f); fclose(f); long pos = size - 22; while (pos >= 0) { uint32_t sig; memcpy(&sig, data + pos, 4); if (sig == 0x06054b50) { break; } pos--; } if (pos < 0) { free(data); return -1; } // Extract fields uint16_t this_disk, cd_start_disk, entries_this_disk, total_entries, comment_len; uint32_t cd_size, cd_offset; memcpy(&this_disk, data + pos + 4, 2); memcpy(&cd_start_disk, data + pos + 6, 2); memcpy(&entries_this_disk, data + pos + 8, 2); memcpy(&total_entries, data + pos + 10, 2); memcpy(&cd_size, data + pos + 12, 4); memcpy(&cd_offset, data + pos + 16, 4); memcpy(&comment_len, data + pos + 20, 2); char* comment = malloc(comment_len + 1); memcpy(comment, data + pos + 22, comment_len); comment[comment_len] = '\0'; // Store as strings char buf[32]; parser->properties[0][0] = strdup("End of Central Directory Signature"); parser->properties[0][1] = strdup("0x06054b50"); parser->properties[1][0] = strdup("Number of this disk"); sprintf(buf, "%u", this_disk); parser->properties[1][1] = strdup(buf); parser->properties[2][0] = strdup("Number of the disk with the start of the central directory"); sprintf(buf, "%u", cd_start_disk); parser->properties[2][1] = strdup(buf); parser->properties[3][0] = strdup("Total number of entries in the central directory on this disk"); sprintf(buf, "%u", entries_this_disk); parser->properties[3][1] = strdup(buf); parser->properties[4][0] = strdup("Total number of entries in the central directory"); sprintf(buf, "%u", total_entries); parser->properties[4][1] = strdup(buf); parser->properties[5][0] = strdup("Size of the central directory"); sprintf(buf, "%u", cd_size); parser->properties[5][1] = strdup(buf); parser->properties[6][0] = strdup("Offset of start of central directory"); sprintf(buf, "%u", cd_offset); parser->properties[6][1] = strdup(buf); parser->properties[7][0] = strdup("ZIP file comment length"); sprintf(buf, "%u", comment_len); parser->properties[7][1] = strdup(buf); parser->properties[8][0] = strdup("ZIP file comment"); parser->properties[8][1] = strdup(comment); free(comment); free(data); return 0; } void print_properties(JarParser* parser) { if (!parser->properties[0][0]) { if (read_properties(parser) != 0) { printf("Error reading properties.\n"); return; } } for (int i = 0; i < 9; i++) { if (parser->properties[i][0]) { printf("%s: %s\n", parser->properties[i][0], parser->properties[i][1]); } } } int write_comment(JarParser* parser, const char* new_comment) { FILE* f = fopen(parser->filename, "rb+"); if (!f) return -1; fseek(f, 0, SEEK_END); long size = ftell(f); uint8_t* data = malloc(size); fseek(f, 0, SEEK_SET); fread(data, 1, size, f); long pos = size - 22; while (pos >= 0) { uint32_t sig; memcpy(&sig, data + pos, 4); if (sig == 0x06054b50) { break; } pos--; } if (pos < 0) { free(data); fclose(f); return -1; } uint16_t old_comment_len; memcpy(&old_comment_len, data + pos + 20, 2); size_t new_comment_len = strlen(new_comment); long new_size = pos + 22 + new_comment_len; uint8_t* new_data = malloc(new_size); memcpy(new_data, data, pos + 22); memcpy(new_data + pos + 22, new_comment, new_comment_len); memcpy(new_data + pos + 20, &new_comment_len, 2); // Update length fseek(f, 0, SEEK_SET); fwrite(new_data, 1, new_size, f); if (new_size < size) { ftruncate(fileno(f), new_size); } fclose(f); free(data); free(new_data); return 0; } // Example usage: // int main() { // JarParser parser; // init_jar_parser(&parser, "example.jar"); // print_properties(&parser); // write_comment(&parser, "New comment"); // free_jar_parser(&parser); // return 0; // } // ===== end task-321 .JAR ===== // ===== task-322 .JAV [C++] ===== #include #include #include #include #include #include #include #include class JavFile { private: std::string filename; std::string filePath; public: JavFile(const std::string& fname) : filename(fname) { char buf[PATH_MAX]; realpath(fname.c_str(), buf); filePath = std::string(buf); } void getProperties(struct stat& st) { if (stat(filename.c_str(), &st) != 0) { throw std::runtime_error("Failed to get file stats"); } } void printProperties() { struct stat st; getProperties(st); struct passwd* pw = getpwuid(st.st_uid); struct group* gr = getgrgid(st.st_gid); std::cout << "File name: " << filename.substr(filename.find_last_of("/\\") + 1) << std::endl; std::cout << "File path: " << filePath << std::endl; std::cout << "File size (in bytes): " << st.st_size << std::endl; std::cout << "Creation time: " << std::ctime(&st.st_ctime); std::cout << "Last modification time: " << std::ctime(&st.st_mtime); std::cout << "Last access time: " << std::ctime(&st.st_atime); std::cout << "File permissions: " << std::oct << (st.st_mode & 0777) << std::endl; std::cout << "Owner: " << (pw ? pw->pw_name : "N/A") << std::endl; std::cout << "Group: " << (gr ? gr->gr_name : "N/A") << std::endl; } std::string read() { // Read content (no decode needed, as it's text) std::ifstream file(filename); if (!file) { throw std::runtime_error("Failed to open file for reading"); } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); return content; } void write(const std::string& content) { // Write content to the file std::ofstream file(filename); if (!file) { throw std::runtime_error("Failed to open file for writing"); } file << content; } }; // Example usage: // int main() { // try { // JavFile jav("example.jav"); // jav.printProperties(); // std::string content = jav.read(); // jav.write("New content"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-322 .JAV ===== // ===== task-313 .IPT [C] ===== #include #include #include #include #include typedef struct { char* data; size_t size; // Map for properties, using simple linked list for simplicity struct PropNode* properties; } IptFile; struct PropNode { char* key; char* value; struct PropNode* next; }; uint8_t magic[] = {0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1}; IptFile* ipt_open(const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); char* data = malloc(size); fread(data, 1, size, f); fclose(f); IptFile* ipt = malloc(sizeof(IptFile)); ipt->data = data; ipt->size = size; ipt->properties = NULL; // Check magic if (memcmp(data, magic, 8) != 0) { free(ipt); free(data); return NULL; } // Parsing similar to above, but simplified in C - omit full for brevity, assume print stub // Implement header, directories, streams as in Python/JS // For demonstration, add dummy properties struct PropNode* node = malloc(sizeof(struct PropNode)); node->key = strdup("App Name"); node->value = strdup("Autodesk Inventor"); node->next = NULL; ipt->properties = node; return ipt; } void ipt_print_properties(IptFile* ipt) { struct PropNode* node = ipt->properties; while (node) { printf("%s: %s\n", node->key, node->value); node = node->next; } } void ipt_write(IptFile* ipt, const char* filename) { FILE* f = fopen(filename, "wb"); fwrite(ipt->data, 1, ipt->size, f); fclose(f); } void ipt_close(IptFile* ipt) { // Free properties struct PropNode* node = ipt->properties; while (node) { struct PropNode* temp = node; node = node->next; free(temp->key); free(temp->value); free(temp); } free(ipt->data); free(ipt); } // Example // int main() { // IptFile* ipt = ipt_open("example.ipt"); // ipt_print_properties(ipt); // ipt_write(ipt, "modified.ipt"); // ipt_close(ipt); // return 0; // } // ===== end task-313 .IPT ===== // ===== task-314 .IPTRACE [C++] ===== #include #include #include #include #include struct Packet { double timestamp; uint32_t length; std::string direction; std::string if_type; uint16_t reserved; std::vector data; }; class IPTraceFile { private: std::string filename; std::string mode; std::ifstream inFile; std::ofstream outFile; double version = 2.0; uint8_t file_header[16]; std::vector packets; public: IPTraceFile(const std::string& fn, const std::string& m = "r") : filename(fn), mode(m) { if (mode == "r") { inFile.open(filename, std::ios::binary); } else { outFile.open(filename, std::ios::binary); } } ~IPTraceFile() { if (inFile.is_open()) inFile.close(); if (outFile.is_open()) outFile.close(); } void read() { if (mode != "r") return; inFile.read(reinterpret_cast(file_header), 16); while (true) { uint8_t pkt_header[16]; inFile.read(reinterpret_cast(pkt_header), 16); if (inFile.gcount() < 16) break; double timestamp; uint32_t length; uint8_t direction_byte; uint8_t if_type_byte; uint16_t reserved; memcpy(×tamp, pkt_header, 8); memcpy(&length, pkt_header + 8, 4); direction_byte = pkt_header[12]; if_type_byte = pkt_header[13]; memcpy(&reserved, pkt_header + 14, 2); std::vector data(length); inFile.read(reinterpret_cast(data.data()), length); if (inFile.gcount() < static_cast(length)) break; Packet pkt; pkt.timestamp = timestamp; pkt.length = length; pkt.direction = (direction_byte == 0) ? "Sent" : "Received"; pkt.if_type = "0x" + std::to_string(if_type_byte); pkt.reserved = reserved; pkt.data = data; packets.push_back(pkt); } } void printProperties() { std::cout << "Version: " << version << std::endl; std::cout << "File Header: "; for (int i = 0; i < 16; ++i) std::cout << static_cast(file_header[i]) << " "; std::cout << std::endl; std::cout << "Packet Count: " << packets.size() << std::endl; for (size_t i = 0; i < packets.size(); ++i) { auto& pkt = packets[i]; std::cout << "\nPacket " << (i + 1) << ":" << std::endl; std::cout << " Timestamp: " << pkt.timestamp << std::endl; std::cout << " Length: " << pkt.length << std::endl; std::cout << " Direction: " << pkt.direction << std::endl; std::cout << " Interface Type: " << pkt.if_type << std::endl; std::cout << " Reserved: " << pkt.reserved << std::endl; } } void write(const std::vector& new_packets) { if (mode != "w") return; uint8_t dummy_header[16] = {0}; outFile.write(reinterpret_cast(dummy_header), 16); for (const auto& pkt : new_packets) { uint8_t pkt_header[16]; memcpy(pkt_header, &pkt.timestamp, 8); memcpy(pkt_header + 8, &pkt.length, 4); pkt_header[12] = (pkt.direction == "Sent") ? 0 : 1; pkt_header[13] = static_cast(std::stoi(pkt.if_type.substr(2), nullptr, 16)); memcpy(pkt_header + 14, &pkt.reserved, 2); outFile.write(reinterpret_cast(pkt_header), 16); outFile.write(reinterpret_cast(pkt.data.data()), pkt.length); } } }; // Example usage: // IPTraceFile f("example.iptrace"); // f.read(); // f.printProperties(); // For write: IPTraceFile fw("new.iptrace", "w"); // std::vector pkts = {...}; // fw.write(pkts); // ===== end task-314 .IPTRACE ===== // ===== task-324 .JBIG [C] ===== #include #include #include #include #include // For big-endian conversion if needed, but assuming host is little-endian struct JBIGProperties { uint8_t dl; uint8_t d; uint8_t p; uint8_t reserved; uint32_t xd; uint32_t yd; uint32_t l0; uint8_t mx; uint8_t my; uint8_t order; uint8_t options; struct { uint8_t sm : 1; uint8_t ileave : 1; uint8_t seq : 1; uint8_t hitolo : 1; } order_bits; struct { uint8_t lrl two : 1; uint8_t dpon : 1; uint8_t tpbon : 1; uint8_t tpdon : 1; uint8_t dppriv : 1; uint8_t qopt : 1; } options_bits; }; struct JBIGHandler { char* filepath; uint8_t header[20]; uint8_t* data; size_t data_size; struct JBIGProperties properties; }; void jbig_handler_init(struct JBIGHandler* self, const char* filepath) { self->filepath = strdup(filepath); FILE* f = fopen(filepath, "rb"); if (f == NULL) { perror("fopen"); exit(1); } if (fread(self->header, 1, 20, f) < 20) { fprintf(stderr, "File too small for JBIG header\n"); exit(1); } fseek(f, 0, SEEK_END); size_t file_size = ftell(f); self->data_size = file_size - 20; self->data = malloc(self->data_size); fseek(f, 20, SEEK_SET); fread(self->data, 1, self->data_size, f); fclose(f); // Parse self->properties.dl = self->header[0]; self->properties.d = self->header[1]; self->properties.p = self->header[2]; self->properties.reserved = self->header[3]; self->properties.xd = be32toh(*(uint32_t*)(self->header + 4)); self->properties.yd = be32toh(*(uint32_t*)(self->header + 8)); self->properties.l0 = be32toh(*(uint32_t*)(self->header + 12)); self->properties.mx = self->header[16]; self->properties.my = self->header[17]; self->properties.order = self->header[18]; self->properties.options = self->header[19]; self->properties.order_bits.sm = self->properties.order & 0x01; self->properties.order_bits.ileave = self->properties.order & 0x02; self->properties.order_bits.seq = self->properties.order & 0x04; self->properties.order_bits.hitolo = self->properties.order & 0x08; self->properties.options_bits.lrl two = self->properties.options & 0x01; self->properties.options_bits.dpon = self->properties.options & 0x02; self->properties.options_bits.tpbon = self->properties.options & 0x04; self->properties.options_bits.tpdon = self->properties.options & 0x08; self->properties.options_bits.dppriv = self->properties.options & 0x10; self->properties.options_bits.qopt = self->properties.options & 0x20; } void jbig_handler_print_properties(const struct JBIGHandler* self) { printf("DL: %u\n", self->properties.dl); printf("D: %u\n", self->properties.d); printf("P: %u\n", self->properties.p); printf("Reserved: %u\n", self->properties.reserved); printf("XD: %u\n", self->properties.xd); printf("YD: %u\n", self->properties.yd); printf("L0: %u\n", self->properties.l0); printf("MX: %u\n", self->properties.mx); printf("MY: %u\n", self->properties.my); printf("ORDER: %u (SM: %u, ILEAVE: %u, SEQ: %u, HITOLO: %u)\n", self->properties.order, self->properties.order_bits.sm, self->properties.order_bits.ileave, self->properties.order_bits.seq, self->properties.order_bits.hitolo); printf("OPTIONS: %u (LRLTWO: %u, DPON: %u, TPBON: %u, TPDON: %u, DPPRIV: %u, QOPT: %u)\n", self->properties.options, self->properties.options_bits.lrl two, self->properties.options_bits.dpon, self->properties.options_bits.tpbon, self->properties.options_bits.tpdon, self->properties.options_bits.dppriv, self->properties.options_bits.qopt); } void jbig_handler_write(const struct JBIGHandler* self, const char* output_path) { FILE* f = fopen(output_path, "wb"); if (f == NULL) { perror("fopen"); exit(1); } fwrite(self->header, 1, 20, f); fwrite(self->data, 1, self->data_size, f); fclose(f); } void jbig_handler_destroy(struct JBIGHandler* self) { free(self->filepath); free(self->data); } int main(int argc, char** argv) { if (argc < 2) { fprintf(stderr, "Usage: %s input.jbig [output.jbig]\n", argv[0]); return 1; } struct JBIGHandler handler; jbig_handler_init(&handler, argv[1]); jbig_handler_print_properties(&handler); if (argc > 2) { jbig_handler_write(&handler, argv[2]); } jbig_handler_destroy(&handler); return 0; } // ===== end task-324 .JBIG ===== // ===== task-325 .JCM [C] ===== #include #include #include #define MAX_PROPS 100 #define MAX_KEY_LEN 64 #define MAX_VALUE_LEN 4096 typedef struct { char keys[MAX_PROPS][MAX_KEY_LEN]; char values[MAX_PROPS][MAX_VALUE_LEN]; int count; } JCMFile; void jcm_init(JCMFile *jcm) { jcm->count = 0; } void jcm_read(JCMFile *jcm, const char *filename) { FILE *fp = fopen(filename, "r"); if (!fp) { perror("Failed to open file"); return; } char line[8192]; char *current_key = NULL; char multi_line_value[MAX_VALUE_LEN] = ""; int value_len = 0; while (fgets(line, sizeof(line), fp)) { char *trimmed = strtok(line, "\r\n"); if (!trimmed) continue; if (strncmp(trimmed, "##", 2) == 0) { if (current_key) { multi_line_value[value_len] = '\0'; strcpy(jcm->values[jcm->count], multi_line_value); strcpy(jcm->keys[jcm->count++], current_key); } char *eq = strchr(trimmed, '='); if (eq) { *eq = '\0'; char *key = trimmed + 2; if (*key == '.') key++; while (*key == ' ') key++; current_key = key; char *value = eq + 1; while (*value == ' ') value++; strcpy(multi_line_value, value); value_len = strlen(value); } else { current_key = NULL; } } else if (current_key) { multi_line_value[value_len++] = '\n'; strcpy(multi_line_value + value_len, trimmed); value_len += strlen(trimmed); } } if (current_key) { multi_line_value[value_len] = '\0'; strcpy(jcm->values[jcm->count], multi_line_value); strcpy(jcm->keys[jcm->count++], current_key); } fclose(fp); } void jcm_decode(JCMFile *jcm) { // Basic decode: properties are parsed. Extend for ASDF decompression if needed. } void jcm_print_properties(JCMFile *jcm) { for (int i = 0; i < jcm->count; i++) { printf("%s: %s\n", jcm->keys[i], jcm->values[i]); } } void jcm_write(JCMFile *jcm, const char *filename) { FILE *fp = fopen(filename, "w"); if (!fp) { perror("Failed to open file"); return; } for (int i = 0; i < jcm->count; i++) { fprintf(fp, "##%s=%s\n", jcm->keys[i], jcm->values[i]); } fclose(fp); } // Example usage: // int main() { // JCMFile jcm; // jcm_init(&jcm); // jcm_read(&jcm, "example.jcm"); // jcm_print_properties(&jcm); // jcm_write(&jcm, "output.jcm"); // return 0; // } // ===== end task-325 .JCM ===== // ===== task-326 .JDX [C] ===== #include #include #include #include #define MAX_LABELS 100 #define MAX_LABEL_LEN 64 #define MAX_VALUE_LEN 1024 typedef struct { char labels[MAX_LABELS][MAX_LABEL_LEN]; char values[MAX_LABELS][MAX_VALUE_LEN]; int count; char *filepath; } JDXHandler; void init_handler(JDXHandler *handler, const char *filepath) { handler->count = 0; handler->filepath = strdup(filepath); if (filepath) { read_jdx(handler, filepath); } } void read_jdx(JDXHandler *handler, const char *filepath) { FILE *file = fopen(filepath, "r"); if (!file) { perror("Error opening file"); return; } handler->count = 0; char line[256]; char current_label[MAX_LABEL_LEN] = {0}; char value_builder[MAX_VALUE_LEN] = {0}; while (fgets(line, sizeof(line), file)) { char *trimmed = line; while (isspace(*trimmed)) trimmed++; if (strncmp(trimmed, "##", 2) == 0) { if (strlen(current_label) > 0) { strcpy(handler->values[handler->count], value_builder); handler->count++; } char *eq_pos = strchr(trimmed + 2, '='); if (eq_pos) { int label_len = eq_pos - (trimmed + 2); strncpy(current_label, trimmed + 2, label_len); current_label[label_len] = '\0'; // Normalize label: remove -, /, spaces char *p = current_label; while (*p) { if (*p == '-' || *p == '/' || *p == ' ') { memmove(p, p + 1, strlen(p)); } else { p++; } } strcpy(handler->labels[handler->count], current_label); strcpy(value_builder, eq_pos + 1); char *end = value_builder + strlen(value_builder) - 1; while (end > value_builder && isspace(*end)) *end-- = '\0'; } else { current_label[0] = '\0'; } } else if (strlen(current_label) > 0 && strlen(trimmed) > 0) { strcat(value_builder, "\n"); strcat(value_builder, trimmed); } } if (strlen(current_label) > 0) { strcpy(handler->values[handler->count], value_builder); handler->count++; } fclose(file); printf("Properties read from file:\n"); print_properties(handler); } void print_properties(const JDXHandler *handler) { for (int i = 0; i < handler->count; i++) { printf("%s: %s\n", handler->labels[i], handler->values[i]); } } void write_jdx(const JDXHandler *handler, const char *output_filepath) { if (handler->count == 0) { fprintf(stderr, "No properties to write.\n"); return; } FILE *file = fopen(output_filepath, "w"); if (!file) { perror("Error opening file for write"); return; } for (int i = 0; i < handler->count; i++) { fprintf(file, "##%s=%s\n", handler->labels[i], handler->values[i]); } fprintf(file, "##END=\n"); fclose(file); printf("File written to %s\n", output_filepath); } void free_handler(JDXHandler *handler) { free(handler->filepath); } // Example usage: // int main() { // JDXHandler handler; // init_handler(&handler, "example.jdx"); // write_jdx(&handler, "output.jdx"); // free_handler(&handler); // return 0; // } // ===== end task-326 .JDX ===== // ===== task-327 .JNLP [C] ===== #include #include #include #include typedef struct { char* filepath; xmlDocPtr doc; // Properties as maps or structs (simplified; use hashes or arrays for full) } JnlpHandler; void init_handler(JnlpHandler* handler, char* filepath) { handler->filepath = strdup(filepath); handler->doc = NULL; } int open_and_decode(JnlpHandler* handler) { if (strstr(handler->filepath, ".jnlp") == NULL) { printf("Invalid .JNLP file.\n"); return 1; } handler->doc = xmlReadFile(handler->filepath, NULL, 0); if (handler->doc == NULL) { printf("Error parsing XML.\n"); return 1; } // Extract properties (implement parsing similar to above, printing directly or storing) // For brevity: xmlNode* root = xmlDocGetRootElement(handler->doc); // if (strcmp((char*)root->name, "jnlp") == 0) { // printf("spec: %s\n", (char*)xmlGetProp(root, (xmlChar*)"spec")); // // Continue for all properties... // } return 0; } void print_properties(JnlpHandler* handler) { if (handler->doc == NULL) return; // Implement full traversal and print as in other languages printf("Properties:\n"); // Example: xmlNode* cur = xmlDocGetRootElement(handler->doc)->children; // while (cur) { ... } } void write(JnlpHandler* handler, char* new_filepath, /* modifications */) { // Apply mods if needed xmlSaveFormatFileEnc(new_filepath, handler->doc, "UTF-8", 1); } void free_handler(JnlpHandler* handler) { free(handler->filepath); xmlFreeDoc(handler->doc); } int main() { JnlpHandler handler; init_handler(&handler, "example.jnlp"); if (open_and_decode(&handler) == 0) { print_properties(&handler); write(&handler, "modified.jnlp", /* mods */); } free_handler(&handler); return 0; } // ===== end task-327 .JNLP ===== // ===== task-328 .JL [C] ===== #include #include #include #include #include #include #include #include typedef struct { char *filepath; char *content; } JLFileHandler; JLFileHandler* create_jl_handler(const char *filepath) { JLFileHandler *handler = malloc(sizeof(JLFileHandler)); handler->filepath = strdup(filepath); handler->content = NULL; return handler; } void destroy_jl_handler(JLFileHandler *handler) { if (handler->content) free(handler->content); free(handler->filepath); free(handler); } char* read_jl(JLFileHandler *handler) { // Read (decode) as text FILE *f = fopen(handler->filepath, "r"); if (!f) { perror("Failed to open file"); return NULL; } fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); handler->content = malloc(size + 1); fread(handler->content, 1, size, f); handler->content[size] = '\0'; fclose(f); return handler->content; } void write_jl(JLFileHandler *handler, const char *new_filepath, const char *content) { const char *write_content = content ? content : (handler->content ? handler->content : ""); FILE *f = fopen(new_filepath, "w"); if (!f) { perror("Failed to open file for writing"); return; } fprintf(f, "%s", write_content); fclose(f); } void print_properties_jl(JLFileHandler *handler) { struct stat stats; if (stat(handler->filepath, &stats) != 0) { perror("Failed to get file stats"); return; } printf("File name: %s\n", handler->filepath); printf("File size: %ld bytes\n", stats.st_size); printf("Creation time: %s", ctime(&stats.st_ctime)); printf("Modification time: %s", ctime(&stats.st_mtime)); printf("Access time: %s", ctime(&stats.st_atime)); printf("Permissions: %o\n", stats.st_mode & 0777); printf("Owner UID: %d\n", stats.st_uid); printf("Group GID: %d\n", stats.st_gid); printf("File type: %s\n", S_ISREG(stats.st_mode) ? "regular file" : "other"); } // Example usage: // int main() { // JLFileHandler *handler = create_jl_handler("example.jl"); // read_jl(handler); // print_properties_jl(handler); // write_jl(handler, "new_example.jl", "println(\"Hello, Julia!\")"); // destroy_jl_handler(handler); // return 0; // } // ===== end task-328 .JL ===== // ===== task-329 .JP2 [C] ===== #include #include #include #include #include typedef struct { char* filepath; uint8_t* data; size_t data_size; // Use a simple array for properties (key-value pairs) char* keys[100]; char* values[100]; int prop_count; } JP2Parser; void init_parser(JP2Parser* parser, const char* filepath) { parser->filepath = strdup(filepath); parser->data = NULL; parser->prop_count = 0; FILE* f = fopen(filepath, "rb"); if (!f) return; fseek(f, 0, SEEK_END); parser->data_size = ftell(f); fseek(f, 0, SEEK_SET); parser->data = malloc(parser->data_size); fread(parser->data, 1, parser->data_size, f); fclose(f); } uint32_t get_u32_be(uint8_t* buf) { return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]; } uint64_t get_u64_be(uint8_t* buf) { return ((uint64_t)buf[0] << 56) | ((uint64_t)buf[1] << 48) | ((uint64_t)buf[2] << 40) | ((uint64_t)buf[3] << 32) | ((uint64_t)buf[4] << 24) | ((uint64_t)buf[5] << 16) | ((uint64_t)buf[6] << 8) | buf[7]; } void add_prop(JP2Parser* parser, const char* key, const char* value) { parser->keys[parser->prop_count] = strdup(key); parser->values[parser->prop_count] = strdup(value); parser->prop_count++; } void decode(JP2Parser* parser, uint8_t* data, size_t size) { size_t offset = 0; while (offset < size) { uint64_t box_size = get_u32_be(data + offset); offset += 4; char type[5] = {0}; memcpy(type, data + offset, 4); offset += 4; size_t data_start = offset; if (box_size == 1) { box_size = get_u64_be(data + offset); offset += 8; data_start = offset; } else if (box_size == 0) { box_size = size - (data_start - 8); } size_t data_end = data_start + box_size - 8; char val_buf[256]; if (strcmp(type, "jP ") == 0) { sprintf(val_buf, "0x%X", get_u32_be(data + offset)); add_prop(parser, "Signature Value", val_buf); } else if (strcmp(type, "ftyp") == 0) { memcpy(val_buf, data + offset, 4); val_buf[4] = 0; add_prop(parser, "Brand", val_buf); sprintf(val_buf, "%u", get_u32_be(data + offset + 4)); add_prop(parser, "Minor Version", val_buf); // Compatibility list (simplified, first one) memcpy(val_buf, data + offset + 8, 4); val_buf[4] = 0; add_prop(parser, "Compatibility List", val_buf); } else if (strcmp(type, "jp2h") == 0 || strcmp(type, "res ") == 0) { // Recurse decode(parser, data + data_start, box_size - 8); } else if (strcmp(type, "ihdr") == 0) { sprintf(val_buf, "%u", get_u32_be(data + offset)); add_prop(parser, "Image Height", val_buf); sprintf(val_buf, "%u", get_u32_be(data + offset + 4)); add_prop(parser, "Image Width", val_buf); sprintf(val_buf, "%u", (data[offset + 8] << 8) | data[offset + 9]); add_prop(parser, "Number of Components", val_buf); sprintf(val_buf, "%u", data[offset + 10]); add_prop(parser, "Bits Per Component", val_buf); sprintf(val_buf, "%u", data[offset + 11]); add_prop(parser, "Compression Type", val_buf); sprintf(val_buf, "%u", data[offset + 12]); add_prop(parser, "Colorspace Unknown", val_buf); sprintf(val_buf, "%u", data[offset + 13]); add_prop(parser, "Intellectual Property Present", val_buf); } else if (strcmp(type, "colr") == 0) { sprintf(val_buf, "%u", data[offset]); add_prop(parser, "Color Method", val_buf); sprintf(val_buf, "%u", data[offset + 1]); add_prop(parser, "Color Precedence", val_buf); sprintf(val_buf, "%u", data[offset + 2]); add_prop(parser, "Color Approximation", val_buf); if (data[offset] == 1) { sprintf(val_buf, "%u", get_u32_be(data + offset + 3)); add_prop(parser, "Enumerated Colorspace", val_buf); } else if (data[offset] == 2 || data[offset] == 3) { sprintf(val_buf, "%llu", box_size - 11); add_prop(parser, "ICC Profile Length", val_buf); } } else if (strcmp(type, "resc") == 0 || strcmp(type, "resd") == 0) { const char* prefix = (strcmp(type, "resc") == 0) ? "Capture" : "Display"; uint16_t vrn = (data[offset] << 8) | data[offset+1]; uint16_t vrd = (data[offset+2] << 8) | data[offset+3]; uint16_t hrn = (data[offset+4] << 8) | data[offset+5]; uint16_t hrd = (data[offset+6] << 8) | data[offset+7]; int8_t vre = *(int8_t*)(data + offset + 8); int8_t hre = *(int8_t*)(data + offset + 9); char key[50]; sprintf(key, "%s Resolution Vertical", prefix); sprintf(val_buf, "%.6f", (vrn / (double)vrd) * pow(10, vre)); add_prop(parser, key, val_buf); sprintf(key, "%s Resolution Horizontal", prefix); sprintf(val_buf, "%.6f", (hrn / (double)hrd) * pow(10, hre)); add_prop(parser, key, val_buf); } else if (strcmp(type, "jp2c") == 0) { sprintf(val_buf, "%llu", box_size - 8); add_prop(parser, "Codestream Length", val_buf); } else if (strcmp(type, "xml ") == 0) { char* xml = malloc(box_size - 7); memcpy(xml, data + offset, box_size - 8); xml[box_size - 8] = 0; add_prop(parser, "XML Metadata", xml); free(xml); } // Add more offset = data_end; } } void print_properties(JP2Parser* parser) { for (int i = 0; i < parser->prop_count; i++) { printf("%s: %s\n", parser->keys[i], parser->values[i]); } } void write(JP2Parser* parser, const char* output_path) { if (parser->data) { FILE* f = fopen(output_path, "wb"); fwrite(parser->data, 1, parser->data_size, f); fclose(f); printf("File written to %s\n", output_path); } } void free_parser(JP2Parser* parser) { free(parser->data); free(parser->filepath); for (int i = 0; i < parser->prop_count; i++) { free(parser->keys[i]); free(parser->values[i]); } } int main() { JP2Parser parser; init_parser(&parser, "example.jp2"); decode(&parser, parser.data, parser.data_size); print_properties(&parser); write(&parser, "output.jp2"); free_parser(&parser); return 0; } // ===== end task-329 .JP2 ===== // ===== task-330 .JPE [C++] ===== #include #include #include #include #include #include class JPEParser { private: std::string filepath; std::vector data; std::map properties; public: JPEParser(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary); if (!file) { std::cout << "Cannot open file" << std::endl; return; } data = std::vector(std::istreambuf_iterator(file), {}); file.close(); decode(); } void decode() { if (data.size() < 4 || data[0] != 0xFF || data[1] != 0xD8) { std::cout << "Not a valid .JPE file" << std::endl; return; } size_t offset = 2; while (offset < data.size()) { unsigned short marker = (data[offset] << 8) | data[offset + 1]; offset += 2; if (marker == 0xFFE0) { // APP0 JFIF unsigned short length = (data[offset] << 8) | data[offset + 1]; offset += 2; std::string id = ""; for (int i = 0; i < 4; ++i) id += data[offset + i]; if (id != "JFIF") continue; properties["JFIF Identifier"] = id; offset += 5; // JFIF\0 unsigned char major = data[offset]; unsigned char minor = data[offset + 1]; properties["JFIF Version"] = std::to_string(major) + "." + std::to_string(minor); offset += 2; properties["Density Units"] = std::to_string(data[offset]); offset += 1; unsigned short xDensity = (data[offset] << 8) | data[offset + 1]; properties["Horizontal Pixel Density"] = std::to_string(xDensity); offset += 2; unsigned short yDensity = (data[offset] << 8) | data[offset + 1]; properties["Vertical Pixel Density"] = std::to_string(yDensity); offset += 2; unsigned char thumbW = data[offset]; offset += 1; unsigned char thumbH = data[offset]; offset += 1; properties["Thumbnail Width"] = std::to_string(thumbW); properties["Thumbnail Height"] = std::to_string(thumbH); properties["Has Thumbnail"] = (thumbW > 0 && thumbH > 0) ? "Yes" : "No"; offset += 3 * thumbW * thumbH; } else if ((marker & 0xFFF0) == 0xFFC0 || (marker & 0xFFF0) == 0xFFC8) { // SOF properties["Compression Mode"] = (marker == 0xFFC0) ? "Baseline DCT" : "Progressive DCT"; unsigned short length = (data[offset] << 8) | data[offset + 1]; offset += 2; properties["Bits per Sample"] = std::to_string(data[offset]); offset += 1; unsigned short height = (data[offset] << 8) | data[offset + 1]; properties["Image Height"] = std::to_string(height); offset += 2; unsigned short width = (data[offset] << 8) | data[offset + 1]; properties["Image Width"] = std::to_string(width); offset += 2; properties["Number of Color Components"] = std::to_string(data[offset]); offset += 1; offset += (length - 8); } else if (marker == 0xFFD9) { break; } else { if ((marker & 0xFF00) != 0xFF00) break; unsigned short length = (data[offset] << 8) | data[offset + 1]; offset += length; } } properties["File Signature"] = "FFD8FFE0 (JFIF)"; } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& outputPath, bool modifyExample = false) { if (data.empty()) { std::cout << "No data to write" << std::endl; return; } std::vector modifiedData = data; if (modifyExample) { // Example: Set Xdensity to 300 size_t app0Start = 0; for (size_t i = 0; i < modifiedData.size() - 1; ++i) { if (modifiedData[i] == 0xFF && modifiedData[i + 1] == 0xE0) { app0Start = i; break; } } if (app0Start != 0) { size_t densityOffset = app0Start + 2 + 2 + 5 + 2 + 1; // Marker + length + JFIF\0 + version + units modifiedData[densityOffset] = 300 >> 8; modifiedData[densityOffset + 1] = 300 & 0xFF; } } std::ofstream outFile(outputPath, std::ios::binary); outFile.write(reinterpret_cast(modifiedData.data()), modifiedData.size()); outFile.close(); } }; // Usage example: // int main() { // JPEParser parser("sample.jpe"); // parser.read(); // parser.printProperties(); // parser.write("modified.jpe", true); // return 0; // } // ===== end task-330 .JPE ===== // ===== task-331 .JPEG [C++] ===== #include #include #include #include #include #include #include class JPEGHandler { private: std::string filepath; std::map props; // Simplified to string values for print std::vector data; uint16_t getUint16(const uint8_t* ptr, bool bigEndian = true) { if (bigEndian) return (ptr[0] << 8) | ptr[1]; return (ptr[1] << 8) | ptr[0]; } uint32_t getUint32(const uint8_t* ptr, bool bigEndian = true) { if (bigEndian) return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; return (ptr[3] << 24) | (ptr[2] << 16) | (ptr[1] << 8) | ptr[0]; } void parseSegment(uint8_t marker, const uint8_t* segData, size_t length) { if (marker == 0xE0) { // APP0 JFIF if (std::string(reinterpret_cast(segData), 5) == "JFIF\0") { props["JFIF Version"] = std::to_string(segData[5]) + "." + std::to_string(segData[6]); props["Density Units"] = std::to_string(segData[7]); props["X Density"] = std::to_string(getUint16(segData + 8)); props["Y Density"] = std::to_string(getUint16(segData + 10)); props["Thumbnail Width"] = std::to_string(segData[12]); props["Thumbnail Height"] = std::to_string(segData[13]); } } else if (marker >= 0xC0 && marker <= 0xCF && marker != 0xC4 && marker != 0xC8 && marker != 0xCC) { // SOF props["Sample Precision"] = std::to_string(segData[0]); props["Image Height"] = std::to_string(getUint16(segData + 1)); props["Image Width"] = std::to_string(getUint16(segData + 3)); int nf = segData[5]; props["Number of Components"] = std::to_string(nf); // Component details as string for simplicity std::string compStr; const uint8_t* off = segData + 6; for (int i = 0; i < nf; ++i) { compStr += "ID:" + std::to_string(off[0]) + " H:" + std::to_string(off[1] >> 4) + " V:" + std::to_string(off[1] & 0x0F) + " QID:" + std::to_string(off[2]) + "; "; off += 3; } props["Component Details"] = compStr; } else if (marker == 0xDB) { // DQT std::string qtStr; size_t off = 0; while (off < length) { uint8_t pq = segData[off]; int p = pq >> 4; int qid = pq & 0x0F; qtStr += "ID:" + std::to_string(qid) + " Precision:" + std::to_string(p ? 16 : 8) + " Values:["; int elemSize = p + 1; for (int i = 0; i < 64; ++i) { uint16_t val = elemSize == 1 ? segData[off + 1 + i] : getUint16(segData + off + 1 + i * 2); qtStr += std::to_string(val) + ","; } qtStr += "]; "; off += 1 + 64 * elemSize; } props["Quantization Tables"] = qtStr; } else if (marker == 0xC4) { // DHT std::string htStr; size_t off = 0; while (off < length) { uint8_t tc = segData[off]; std::string classType = (tc >> 4) ? "AC" : "DC"; int hid = tc & 0x0F; htStr += "Class:" + classType + " ID:" + std::to_string(hid) + " Counts:["; for (int i = 1; i <= 16; ++i) htStr += std::to_string(segData[off + i]) + ","; int totalCodes = 0; for (int i = 1; i <= 16; ++i) totalCodes += segData[off + i]; htStr += "] Values:["; for (int i = 0; i < totalCodes; ++i) htStr += std::to_string(segData[off + 17 + i]) + ","; htStr += "]; "; off += 17 + totalCodes; } props["Huffman Tables"] = htStr; } else if (marker == 0xDD) { // DRI props["Restart Interval"] = std::to_string(getUint16(segData)); } else if (marker == 0xFE) { // COM std::string comment = std::string(reinterpret_cast(segData), length); props["Comments"] = (props.count("Comments") ? props["Comments"] + "; " : "") + comment; } else if (marker == 0xE1) { // APP1 EXIF if (std::string(reinterpret_cast(segData), 6) == "Exif\0\0") { props["EXIF Tags"] = parseExif(segData + 6, length - 6); } } } std::string parseExif(const uint8_t* exData, size_t length) { std::string exifStr; bool littleEndian = std::string(reinterpret_cast(exData), 2) == "II"; uint16_t tiffTag = getUint16(exData + 2, !littleEndian); if (tiffTag != 0x002A) return "Invalid EXIF"; uint32_t ifdOffset = getUint32(exData + 4, !littleEndian); uint16_t numEntries = getUint16(exData + ifdOffset, !littleEndian); ifdOffset += 2; for (uint16_t i = 0; i < numEntries; ++i) { uint16_t tag = getUint16(exData + ifdOffset, !littleEndian); uint16_t type = getUint16(exData + ifdOffset + 2, !littleEndian); uint32_t count = getUint32(exData + ifdOffset + 4, !littleEndian); uint32_t valOffset = getUint32(exData + ifdOffset + 8, !littleEndian); std::string value; if (type == 2) { // ASCII value = std::string(reinterpret_cast(exData + valOffset), count - 1); } else if (type == 3) { // Short value = std::to_string(getUint16(exData + ifdOffset + 8, !littleEndian)); } else if (type == 5) { // Rational uint32_t num = getUint32(exData + valOffset, !littleEndian); uint32_t den = getUint32(exData + valOffset + 4, !littleEndian); value = std::to_string(static_cast(num) / den); } if (tag == 0x010F) exifStr += "Make:" + value + "; "; else if (tag == 0x0110) exifStr += "Model:" + value + "; "; else if (tag == 0x0112) exifStr += "Orientation:" + value + "; "; else if (tag == 0x0132) exifStr += "DateTime:" + value + "; "; // Add more ifdOffset += 12; } return exifStr; } public: JPEGHandler(const std::string& fp) : filepath(fp) {} void readDecode() { std::ifstream file(filepath, std::ios::binary); if (!file) throw std::runtime_error("Cannot open file"); file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0); data.resize(size); file.read(reinterpret_cast(data.data()), size); if (getUint16(data.data()) != 0xFFD8) throw std::runtime_error("Not a valid JPEG"); props["File Signature"] = "0xFFD8"; size_t offset = 2; while (offset < size) { if (data[offset] != 0xFF) break; uint8_t marker = data[offset + 1]; offset += 2; if (marker == 0xD9) break; if (marker >= 0xD0 && marker <= 0xD7 || marker == 0xD8 || marker == 0xD9) continue; uint16_t length = getUint16(data.data() + offset); parseSegment(marker, data.data() + offset + 2, length - 2); offset += length; } } void printProperties() { for (const auto& p : props) { std::cout << p.first << ": " << p.second << std::endl; } } void write(const std::string& newFilepath = "") { std::string outPath = newFilepath.empty() ? filepath : newFilepath; std::ofstream out(outPath, std::ios::binary); out.write(reinterpret_cast(data.data()), data.size()); std::cout << "File written to " << outPath << std::endl; } }; // Example usage: // int main() { // JPEGHandler handler("example.jpg"); // handler.readDecode(); // handler.printProperties(); // handler.write("modified.jpg"); // return 0; // } // ===== end task-331 .JPEG ===== // ===== task-332 .JPG [C] ===== #include #include #include #include typedef struct { char* filepath; uint8_t* data; size_t size; // For properties, use a simple array of strings for demo; in real, use dict-like char* properties[100]; // Limited, for simplicity int prop_count; } JPEGHandler; void init_jpeg_handler(JPEGHandler* handler, const char* filepath) { handler->filepath = strdup(filepath); handler->data = NULL; handler->size = 0; handler->prop_count = 0; } void open_file(JPEGHandler* handler) { FILE* f = fopen(handler->filepath, "rb"); if (!f) { perror("open_file"); exit(1); } fseek(f, 0, SEEK_END); handler->size = ftell(f); fseek(f, 0, SEEK_SET); handler->data = malloc(handler->size); fread(handler->data, 1, handler->size, f); fclose(f); } void add_property(JPEGHandler* handler, const char* prop) { if (handler->prop_count < 100) { handler->properties[handler->prop_count++] = strdup(prop); } } void decode(JPEGHandler* handler) { if (!handler->data) { fprintf(stderr, "File not opened\n"); return; } size_t offset = 0; if (handler->data[offset] != 0xFF || handler->data[offset + 1] != 0xD8) { fprintf(stderr, "Invalid JPEG: Missing SOI\n"); return; } add_property(handler, "SOI: Present"); offset += 2; char buf[256]; while (offset < handler->size) { if (handler->data[offset] != 0xFF) break; uint8_t marker = handler->data[offset + 1]; offset += 2; if (marker == 0xD9) { add_property(handler, "EOI: Present"); break; } if (marker >= 0xD0 && marker <= 0xD7) { // RST snprintf(buf, sizeof(buf), "Restart Marker: %d", marker - 0xD0); add_property(handler, buf); continue; } uint16_t length = (handler->data[offset] << 8) | handler->data[offset + 1]; offset += 2; if (marker >= 0xC0 && marker <= 0xCF && marker != 0xC4 && marker != 0xC8 && marker != 0xCC) { // SOF const char* type = get_frame_type(marker); snprintf(buf, sizeof(buf), "Frame Type: %s", type); add_property(handler, buf); uint8_t precision = handler->data[offset++]; uint16_t height = (handler->data[offset] << 8) | handler->data[offset + 1]; offset += 2; uint16_t width = (handler->data[offset] << 8) | handler->data[offset + 1]; offset += 2; uint8_t components = handler->data[offset++]; snprintf(buf, sizeof(buf), "Sample Precision: %u", precision); add_property(handler, buf); snprintf(buf, sizeof(buf), "Height: %u", height); add_property(handler, buf); snprintf(buf, sizeof(buf), "Width: %u", width); add_property(handler, buf); snprintf(buf, sizeof(buf), "Components: %u", components); add_property(handler, buf); add_property(handler, "Component Details:"); for (uint8_t i = 0; i < components; i++) { uint8_t id = handler->data[offset++]; uint8_t sampling = handler->data[offset++]; uint8_t h = sampling >> 4, v = sampling & 0x0F; uint8_t qtable = handler->data[offset++]; snprintf(buf, sizeof(buf), " Component %u: ID=%u, H=%u, V=%u, Quant Table=%u", i+1, id, h, v, qtable); add_property(handler, buf); } } else if (marker == 0xDB) { // DQT add_property(handler, "Quantization Tables:"); size_t end = offset + length - 2; while (offset < end) { uint8_t info = handler->data[offset++]; uint8_t prec = info >> 4 ? 16 : 8; uint8_t id = info & 0x0F; snprintf(buf, sizeof(buf), " Table ID: %u, Precision: %u-bit", id, prec); add_property(handler, buf); add_property(handler, " Values:"); char val_buf[1024] = ""; for (int i = 0; i < 64; i++) { uint16_t val; if (prec == 16) { val = (handler->data[offset] << 8) | handler->data[offset + 1]; offset += 2; } else { val = handler->data[offset++]; } char temp[10]; snprintf(temp, sizeof(temp), "%u ", val); strcat(val_buf, temp); if (strlen(val_buf) > 900) { // Prevent overflow add_property(handler, val_buf); val_buf[0] = '\0'; } } add_property(handler, val_buf); } } else if (marker == 0xC4) { // DHT add_property(handler, "Huffman Tables:"); size_t end = offset + length - 2; while (offset < end) { uint8_t info = handler->data[offset++]; const char* class_type = (info >> 4) ? "AC" : "DC"; uint8_t id = info & 0x0F; snprintf(buf, sizeof(buf), " Table: %s ID=%u", class_type, id); add_property(handler, buf); add_property(handler, " Code Lengths:"); char len_buf[256] = ""; int total_sym = 0; for (int i = 0; i < 16; i++) { uint8_t count = handler->data[offset++]; char temp[10]; snprintf(temp, sizeof(temp), "%u ", count); strcat(len_buf, temp); total_sym += count; } add_property(handler, len_buf); add_property(handler, " Symbols:"); char sym_buf[1024] = ""; for (int i = 0; i < total_sym; i++) { uint8_t sym = handler->data[offset++]; char temp[10]; snprintf(temp, sizeof(temp), "%u ", sym); strcat(sym_buf, temp); if (strlen(sym_buf) > 900) { add_property(handler, sym_buf); sym_buf[0] = '\0'; } } add_property(handler, sym_buf); } } else if (marker == 0xDD) { // DRI uint16_t interval = (handler->data[offset] << 8) | handler->data[offset + 1]; snprintf(buf, sizeof(buf), "Restart Interval: %u", interval); add_property(handler, buf); offset += 2; } else if (marker == 0xDA) { // SOS add_property(handler, "Scan Header:"); uint8_t comps = handler->data[offset++]; snprintf(buf, sizeof(buf), " Components in Scan: %u", comps); add_property(handler, buf); for (uint8_t i = 0; i < comps; i++) { uint8_t selector = handler->data[offset++]; uint8_t tables = handler->data[offset++]; uint8_t dc = tables >> 4, ac = tables & 0x0F; snprintf(buf, sizeof(buf), " Component %u: Selector=%u, DC Table=%u, AC Table=%u", i+1, selector, dc, ac); add_property(handler, buf); } uint8_t ss = handler->data[offset++], se = handler->data[offset++]; uint8_t approx = handler->data[offset++]; uint8_t ah = approx >> 4, al = approx & 0x0F; snprintf(buf, sizeof(buf), " Spectral Start: %u, End: %u", ss, se); add_property(handler, buf); snprintf(buf, sizeof(buf), " Approx High: %u, Low: %u", ah, al); add_property(handler, buf); // Skip entropy while (offset < handler->size && (handler->data[offset] != 0xFF || handler->data[offset + 1] == 0x00)) offset++; if (handler->data[offset] == 0xFF && handler->data[offset + 1] != 0x00) offset -= 2; } else if (marker == 0xFE) { // COM char* comment = malloc(length - 1); strncpy(comment, (const char*)&handler->data[offset], length - 2); comment[length - 2] = '\0'; snprintf(buf, sizeof(buf), "Comment: %s", comment); add_property(handler, buf); free(comment); } else if (marker >= 0xE0 && marker <= 0xEF) { // APPn char app_data[6]; strncpy(app_data, (const char*)&handler->data[offset], 5); app_data[5] = '\0'; if (strcmp(app_data, "JFIF") == 0) { // Note: \0 is next byte uint8_t major = handler->data[offset + 5]; uint8_t minor = handler->data[offset + 6]; uint8_t units = handler->data[offset + 7]; uint16_t xdens = (handler->data[offset + 8] << 8) | handler->data[offset + 9]; uint16_t ydens = (handler->data[offset + 10] << 8) | handler->data[offset + 11]; uint8_t thumb_w = handler->data[offset + 12]; uint8_t thumb_h = handler->data[offset + 13]; snprintf(buf, sizeof(buf), "JFIF: Version %u.%u, Units=%u, XDensity=%u, YDensity=%u, Thumbnail %ux%u", major, minor, units, xdens, ydens, thumb_w, thumb_h); add_property(handler, buf); } else if (strcmp(app_data, "JFXX") == 0) { uint8_t ext_code = handler->data[offset + 5]; snprintf(buf, sizeof(buf), "JFXX Extension: Code 0x%02X", ext_code); add_property(handler, buf); } else { snprintf(buf, sizeof(buf), "APP%u: %s", marker - 0xE0, app_data); add_property(handler, buf); } } offset += length - 2; } } void print_properties(const JPEGHandler* handler) { for (int i = 0; i < handler->prop_count; i++) { printf("%s\n", handler->properties[i]); } } void write_file(const JPEGHandler* handler, const char* output_path) { if (!handler->data) { fprintf(stderr, "No data to write\n"); return; } FILE* f = fopen(output_path, "wb"); if (!f) { perror("write_file"); return; } fwrite(handler->data, 1, handler->size, f); fclose(f); } void free_handler(JPEGHandler* handler) { free(handler->data); free(handler->filepath); for (int i = 0; i < handler->prop_count; i++) { free(handler->properties[i]); } } const char* get_frame_type(uint8_t marker) { switch (marker) { case 0xC0: return "Baseline DCT"; case 0xC1: return "Extended Sequential DCT"; case 0xC2: return "Progressive DCT"; case 0xC3: return "Lossless"; case 0xC5: return "Diff Sequential DCT"; case 0xC6: return "Diff Progressive DCT"; case 0xC7: return "Diff Lossless"; default: return "Unknown"; } } // Example usage: // int main() { // JPEGHandler handler; // init_jpeg_handler(&handler, "example.jpg"); // open_file(&handler); // decode(&handler); // print_properties(&handler); // write_file(&handler, "output.jpg"); // free_handler(&handler); // return 0; // } // ===== end task-332 .JPG ===== // ===== task-333 .JS [C++] ===== #include #include #include #include #include #include // For getuid, etc., if needed class JSFileHandler { private: std::string filename; struct stat file_stat; public: JSFileHandler(const std::string& fname) : filename(fname) { if (filename.length() < 3 || filename.substr(filename.length() - 3) != ".js") { throw std::invalid_argument("File must have .js extension"); } if (::stat(filename.c_str(), &file_stat) != 0) { throw std::runtime_error("Failed to get file stats"); } } std::string decode_read_content() { // No binary decoding needed; read as text std::ifstream file(filename); if (!file) { throw std::runtime_error("Failed to open file for reading"); } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); return content; } void write_content(const std::string& content) { std::ofstream file(filename); if (!file) { throw std::runtime_error("Failed to open file for writing"); } file << content; } void print_properties() { std::cout << "File name: " << filename << std::endl; // basename not used for simplicity std::cout << "File path: " << std::string(std::filesystem::absolute(filename)) << std::endl; // Requires C++17 std::cout << "Size (in bytes): " << file_stat.st_size << std::endl; std::cout << "Creation time: " << std::ctime(&file_stat.st_ctime); std::cout << "Last modification time: " << std::ctime(&file_stat.st_mtime); std::cout << "Last access time: " << std::ctime(&file_stat.st_atime); std::cout << "Permissions: " << std::oct << file_stat.st_mode << std::dec << std::endl; std::cout << "Owner user ID (or name): " << file_stat.st_uid << std::endl; std::cout << "Owner group ID (or name): " << file_stat.st_gid << std::endl; std::cout << "Inode number: " << file_stat.st_ino << std::endl; std::cout << "Number of hard links: " << file_stat.st_nlink << std::endl; std::cout << "Device ID: " << file_stat.st_dev << std::endl; std::cout << "File type: regular file" << std::endl; } }; // ===== end task-333 .JS ===== // ===== task-334 .JSON [C++] ===== #include #include #include #include using json = nlohmann::json; class JSONHandler { private: std::string filename; json data; public: JSONHandler(const std::string& fn) : filename(fn) {} void openAndDecode() { if (filename.substr(filename.find_last_of(".") + 1) != "json") { throw std::invalid_argument("File must have .json extension"); } std::ifstream file(filename); if (!file.is_open()) { throw std::runtime_error("Could not open file"); } file >> data; file.close(); } json read(const std::string& key = "") { if (data.is_null()) { throw std::runtime_error("File not opened or decoded"); } if (!key.empty()) { return data.value(key, json(nullptr)); } return data; } void write(const json& newData = json(nullptr), const std::string& newFilename = "") { json toWrite = (newData.is_null()) ? data : newData; if (toWrite.is_null()) { throw std::runtime_error("No data to write"); } std::string targetFilename = newFilename.empty() ? filename : newFilename; std::ofstream file(targetFilename); if (!file.is_open()) { throw std::runtime_error("Could not open file for writing"); } file << toWrite.dump(4); file.close(); } void printProperties() { std::string properties[] = { "File extension: .json", "MIME type: application/json", "Encoding: UTF-8", "Byte order mark: None", "Macintosh file type code: TEXT" }; for (const auto& prop : properties) { std::cout << prop << std::endl; } } }; // ===== end task-334 .JSON ===== // ===== task-335 .JSP [C++] ===== #include #include #include #include #include class JSPParser { private: std::string filepath; std::map properties; std::string content; public: JSPParser(const std::string& fp) : filepath(fp) {} void readAndDecode() { if (filepath.substr(filepath.find_last_of(".") + 1) != "jsp") { std::cout << "Invalid .JSP file." << std::endl; return; } std::ifstream file(filepath); if (!file.is_open()) { std::cout << "Failed to open file." << std::endl; return; } std::string line; while (std::getline(file, line)) { content += line + "\n"; } file.close(); std::regex directiveRegex(R"(<%@\s*page\s+([^%>]+)%>)", std::regex_constants::icase); std::smatch match; if (std::regex_search(content, match, directiveRegex)) { std::string attrs = match[1].str(); std::regex propRegex(R"((\w+)\s*=\s*"([^"]*)")"); std::sregex_iterator iter(attrs.begin(), attrs.end(), propRegex); std::sregex_iterator end; for (; iter != end; ++iter) { properties[(*iter)[1].str()] = (*iter)[2].str(); } } printProperties(); } void printProperties() { if (properties.empty()) { std::cout << "No properties found in the page directive." << std::endl; return; } std::cout << "Extracted JSP Properties:" << std::endl; for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& newFilepath, const std::map& newProperties = {}) { for (const auto& pair : newProperties) { properties[pair.first] = pair.second; } std::string directive = "<%@ page "; for (const auto& pair : properties) { directive += pair.first + "=\"" + pair.second + "\" "; } directive += "%>"; std::string newContent = directive + "\n" + content; std::ofstream outFile(newFilepath); if (outFile.is_open()) { outFile << newContent; outFile.close(); std::cout << "Written to " << newFilepath << std::endl; } else { std::cout << "Failed to write file." << std::endl; } } }; // Example usage: // int main() { // JSPParser parser("example.jsp"); // parser.readAndDecode(); // std::map updates = {{"contentType", "text/html; charset=UTF-8"}}; // parser.write("new.jsp", updates); // return 0; // } // ===== end task-335 .JSP ===== // ===== task-336 .JUMP [C++] ===== #include #include #include #include #include struct DestEntry { char netbios[17]; uint64_t stream_num; time_t last_mod; char* path; }; class JumpFile { private: char* filename; FILE* fp; struct stat file_stat; DestEntry* dest_list; int dest_count; public: JumpFile(const char* fn) { filename = strdup(fn); dest_list = NULL; dest_count = 0; } ~JumpFile() { free(filename); for (int i = 0; i < dest_count; i++) free(dest_list[i].path); free(dest_list); } void open() { fp = fopen(filename, "rb"); if (!fp) { printf("Error opening file\n"); return; } stat(filename, &file_stat); // Read data (simplified, load whole file) fseek(fp, 0, SEEK_END); long size = ftell(fp); fseek(fp, 0, SEEK_SET); uint8_t* data = (uint8_t*)malloc(size); fread(data, 1, size, fp); // Check OLE if (*(uint32_t*)data != 0xE011CFD0 || *(uint32_t*)(data+4) != 0xE11AB1A1) { printf("Invalid OLE\n"); free(data); return; } // Assume DestList at offset int offset = 512 + 32; // Placeholder while (offset + 114 < size) { dest_list = (DestEntry*)realloc(dest_list, sizeof(DestEntry) * (++dest_count)); strncpy(dest_list[dest_count-1].netbios, (char*)(data + offset + 0x48), 16); dest_list[dest_count-1].netbios[16] = '\0'; dest_list[dest_count-1].stream_num = *(uint64_t*)(data + offset + 0x58); uint64_t last_mod_raw = *(uint64_t*)(data + offset + 0x64); dest_list[dest_count-1].last_mod = (time_t)((last_mod_raw / 10000000) - 11644473600LL); uint16_t path_size = *(uint16_t*)(data + offset + 0x70); dest_list[dest_count-1].path = (char*)malloc(path_size * 2 + 1); memcpy(dest_list[dest_count-1].path, data + offset + 0x72, path_size * 2); dest_list[dest_count-1].path[path_size * 2] = '\0'; offset += 114 + path_size * 2; } free(data); } void printProperties() { printf("Filename: %s\n", filename); printf("Creation Time: %s", ctime(&file_stat.st_ctime)); printf("Modification Time: %s", ctime(&file_stat.st_mtime)); printf("\nDestList Entries:\n"); for (int i = 0; i < dest_count; i++) { printf("NetBIOS: %s\nStream Num: %llu\nLast Mod: %sPath: %ls\n\n", dest_list[i].netbios, dest_list[i].stream_num, ctime(&dest_list[i].last_mod), (wchar_t*)dest_list[i].path); } } void write(const char* new_fn) { FILE* out = fopen(new_fn, "wb"); fseek(fp, 0, SEEK_SET); uint8_t buf[1024]; size_t read; while ((read = fread(buf, 1, 1024, fp)) > 0) { fwrite(buf, 1, read, out); } fclose(out); printf("File written\n"); } void close() { if (fp) fclose(fp); } }; int main() { JumpFile j("example.JUMP"); j.open(); j.printProperties(); j.write("new.JUMP"); j.close(); return 0; } // ===== end task-336 .JUMP ===== // ===== task-337 .JVX [C++] ===== #include #include #include #include #include class JVXHandler { private: std::string filepath; std::string xmlContent; void dumpProperties(const std::string& content) { // Simple regex-based dumper for elements/attributes/text (not robust, for demo) std::regex elemRegex("<(\\w+)([^>]*)>(.*?)", std::regex::dotall); std::smatch matches; std::string temp = content; while (std::regex_search(temp, matches, elemRegex)) { std::cout << "<" << matches[1] << matches[2] << ">" << std::endl; if (!matches[3].str().empty() && matches[3].str().find('<') == std::string::npos) { std::cout << " " << matches[3] << std::endl; } else if (!matches[3].str().empty()) { dumpProperties(matches[3]); // Recurse for nested } std::cout << "" << std::endl; temp = matches.suffix(); } } public: JVXHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath); if (!file.is_open()) { std::cout << "Error opening JVX file." << std::endl; return; } xmlContent.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); } void printProperties() { if (xmlContent.empty()) { std::cout << "No JVX loaded." << std::endl; return; } dumpProperties(xmlContent); } void write(const std::string& outputPath) { std::ofstream outFile(outputPath); if (!outFile.is_open()) { std::cout << "Error writing JVX." << std::endl; return; } if (xmlContent.empty()) { // Sample content xmlContent = R"( 2.00 Sample JVX )"; } outFile << xmlContent; outFile.close(); std::cout << "Written to " << outputPath << std::endl; } }; // Example usage: // int main() { // JVXHandler handler("sample.jvx"); // handler.read(); // handler.printProperties(); // handler.write("output.jvx"); // return 0; // } // ===== end task-337 .JVX ===== // ===== task-338 .JVX [C++] ===== #include #include #include #include #include #include class JXLHandler { private: std::string filename; std::vector data; std::map properties; public: JXLHandler(const std::string& fn) : filename(fn) {} void open() { std::ifstream file(filename, std::ios::binary); if (file) { file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(reinterpret_cast(data.data()), size); } } void decodeRead() { if (data.empty()) return; size_t offset = 0; if (data[0] == 0x00 && data[1] == 0x00 && data[2] == 0x00 && data[3] == 0x0C && data[4] == 0x4A && data[5] == 0x58 && data[6] == 0x4C && data[7] == 0x20) { properties["Signature"] = "Container (ISO BMFF)"; offset = 12; } else if (data[0] == 0xFF && data[1] == 0x0A) { properties["Signature"] = "Naked Codestream"; offset = 2; } else { throw std::runtime_error("Invalid JXL file"); } while (offset < data.size()) { uint32_t boxSize = (data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]; std::string boxType(1, data[offset+4]); boxType += data[offset+5]; boxType += data[offset+6]; boxType += data[offset+7]; properties["Box " + boxType + " Size"] = std::to_string(boxSize); if (boxType == "jxll") { uint8_t level = data[offset+8]; properties["Level"] = std::to_string(level); } else if (boxType == "Exif") { properties["Presence of Exif metadata"] = "Yes"; } else if (boxType == "xml ") { properties["Presence of XMP metadata"] = "Yes"; } else if (boxType == "jumb") { properties["Presence of JUMBF metadata"] = "Yes"; } else if (boxType == "jxlc" || boxType == "jxlp") { properties["Codestream found"] = "Yes"; auto csProps = parseCodestream(data, offset + 8); properties.insert(csProps.begin(), csProps.end()); } if (boxSize == 0) break; offset += boxSize; } } std::map parseCodestream(const std::vector& d, size_t start) { std::map props; size_t offset = start + 2; uint8_t byte = d[offset]; bool div8 = byte & 1; int ratio = (byte >> 1) & 7; offset += 1; uint32_t height = (d[offset] << 24) | (d[offset+1] << 16) | (d[offset+2] << 8) | d[offset+3]; uint32_t width = (d[offset+4] << 24) | (d[offset+5] << 16) | (d[offset+6] << 8) | d[offset+7]; props["Image height"] = std::to_string(height); props["Image width"] = std::to_string(width); return props; } void write(const std::string& newFilename) { std::ofstream file(newFilename, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); } void printProperties() { for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } }; // Example: // JXLHandler handler("example.jxl"); // handler.open(); // handler.decodeRead(); // handler.printProperties(); // handler.write("output.jxl"); // ===== end task-338 .JVX ===== // ===== task-339 .KEY [C++] ===== #include #include #include #include #include #include #include "miniz.h" // Assume miniz for ZIP handling // For plist, simplified parser or use external like tinyxml for XML plists class KeyFileHandler { private: std::string filepath; mz_zip_archive zip; std::map properties; // Simplified to string values public: KeyFileHandler(const std::string& fp) : filepath(fp) { memset(&zip, 0, sizeof(zip)); } ~KeyFileHandler() { close(); } bool open() { if (!mz_zip_reader_init_file(&zip, filepath.c_str(), 0)) { return false; } decodeProperties(); return true; } void decodeProperties() { // File signature void* firstData; size_t firstSize; std::string firstFile = mz_zip_reader_get_filename(&zip, 0); mz_zip_reader_extract_to_mem(&zip, 0, &firstData, &firstSize, 0); std::string sig; for (size_t i = 0; i < 4 && i < firstSize; ++i) { char buf[3]; sprintf(buf, "%02X ", ((unsigned char*)firstData)[i]); sig += buf; } properties["file_signature"] = sig.substr(0, sig.size() - 1); mz_free(firstData); // Structure std::stringstream structure; for (mz_uint i = 0; i < mz_zip_reader_get_num_files(&zip); ++i) { structure << mz_zip_reader_get_filename(&zip, i) << " "; } properties["structure"] = structure.str(); // Simplified plist parsing (text dump) std::vector plists = {"Metadata/buildVersionHistory.plist", "Metadata/Properties.plist", "Metadata/DocumentIdentifier"}; for (const auto& p : plists) { mz_uint index; if (mz_zip_reader_locate_file(&zip, p.c_str(), nullptr, 0, &index)) { void* data; size_t size; mz_zip_reader_extract_to_mem(&zip, index, &data, &size, 0); properties[p] = std::string((char*)data, size); mz_free(data); } } // Previews and index std::stringstream previews; bool hasIndex = false; for (mz_uint i = 0; i < mz_zip_reader_get_num_files(&zip); ++i) { std::string name = mz_zip_reader_get_filename(&zip, i); if (name.find("preview") != std::string::npos || name.find("Thumbnail") != std::string::npos) { previews << name << " "; } if (name.find("Index") != std::string::npos) { hasIndex = true; } } properties["previews"] = previews.str(); properties["has_index"] = hasIndex ? "true" : "false"; } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } bool write(const std::string& newFilepath, const std::map& modifications) { mz_zip_archive newZip; memset(&newZip, 0, sizeof(newZip)); if (!mz_zip_writer_init_file(&newZip, newFilepath.c_str(), 0)) { return false; } for (mz_uint i = 0; i < mz_zip_reader_get_num_files(&zip); ++i) { std::string name = mz_zip_reader_get_filename(&zip, i); void* data; size_t size; mz_zip_reader_extract_to_mem(&zip, i, &data, &size, 0); auto it = modifications.find(name); if (it != modifications.end()) { data = (void*)it->second.data(); size = it->second.size(); } mz_zip_writer_add_mem(&newZip, name.c_str(), data, size, MZ_DEFAULT_COMPRESSION); mz_free(data); } mz_zip_writer_finalize_archive(&newZip); mz_zip_writer_end(&newZip); return true; } void close() { mz_zip_reader_end(&zip); } }; // Usage: // KeyFileHandler handler("example.key"); // if (handler.open()) { // handler.printProperties(); // std::map mods = {{"Metadata/Properties.plist", "newvalue"}}; // handler.write("modified.key", mods); // } // ===== end task-339 .KEY ===== // ===== task-340 .KLC [C++] ===== #include #include #include #include #include #include class KLCParser { private: std::map> properties; public: void read(const std::string& filepath) { std::ifstream file(filepath, std::ios::binary); if (!file) { std::cerr << "Cannot open file" << std::endl; return; } std::string line; std::string currentSection; while (std::getline(file, line)) { // Trim line (simple trim) line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); if (line.empty()) continue; bool isSection = true; for (char c : line) { if (!isupper(c)) { isSection = false; break; } } if (isSection) { currentSection = line; properties[currentSection] = {}; } else if (!currentSection.empty()) { properties[currentSection].push_back(line); } else { std::istringstream iss(line); std::string key, value; iss >> key; std::getline(iss, value); properties[key] = {value}; } } // Post-processing if (properties.count("SHIFTSTATE")) { auto& shift = properties["SHIFTSTATE"]; std::vector newShift; for (auto& l : shift) { if (isdigit(l[0])) { size_t pos = l.find("//"); if (pos != std::string::npos) l = l.substr(0, pos); l.erase(l.find_last_not_of(" \t") + 1); newShift.push_back(l); } } shift = newShift; } if (properties.count("LAYOUT")) { auto& layout = properties["LAYOUT"]; std::vector newLayout; for (auto& l : layout) { if (isalnum(l[0])) { size_t pos = l.find("//"); if (pos != std::string::npos) l = l.substr(0, pos); l.erase(l.find_last_not_of(" \t") + 1); newLayout.push_back(l); } } layout = newLayout; } } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ":" << std::endl; for (const auto& val : pair.second) { std::cout << " " << val << std::endl; } } } void write(const std::string& filepath) { std::ofstream file(filepath, std::ios::binary); if (!file) { std::cerr << "Cannot open file for writing" << std::endl; return; } for (const auto& pair : properties) { if (pair.second.size() == 1 && !pair.second[0].empty()) { file << pair.first << " " << pair.second[0] << "\n"; } else { file << pair.first << "\n"; for (const auto& val : pair.second) { file << val << "\n"; } } } file << "ENDKBD\n"; } }; int main() { KLCParser parser; parser.read("example.klc"); parser.printProperties(); parser.write("output.klc"); return 0; } // ===== end task-340 .KLC ===== // ===== task-341 .KML [C++] ===== #include #include #include #include class KMLHandler { private: std::string filename; xmlDocPtr doc; void dumpProperties(xmlNodePtr node, int indent) { std::string indentStr(indent * 2, ' '); std::cout << indentStr << "Element: " << node->name << std::endl; for (xmlAttrPtr attr = node->properties; attr; attr = attr->next) { std::string value(reinterpret_cast(attr->children->content)); std::cout << indentStr << " Attribute: " << attr->name << " = \"" << value << "\"" << std::endl; } std::string text; for (xmlNodePtr child = node->children; child; child = child->next) { if (child->type == XML_TEXT_NODE && xmlNodeGetContent(child)) { text = reinterpret_cast(xmlNodeGetContent(child)); text.erase(0, text.find_first_not_of(" \t\n\r\f\v")); text.erase(text.find_last_not_of(" \t\n\r\f\v") + 1); if (!text.empty()) { std::cout << indentStr << " Text: " << text << std::endl; } } } for (xmlNodePtr child = node->children; child; child = child->next) { if (child->type == XML_ELEMENT_NODE) { dumpProperties(child, indent + 1); } } } public: KMLHandler(const std::string& fn) : filename(fn), doc(nullptr) {} ~KMLHandler() { if (doc) xmlFreeDoc(doc); } void read() { if (filename.substr(filename.find_last_of(".") + 1) != "kml") { throw std::runtime_error("Invalid .KML file"); } doc = xmlReadFile(filename.c_str(), nullptr, 0); if (!doc) { throw std::runtime_error("Failed to parse KML"); } } void printProperties() { if (!doc) { throw std::runtime_error("File not read yet"); } xmlNodePtr root = xmlDocGetRootElement(doc); dumpProperties(root, 0); } void write(const std::string& outputFilename = "") { if (!doc) { throw std::runtime_error("No data to write"); } std::string out = outputFilename.empty() ? filename : outputFilename; xmlSaveFormatFileEnc(out.c_str(), doc, "UTF-8", 1); } }; // Example usage: // int main() { // try { // KMLHandler handler("sample.kml"); // handler.read(); // handler.printProperties(); // handler.write("output.kml"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-341 .KML ===== // ===== task-342 .KMZ [C++] ===== #include #include #include #include #include #include class KMZParser { private: std::vector data; struct ArchiveProps { uint16_t diskNum, cdDiskNum, entriesThisDisk, totalEntries; uint32_t cdSize, cdOffset; std::string comment; }; struct Entry { uint16_t versionMade, versionNeeded, bitFlag, compMethod, modTime, modDate; uint32_t crc32, compSize, uncompSize; std::string name, comment; uint16_t diskStart, intAttr; uint32_t extAttr, localOffset; std::vector extra; }; ArchiveProps archive; std::vector entries; std::string kmzRoot; std::vector kmzSupport; public: KMZParser(const std::string& filename = "") { if (!filename.empty()) load(filename); } void load(const std::string& filename) { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) throw std::runtime_error("Cannot open file"); size_t size = file.tellg(); data.resize(size); file.seekg(0); file.read(reinterpret_cast(data.data()), size); parse(); } size_t findEOCD() { for (size_t i = data.size() - 22; i != static_cast(-1); --i) { uint32_t sig; std::memcpy(&sig, &data[i], 4); if (sig == 0x06054B50) return i; } throw std::runtime_error("EOCD signature not found"); } void parse() { size_t eocdOffset = findEOCD(); std::memcpy(&archive.diskNum, &data[eocdOffset + 4], 2); std::memcpy(&archive.cdDiskNum, &data[eocdOffset + 6], 2); std::memcpy(&archive.entriesThisDisk, &data[eocdOffset + 8], 2); std::memcpy(&archive.totalEntries, &data[eocdOffset + 10], 2); std::memcpy(&archive.cdSize, &data[eocdOffset + 12], 4); std::memcpy(&archive.cdOffset, &data[eocdOffset + 16], 4); uint16_t commentLen; std::memcpy(&commentLen, &data[eocdOffset + 20], 2); archive.comment = std::string(reinterpret_cast(&data[eocdOffset + 22]), commentLen); size_t offset = archive.cdOffset; entries.resize(archive.totalEntries); for (size_t i = 0; i < archive.totalEntries; ++i) { uint32_t sig; std::memcpy(&sig, &data[offset], 4); if (sig != 0x02014B50) throw std::runtime_error("CD signature not found"); std::memcpy(&entries[i].versionMade, &data[offset + 4], 2); std::memcpy(&entries[i].versionNeeded, &data[offset + 6], 2); std::memcpy(&entries[i].bitFlag, &data[offset + 8], 2); std::memcpy(&entries[i].compMethod, &data[offset + 10], 2); std::memcpy(&entries[i].modTime, &data[offset + 12], 2); std::memcpy(&entries[i].modDate, &data[offset + 14], 2); std::memcpy(&entries[i].crc32, &data[offset + 16], 4); std::memcpy(&entries[i].compSize, &data[offset + 20], 4); std::memcpy(&entries[i].uncompSize, &data[offset + 24], 4); uint16_t nameLen, extraLen, commentLen; std::memcpy(&nameLen, &data[offset + 28], 2); std::memcpy(&extraLen, &data[offset + 30], 2); std::memcpy(&commentLen, &data[offset + 32], 2); std::memcpy(&entries[i].diskStart, &data[offset + 34], 2); std::memcpy(&entries[i].intAttr, &data[offset + 36], 2); std::memcpy(&entries[i].extAttr, &data[offset + 38], 4); std::memcpy(&entries[i].localOffset, &data[offset + 42], 4); entries[i].name = std::string(reinterpret_cast(&data[offset + 46]), nameLen); entries[i].extra.assign(&data[offset + 46 + nameLen], &data[offset + 46 + nameLen + extraLen]); entries[i].comment = std::string(reinterpret_cast(&data[offset + 46 + nameLen + extraLen]), commentLen); offset += 46 + nameLen + extraLen + commentLen; } kmzRoot = "doc.kml"; for (const auto& e : entries) { if (e.name.find(".kml") != std::string::npos) { kmzRoot = e.name; break; } } kmzSupport.clear(); for (const auto& e : entries) { if (e.name != kmzRoot) kmzSupport.push_back(e.name); } } void printProperties() const { std::cout << "Archive Properties:" << std::endl; std::cout << " diskNum: " << archive.diskNum << std::endl; std::cout << " cdDiskNum: " << archive.cdDiskNum << std::endl; std::cout << " entriesThisDisk: " << archive.entriesThisDisk << std::endl; std::cout << " totalEntries: " << archive.totalEntries << std::endl; std::cout << " cdSize: " << archive.cdSize << std::endl; std::cout << " cdOffset: " << archive.cdOffset << std::endl; std::cout << " comment: " << archive.comment << std::endl; std::cout << "\nEntries:" << std::endl; for (size_t i = 0; i < entries.size(); ++i) { std::cout << "Entry " << i + 1 << ":" << std::endl; std::cout << " name: " << entries[i].name << std::endl; std::cout << " versionMade: " << entries[i].versionMade << std::endl; std::cout << " versionNeeded: " << entries[i].versionNeeded << std::endl; std::cout << " bitFlag: " << entries[i].bitFlag << std::endl; std::cout << " compMethod: " << entries[i].compMethod << std::endl; std::cout << " modTime: " << entries[i].modTime << std::endl; std::cout << " modDate: " << entries[i].modDate << std::endl; std::cout << " crc32: " << entries[i].crc32 << std::endl; std::cout << " compSize: " << entries[i].compSize << std::endl; std::cout << " uncompSize: " << entries[i].uncompSize << std::endl; std::cout << " comment: " << entries[i].comment << std::endl; std::cout << " diskStart: " << entries[i].diskStart << std::endl; std::cout << " intAttr: " << entries[i].intAttr << std::endl; std::cout << " extAttr: " << entries[i].extAttr << std::endl; std::cout << " localOffset: " << entries[i].localOffset << std::endl; } std::cout << "\nKMZ-Specific:" << std::endl; std::cout << " Root KML: " << kmzRoot << std::endl; std::cout << " Supporting Files: "; for (const auto& s : kmzSupport) std::cout << s << " "; std::cout << std::endl; } void writeSimpleKmz(const std::string& outputFilename, const std::vector& kmlContent, const std::string& rootName = "doc.kml") { std::ofstream file(outputFilename, std::ios::binary); if (!file) throw std::runtime_error("Cannot write file"); // Local header uint32_t sig = 0x04034B50; uint16_t version = 10, flag = 0, method = 0, time = 0, date = 0; uint32_t crc = 0, compSize = kmlContent.size(), uncompSize = kmlContent.size(); uint16_t nameLen = rootName.length(), extraLen = 0; file.write(reinterpret_cast(&sig), 4); file.write(reinterpret_cast(&version), 2); file.write(reinterpret_cast(&flag), 2); file.write(reinterpret_cast(&method), 2); file.write(reinterpret_cast(&time), 2); file.write(reinterpret_cast(&date), 2); file.write(reinterpret_cast(&crc), 4); file.write(reinterpret_cast(&compSize), 4); file.write(reinterpret_cast(&uncompSize), 4); file.write(reinterpret_cast(&nameLen), 2); file.write(reinterpret_cast(&extraLen), 2); file << rootName; file.write(reinterpret_cast(kmlContent.data()), kmlContent.size()); // CD header sig = 0x02014B50; uint16_t versionMade = 10; uint16_t commentLen = 0, diskStart = 0, intAttr = 0; uint32_t extAttr = 0, localOffset = 0; file.write(reinterpret_cast(&sig), 4); file.write(reinterpret_cast(&versionMade), 2); file.write(reinterpret_cast(&version), 2); file.write(reinterpret_cast(&flag), 2); file.write(reinterpret_cast(&method), 2); file.write(reinterpret_cast(&time), 2); file.write(reinterpret_cast(&date), 2); file.write(reinterpret_cast(&crc), 4); file.write(reinterpret_cast(&compSize), 4); file.write(reinterpret_cast(&uncompSize), 4); file.write(reinterpret_cast(&nameLen), 2); file.write(reinterpret_cast(&extraLen), 2); file.write(reinterpret_cast(&commentLen), 2); file.write(reinterpret_cast(&diskStart), 2); file.write(reinterpret_cast(&intAttr), 2); file.write(reinterpret_cast(&extAttr), 4); file.write(reinterpret_cast(&localOffset), 4); file << rootName; // EOCD sig = 0x06054B50; uint16_t diskNum = 0, cdDisk = 0, entriesDisk = 1, totalEntries = 1; uint32_t cdSize = 46 + nameLen, cdOffset = 30 + nameLen + kmlContent.size(); uint16_t eCommentLen = 0; file.write(reinterpret_cast(&sig), 4); file.write(reinterpret_cast(&diskNum), 2); file.write(reinterpret_cast(&cdDisk), 2); file.write(reinterpret_cast(&entriesDisk), 2); file.write(reinterpret_cast(&totalEntries), 2); file.write(reinterpret_cast(&cdSize), 4); file.write(reinterpret_cast(&cdOffset), 4); file.write(reinterpret_cast(&eCommentLen), 2); } }; // Example usage: // int main() { // try { // KMZParser parser("example.kmz"); // parser.printProperties(); // std::vector kml = {'<', 'k', 'm', 'l', '>', '<', '/', 'k', 'm', 'l', '>'}; // parser.writeSimpleKmz("new.kmz", kml); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-342 .KMZ ===== // ===== task-343 .KO [C++] ===== #include #include #include #include #include #include #include class KOParser { private: std::string filename; std::map> properties; std::map elfHeader; std::vector data; size_t modinfoOff = 0; size_t modinfoSize = 0; public: KOParser(const std::string& fn) : filename(fn) {} void read() { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) { std::cerr << "Cannot open file" << std::endl; return; } size_t size = file.tellg(); data.resize(size); file.seekg(0); file.read(reinterpret_cast(data.data()), size); uint32_t* header = reinterpret_cast(data.data()); if (header[0] != 0x464c457f) { std::cerr << "Not ELF" << std::endl; return; } uint8_t* ident = reinterpret_cast(data.data()); uint16_t* hdr16 = reinterpret_cast(data.data()); uint64_t* hdr64 = reinterpret_cast(data.data()); elfHeader["Magic"] = "0x7F ELF"; elfHeader["Class"] = (ident[4] == 2 ? "64-bit" : "32-bit"); elfHeader["Data Encoding"] = (ident[5] == 1 ? "Little-endian" : "Big-endian"); elfHeader["Version"] = std::to_string(ident[6]); elfHeader["OS/ABI"] = std::to_string(ident[7]); elfHeader["Machine"] = std::to_string(hdr16[9]); elfHeader["Type"] = std::to_string(hdr16[8]); uint64_t shoff = hdr64[5]; uint16_t shentsize = hdr16[29]; uint16_t shnum = hdr16[30]; uint16_t shstrndx = hdr16[31]; // Section string table uint64_t strtabOff = *reinterpret_cast(data.data() + shoff + shstrndx * shentsize + 24); uint64_t strtabSize = *reinterpret_cast(data.data() + shoff + shstrndx * shentsize + 32); // Find .modinfo for (uint16_t i = 0; i < shnum; ++i) { uint64_t secOff = shoff + i * shentsize; uint32_t nameOff = *reinterpret_cast(data.data() + secOff); std::string name = getString(data.data() + strtabOff + nameOff); if (name == ".modinfo") { modinfoOff = *reinterpret_cast(data.data() + secOff + 24); modinfoSize = *reinterpret_cast(data.data() + secOff + 32); break; } } if (modinfoOff && modinfoSize) { char* modinfoPtr = reinterpret_cast(data.data() + modinfoOff); std::string modinfoStr(modinfoPtr, modinfoSize); size_t pos = 0; while (pos < modinfoSize) { size_t end = modinfoStr.find('\0', pos); if (end == std::string::npos) break; std::string pair = modinfoStr.substr(pos, end - pos); pos = end + 1; size_t eq = pair.find('='); if (eq != std::string::npos) { std::string key = pair.substr(0, eq); std::string value = pair.substr(eq + 1); properties[key].push_back(value); } } } } void printProperties() const { std::cout << "ELF Properties:" << std::endl; for (const auto& [key, value] : elfHeader) { std::cout << "- " << key << ": " << value << std::endl; } std::cout << "\nModule Properties:" << std::endl; for (const auto& [key, values] : properties) { for (const auto& value : values) { std::cout << "- " << key << ": " << value << std::endl; } } } void write(const std::string& outputFilename, const std::map& updates) { if (!updates.empty() && modinfoSize > 0) { char* modinfoPtr = reinterpret_cast(data.data() + modinfoOff); std::string modinfoStr(modinfoPtr, modinfoSize); for (const auto& [key, newValue] : updates) { std::string oldValue = properties.count(key) && !properties.at(key).empty() ? properties.at(key)[0] : ""; std::string oldPair = key + "=" + oldValue + "\0"; std::string newPair = key + "=" + newValue + "\0"; size_t pos = modinfoStr.find(oldPair); if (pos != std::string::npos && newPair.size() == oldPair.size()) { modinfoStr.replace(pos, oldPair.size(), newPair); } } std::memcpy(modinfoPtr, modinfoStr.data(), modinfoSize); } std::ofstream out(outputFilename, std::ios::binary); out.write(reinterpret_cast(data.data()), data.size()); } private: std::string getString(const uint8_t* ptr) const { std::string str; while (*ptr) { str += *ptr++; } return str; } }; int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Usage: " << argv[0] << " " << std::endl; return 1; } KOParser parser(argv[1]); parser.read(); parser.printProperties(); // Example write // std::map updates = {{"description", "Updated description"}}; // parser.write("modified.ko", updates); return 0; } // ===== end task-343 .KO ===== // ===== task-344 .KRA [C++] ===== #include #include #include #include #include class KraHandler { private: std::string filepath; zip_t* zip; std::map properties; public: KraHandler(const std::string& fp) : filepath(fp), zip(nullptr) {} ~KraHandler() { close(); } void open() { int err = 0; zip = zip_open(filepath.c_str(), 0, &err); if (!zip) std::cerr << "Failed to open ZIP" << std::endl; } void decodeRead() { if (!zip) open(); // Read maindoc.xml zip_file_t* file = zip_fopen(zip, "maindoc.xml", 0); zip_stat_t stat; zip_stat(zip, "maindoc.xml", 0, &stat); char* buf = new char[stat.size + 1]; zip_fread(file, buf, stat.size); buf[stat.size] = '\0'; xmlDocPtr doc = xmlParseMemory(buf, stat.size); xmlNodePtr root = xmlDocGetRootElement(doc); xmlNodePtr image = nullptr; for (xmlNodePtr node = root->children; node; node = node->next) { if (xmlStrcmp(node->name, (const xmlChar*)"IMAGE") == 0) { image = node; break; } } if (image) { properties["Document Width"] = (char*)xmlGetProp(image, (const xmlChar*)"width"); properties["Document Height"] = (char*)xmlGetProp(image, (const xmlChar*)"height"); properties["Color Space Name"] = (char*)xmlGetProp(image, (const xmlChar*)"colorspacename"); int layerCount = 0; for (xmlNodePtr node = root; node; node = node->next) if (xmlStrcmp(node->name, (const xmlChar*)"layer") == 0) layerCount++; properties["Number of Layers"] = std::to_string(layerCount); } xmlFreeDoc(doc); zip_fclose(file); delete[] buf; // Find first layer file const char* layerName = nullptr; int num = zip_get_num_entries(zip, 0); for (int i = 0; i < num; i++) { const char* name = zip_get_name(zip, i, 0); if (std::string(name).find("/layers/layer") != std::string::npos && std::string(name).find(".") == std::string::npos) { layerName = name; break; } } if (layerName) { file = zip_fopen(zip, layerName, 0); zip_stat(zip, layerName, 0, &stat); buf = new char[stat.size + 1]; zip_fread(file, buf, stat.size); buf[stat.size] = '\0'; std::string data(buf); size_t pos = 0; std::string line = data.substr(0, data.find('\n')); properties["Version"] = line.substr(line.find(' ') + 1); pos = data.find('\n') + 1; line = data.substr(pos, data.find('\n', pos) - pos); properties["Tile Width"] = line.substr(line.find(' ') + 1); pos = data.find('\n', pos) + 1; line = data.substr(pos, data.find('\n', pos) - pos); properties["Tile Height"] = line.substr(line.find(' ') + 1); pos = data.find('\n', pos) + 1; line = data.substr(pos, data.find('\n', pos) - pos); properties["Pixel Size"] = line.substr(line.find(' ') + 1); pos = data.find('\n', pos) + 1; line = data.substr(pos, data.find('\n', pos) - pos); size_t comma2 = line.find(',', line.find(',') + 1); size_t comma3 = line.find(',', comma2 + 1); properties["Compression Type"] = line.substr(comma2 + 1, comma3 - comma2 - 1); zip_fclose(file); delete[] buf; } properties["Bit Depth"] = std::to_string(std::stoi(properties["Pixel Size"]) * 8 / 4); properties["Has Animation"] = (zip_name_locate(zip, "keyframes.xml", 0) >= 0) ? "Yes" : "No"; properties["ICC Profile"] = (zip_name_locate(zip, ".icc", ZIP_FL_ENC_GUESS | ZIP_FL_NOCASE) >= 0) ? "Present" : "Absent"; // Default pixel const char* defPixelName = nullptr; for (int i = 0; i < num; i++) { const char* name = zip_get_name(zip, i, 0); if (std::string(name).ends_with(".defaultpixel")) { defPixelName = name; break; } } if (defPixelName) { file = zip_fopen(zip, defPixelName, 0); zip_stat(zip, defPixelName, 0, &stat); buf = new char[stat.size]; zip_fread(file, buf, stat.size); properties["Default Pixel"] = std::string(buf, stat.size); // Binary, so string rep zip_fclose(file); delete[] buf; } else { properties["Default Pixel"] = "N/A"; } } void printProperties() { for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } void write(const std::string& newFilepath) { // Simple copy and modify maindoc.xml zip_t* newZip = zip_open(newFilepath.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); int num = zip_get_num_entries(zip, 0); for (int i = 0; i < num; i++) { const char* name = zip_get_name(zip, i, 0); zip_file_t* file = zip_fopen_index(zip, i, 0); zip_stat_t stat; zip_stat_index(zip, i, 0, &stat); char* buf = new char[stat.size]; zip_fread(file, buf, stat.size); zip_file_add(newZip, name, zip_buffer_create(buf, stat.size), ZIP_FL_OVERWRITE); zip_fclose(file); // Modify if maindoc.xml if (std::string(name) == "maindoc.xml") { xmlDocPtr doc = xmlParseMemory(buf, stat.size); xmlNodePtr image = nullptr; xmlNodePtr root = xmlDocGetRootElement(doc); for (xmlNodePtr node = root->children; node; node = node->next) { if (xmlStrcmp(node->name, (const xmlChar*)"IMAGE") == 0) { image = node; break; } } if (image) { xmlChar* width = xmlGetProp(image, (const xmlChar*)"width"); int newWidth = std::stoi((char*)width) + 10; xmlSetProp(image, (const xmlChar*)"width", (const xmlChar*)std::to_string(newWidth).c_str()); xmlFree(width); } xmlChar* xmlBuf; int size; xmlDocDumpMemory(doc, &xmlBuf, &size); zip_file_replace(newZip, zip_name_locate(newZip, name, 0), zip_buffer_create((char*)xmlBuf, size), 0); xmlFreeDoc(doc); } delete[] buf; } zip_close(newZip); } void close() { if (zip) zip_close(zip); } }; int main() { KraHandler handler("example.kra"); handler.open(); handler.decodeRead(); handler.printProperties(); handler.write("modified.kra"); return 0; } // ===== end task-344 .KRA ===== // ===== task-346 .KSH [C++] ===== #include #include #include #include #include #include class KSHFile { private: std::map headerProps; std::vector> bodyMeasures; // Each measure's props std::vector bodyChartLinesPerMeasure; // Parallel vector for chart lines (simplified) std::vector comments; std::vector definitions; public: KSHFile(const std::string& filepath = "") { if (!filepath.empty()) { read(filepath); } } void read(const std::string& filepath) { std::ifstream file(filepath, std::ios::in | std::ios::binary); // For BOM handling if (!file) { std::cerr << "Failed to open file." << std::endl; return; } // Skip BOM if present char bom[3]; file.read(bom, 3); if (!(bom[0] == (char)0xEF && bom[1] == (char)0xBB && bom[2] == (char)0xBF)) { file.seekg(0); } std::string line; bool inBody = false; std::map currentMeasure; std::vector currentChartLines; int measureIndex = -1; while (std::getline(file, line)) { line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); // Trim CR if (line.empty()) continue; if (line.substr(0, 2) == "//") { comments.push_back(line); continue; } if (line == "--") { if (!currentMeasure.empty() || !currentChartLines.empty()) { bodyMeasures.push_back(currentMeasure); bodyChartLinesPerMeasure.push_back(currentChartLines); } currentMeasure.clear(); currentChartLines.clear(); inBody = true; measureIndex++; continue; } if (line.substr(0, 7) == "#define") { definitions.push_back(line); continue; } size_t eqPos = line.find('='); if (eqPos != std::string::npos) { std::string key = line.substr(0, eqPos); std::string value = line.substr(eqPos + 1); // Trim spaces key.erase(0, key.find_first_not_of(" \t")); key.erase(key.find_last_not_of(" \t") + 1); value.erase(0, value.find_first_not_of(" \t")); value.erase(value.find_last_not_of(" \t") + 1); if (inBody) { currentMeasure[key] = value; } else { headerProps[key] = value; } } else { if (inBody) { currentChartLines.push_back(line); } } } if (!currentMeasure.empty() || !currentChartLines.empty()) { bodyMeasures.push_back(currentMeasure); bodyChartLinesPerMeasure.push_back(currentChartLines); } } void printProperties() { std::cout << "Header Properties:" << std::endl; for (const auto& pair : headerProps) { std::cout << pair.first << ": " << pair.second << std::endl; } std::cout << "\nBody Measures:" << std::endl; for (size_t i = 0; i < bodyMeasures.size(); ++i) { std::cout << "Measure " << (i + 1) << ":" << std::endl; for (const auto& pair : bodyMeasures[i]) { std::cout << " " << pair.first << ": " << pair.second << std::endl; } std::cout << " chart_lines:" << std::endl; for (const auto& cl : bodyChartLinesPerMeasure[i]) { std::cout << " " << cl << std::endl; } } if (!definitions.empty()) { std::cout << "\nDefinitions:" << std::endl; for (const auto& def : definitions) { std::cout << def << std::endl; } } if (!comments.empty()) { std::cout << "\nComments:" << std::endl; for (const auto& comment : comments) { std::cout << comment << std::endl; } } } void write(const std::string& filepath) { std::ofstream file(filepath, std::ios::out | std::ios::binary); if (!file) { std::cerr << "Failed to write file." << std::endl; return; } // Write BOM file << (char)0xEF << (char)0xBB << (char)0xBF; // Header for (const auto& pair : headerProps) { file << pair.first << "=" << pair.second << "\n"; } // Definitions for (const auto& def : definitions) { file << def << "\n"; } // Body for (size_t i = 0; i < bodyMeasures.size(); ++i) { file << "--\n"; for (const auto& pair : bodyMeasures[i]) { file << pair.first << "=" << pair.second << "\n"; } for (const auto& cl : bodyChartLinesPerMeasure[i]) { file << cl << "\n"; } } // Comments not written } }; int main() { KSHFile ksh("example.ksh"); ksh.printProperties(); ksh.write("output.ksh"); return 0; } // ===== end task-346 .KSH ===== // ===== task-347 .KT [C] ===== #include #include #include #include typedef struct { uint8_t identifier[12]; uint32_t vkFormat; uint32_t typeSize; uint32_t pixelWidth; uint32_t pixelHeight; uint32_t pixelDepth; uint32_t layerCount; uint32_t faceCount; uint32_t levelCount; uint32_t supercompressionScheme; uint32_t dfdByteOffset; uint32_t dfdByteLength; uint32_t kvdByteOffset; uint32_t kvdByteLength; uint64_t sgdByteOffset; uint64_t sgdByteLength; struct Level { uint64_t byteOffset; uint64_t byteLength; uint64_t uncompressedByteLength; } *levelIndex; } KTFile; void read_kt_file(const char *filename, KTFile *kt) { FILE *f = fopen(filename, "rb"); if (!f) { perror("Error opening file"); exit(1); } fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); memcpy(kt->identifier, data, 12); memcpy(&kt->vkFormat, data + 12, 4); memcpy(&kt->typeSize, data + 16, 4); memcpy(&kt->pixelWidth, data + 20, 4); memcpy(&kt->pixelHeight, data + 24, 4); memcpy(&kt->pixelDepth, data + 28, 4); memcpy(&kt->layerCount, data + 32, 4); memcpy(&kt->faceCount, data + 36, 4); memcpy(&kt->levelCount, data + 40, 4); memcpy(&kt->supercompressionScheme, data + 44, 4); memcpy(&kt->dfdByteOffset, data + 48, 4); memcpy(&kt->dfdByteLength, data + 52, 4); memcpy(&kt->kvdByteOffset, data + 56, 4); memcpy(&kt->kvdByteLength, data + 60, 4); memcpy(&kt->sgdByteOffset, data + 64, 8); memcpy(&kt->sgdByteLength, data + 72, 8); kt->levelIndex = malloc(kt->levelCount * sizeof(struct Level)); for (uint32_t i = 0; i < kt->levelCount; i++) { size_t base = 80 + i * 24; memcpy(&kt->levelIndex[i].byteOffset, data + base, 8); memcpy(&kt->levelIndex[i].byteLength, data + base + 8, 8); memcpy(&kt->levelIndex[i].uncompressedByteLength, data + base + 16, 8); } free(data); } void print_kt_properties(const KTFile *kt) { printf("KT File Properties:\n"); printf("identifier: "); for (int i = 0; i < 12; i++) { printf("%u ", kt->identifier[i]); } printf("\n"); printf("vkFormat: %u\n", kt->vkFormat); printf("typeSize: %u\n", kt->typeSize); printf("pixelWidth: %u\n", kt->pixelWidth); printf("pixelHeight: %u\n", kt->pixelHeight); printf("pixelDepth: %u\n", kt->pixelDepth); printf("layerCount: %u\n", kt->layerCount); printf("faceCount: %u\n", kt->faceCount); printf("levelCount: %u\n", kt->levelCount); printf("supercompressionScheme: %u\n", kt->supercompressionScheme); printf("dfdByteOffset: %u\n", kt->dfdByteOffset); printf("dfdByteLength: %u\n", kt->dfdByteLength); printf("kvdByteOffset: %u\n", kt->kvdByteOffset); printf("kvdByteLength: %u\n", kt->kvdByteLength); printf("sgdByteOffset: %lu\n", kt->sgdByteOffset); printf("sgdByteLength: %lu\n", kt->sgdByteLength); printf("levelIndex:\n"); for (uint32_t i = 0; i < kt->levelCount; i++) { printf(" Level %u:\n", i); printf(" byteOffset: %lu\n", kt->levelIndex[i].byteOffset); printf(" byteLength: %lu\n", kt->levelIndex[i].byteLength); printf(" uncompressedByteLength: %lu\n", kt->levelIndex[i].uncompressedByteLength); } } void write_kt_file(const char *output_filename, const KTFile *kt) { size_t header_size = 80 + kt->levelCount * 24; uint8_t *header = malloc(header_size); memcpy(header, kt->identifier, 12); memcpy(header + 12, &kt->vkFormat, 4); memcpy(header + 16, &kt->typeSize, 4); memcpy(header + 20, &kt->pixelWidth, 4); memcpy(header + 24, &kt->pixelHeight, 4); memcpy(header + 28, &kt->pixelDepth, 4); memcpy(header + 32, &kt->layerCount, 4); memcpy(header + 36, &kt->faceCount, 4); memcpy(header + 40, &kt->levelCount, 4); memcpy(header + 44, &kt->supercompressionScheme, 4); memcpy(header + 48, &kt->dfdByteOffset, 4); memcpy(header + 52, &kt->dfdByteLength, 4); memcpy(header + 56, &kt->kvdByteOffset, 4); memcpy(header + 60, &kt->kvdByteLength, 4); memcpy(header + 64, &kt->sgdByteOffset, 8); memcpy(header + 72, &kt->sgdByteLength, 8); for (uint32_t i = 0; i < kt->levelCount; i++) { size_t base = 80 + i * 24; memcpy(header + base, &kt->levelIndex[i].byteOffset, 8); memcpy(header + base + 8, &kt->levelIndex[i].byteLength, 8); memcpy(header + base + 16, &kt->levelIndex[i].uncompressedByteLength, 8); } FILE *f = fopen(output_filename, "wb"); if (!f) { perror("Error opening output file"); exit(1); } fwrite(header, 1, header_size, f); fclose(f); free(header); printf("Written to %s\n", output_filename); } void free_kt(KTFile *kt) { free(kt->levelIndex); } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: %s input.kt [output.kt]\n", argv[0]); return 1; } KTFile kt; read_kt_file(argv[1], &kt); print_kt_properties(&kt); if (argc > 2) { write_kt_file(argv[2], &kt); } free_kt(&kt); return 0; } // ===== end task-347 .KT ===== // ===== task-348 .KV [C++] ===== #include #include #include #include #include #include class KVFileHandler { private: std::string filepath; std::map simpleProps; std::map> listProps; std::map>> nestedProps; std::string content; public: KVFileHandler(const std::string& fp) : filepath(fp) { parse(); } void parse() { std::ifstream file(filepath); if (!file) { std::cerr << "Error opening file" << std::endl; return; } std::string line; content = ""; bool inCanvas = false; std::map> directives; directives["imports"] = {}; directives["sets"] = {}; directives["includes"] = {}; nestedProps["directives"] = directives; listProps["class_rules"] = {}; listProps["dynamic_classes"] = {}; listProps["templates"] = {}; listProps["property_defs"] = {}; listProps["event_bindings"] = {}; listProps["canvas_instructions"] = {}; listProps["ids"] = {}; listProps["expressions"] = {}; simpleProps["header"] = ""; simpleProps["root_widget"] = ""; while (std::getline(file, line)) { content += line + "\n"; line = std::regex_replace(line, std::regex("^ +| +$|( )+"), "$1"); // Trim if (line.find("#:kivy") == 0) { simpleProps["header"] = line; } else if (line.find("#:import") == 0) { nestedProps["directives"]["imports"].push_back(line); } else if (line.find("#:set") == 0) { nestedProps["directives"]["sets"].push_back(line); } else if (line.find("#:include") == 0) { nestedProps["directives"]["includes"].push_back(line); } else if (std::regex_match(line, std::regex("^[A-Z][a-zA-Z0-9_]*:$")) && !inCanvas) { simpleProps["root_widget"] = line.substr(0, line.size() - 1); } else if (std::regex_match(line, std::regex("^<[a-zA-Z0-9_, ]+>:$"))) { listProps["class_rules"].push_back(line); } else if (std::regex_match(line, std::regex("^<[a-zA-Z0-9_]+@[a-zA-Z0-9_+]+>:$"))) { listProps["dynamic_classes"].push_back(line); } else if (std::regex_match(line, std::regex("^\\[[a-zA-Z0-9_]+@[a-zA-Z0-9_,+]+]:$"))) { listProps["templates"].push_back(line); } else if (line.find(':') != std::string::npos && line.find("on_") != 0 && !inCanvas) { listProps["property_defs"].push_back(line); } else if (line.find("on_") == 0 && line.find(':') != std::string::npos) { listProps["event_bindings"].push_back(line); } else if (line == "canvas:" || line == "canvas.before:" || line == "canvas.after:") { inCanvas = true; listProps["canvas_instructions"].push_back(line); } else if (inCanvas && (line[0] == '-' || line == "Clear")) { inCanvas = false; } else if (inCanvas) { listProps["canvas_instructions"].push_back(line); } else if (line.find("id:") == 0) { listProps["ids"].push_back(line); } if (std::regex_search(line, std::regex("(self\\.|root\\.|app\\.|f[\"'])"))) { listProps["expressions"].push_back(line); } } file.close(); } void printProperties() { // Simple console print (not JSON, as C++ std doesn't have built-in) std::cout << "header: " << simpleProps["header"] << std::endl; std::cout << "root_widget: " << simpleProps["root_widget"] << std::endl; std::cout << "directives.imports: "; for (auto& v : nestedProps["directives"]["imports"]) std::cout << v << " "; std::cout << std::endl; // Repeat for others... std::cout << "directives.sets: "; for (auto& v : nestedProps["directives"]["sets"]) std::cout << v << " "; std::cout << std::endl; std::cout << "directives.includes: "; for (auto& v : nestedProps["directives"]["includes"]) std::cout << v << " "; std::cout << std::endl; std::cout << "class_rules: "; for (auto& v : listProps["class_rules"]) std::cout << v << " "; std::cout << std::endl; std::cout << "dynamic_classes: "; for (auto& v : listProps["dynamic_classes"]) std::cout << v << " "; std::cout << std::endl; std::cout << "templates: "; for (auto& v : listProps["templates"]) std::cout << v << " "; std::cout << std::endl; std::cout << "property_defs: "; for (auto& v : listProps["property_defs"]) std::cout << v << " "; std::cout << std::endl; std::cout << "event_bindings: "; for (auto& v : listProps["event_bindings"]) std::cout << v << " "; std::cout << std::endl; std::cout << "canvas_instructions: "; for (auto& v : listProps["canvas_instructions"]) std::cout << v << " "; std::cout << std::endl; std::cout << "ids: "; for (auto& v : listProps["ids"]) std::cout << v << " "; std::cout << std::endl; std::cout << "expressions: "; for (auto& v : listProps["expressions"]) std::cout << v << " "; std::cout << std::endl; } void write(const std::string& newFilepath = "") { std::string outPath = newFilepath.empty() ? filepath : newFilepath; std::ofstream file(outPath); if (file) { file << content; file.close(); } else { std::cerr << "Error writing file" << std::endl; } } }; // Example usage: // int main() { // KVFileHandler handler("example.kv"); // handler.printProperties(); // handler.write("modified.kv"); // return 0; // } // ===== end task-348 .KV ===== // ===== task-349 .LABEL [C++] ===== #include #include #include "tinyxml2.h" // Assume tinyxml2 library is linked using namespace tinyxml2; class LabelFile { private: std::string filepath; XMLDocument doc; public: LabelFile(const std::string& fp = "") : filepath(fp) { if (!fp.empty()) { open(fp); } } void open(const std::string& fp) { if (doc.LoadFile(fp.c_str()) != XML_SUCCESS) { std::cerr << "Error loading file." << std::endl; } filepath = fp; } void printProperties() { XMLElement* root = doc.FirstChildElement(); if (!root) { std::cout << "No file loaded." << std::endl; return; } std::cout << "Properties:" << std::endl; std::cout << "Label Type: " << root->Name() << std::endl; std::cout << "Version: " << (root->Attribute("Version") ? root->Attribute("Version") : "N/A") << std::endl; std::cout << "Units: " << (root->Attribute("Units") ? root->Attribute("Units") : "N/A") << std::endl; std::cout << "PaperOrientation: " << (root->FirstChildElement("PaperOrientation") ? root->FirstChildElement("PaperOrientation")->GetText() : "N/A") << std::endl; std::cout << "Id: " << (root->FirstChildElement("Id") ? root->FirstChildElement("Id")->GetText() : "N/A") << std::endl; std::cout << "PaperName: " << (root->FirstChildElement("PaperName") ? root->FirstChildElement("PaperName")->GetText() : "N/A") << std::endl; XMLElement* drawCommands = root->FirstChildElement("DrawCommands"); if (drawCommands) { std::cout << "DrawCommands:" << std::endl; for (XMLElement* cmd = drawCommands->FirstChildElement(); cmd; cmd = cmd->NextSiblingElement()) { std::cout << " - " << cmd->Name() << ": "; for (const XMLAttribute* attr = cmd->FirstAttribute(); attr; attr = attr->Next()) { std::cout << attr->Name() << "=" << attr->Value() << ", "; } std::cout << std::endl; } } int idx = 1; for (XMLElement* obj = root->FirstChildElement("ObjectInfo"); obj; obj = obj->NextSiblingElement("ObjectInfo"), ++idx) { std::cout << "ObjectInfo " << idx << ":" << std::endl; XMLElement* textObj = obj->FirstChildElement("TextObject"); if (textObj) { std::cout << " Type: TextObject" << std::endl; std::cout << " Name: " << (textObj->FirstChildElement("Name") ? textObj->FirstChildElement("Name")->GetText() : "N/A") << std::endl; XMLElement* foreColor = textObj->FirstChildElement("ForeColor"); if (foreColor) { std::cout << " ForeColor: Alpha=" << foreColor->Attribute("Alpha") << ", Red=" << foreColor->Attribute("Red") << ", Green=" << foreColor->Attribute("Green") << ", Blue=" << foreColor->Attribute("Blue") << std::endl; } XMLElement* backColor = textObj->FirstChildElement("BackColor"); if (backColor) { std::cout << " BackColor: Alpha=" << backColor->Attribute("Alpha") << ", Red=" << backColor->Attribute("Red") << ", Green=" << backColor->Attribute("Green") << ", Blue=" << backColor->Attribute("Blue") << std::endl; } std::cout << " LinkedObjectName: " << (textObj->FirstChildElement("LinkedObjectName") ? textObj->FirstChildElement("LinkedObjectName")->GetText() : "N/A") << std::endl; std::cout << " Rotation: " << (textObj->FirstChildElement("Rotation") ? textObj->FirstChildElement("Rotation")->GetText() : "N/A") << std::endl; std::cout << " IsMirrored: " << (textObj->FirstChildElement("IsMirrored") ? textObj->FirstChildElement("IsMirrored")->GetText() : "N/A") << std::endl; std::cout << " IsVariable: " << (textObj->FirstChildElement("IsVariable") ? textObj->FirstChildElement("IsVariable")->GetText() : "N/A") << std::endl; std::cout << " HorizontalAlignment: " << (textObj->FirstChildElement("HorizontalAlignment") ? textObj->FirstChildElement("HorizontalAlignment")->GetText() : "N/A") << std::endl; std::cout << " VerticalAlignment: " << (textObj->FirstChildElement("VerticalAlignment") ? textObj->FirstChildElement("VerticalAlignment")->GetText() : "N/A") << std::endl; std::cout << " TextFitMode: " << (textObj->FirstChildElement("TextFitMode") ? textObj->FirstChildElement("TextFitMode")->GetText() : "N/A") << std::endl; std::cout << " UseFullFontHeight: " << (textObj->FirstChildElement("UseFullFontHeight") ? textObj->FirstChildElement("UseFullFontHeight")->GetText() : "N/A") << std::endl; std::cout << " Verticalized: " << (textObj->FirstChildElement("Verticalized") ? textObj->FirstChildElement("Verticalized")->GetText() : "N/A") << std::endl; XMLElement* styledText = textObj->FirstChildElement("StyledText"); if (styledText) { std::cout << " StyledText:" << std::endl; for (XMLElement* el = styledText->FirstChildElement("Element"); el; el = el->NextSiblingElement("Element")) { std::cout << " String: " << (el->FirstChildElement("String") ? el->FirstChildElement("String")->GetText() : "N/A") << std::endl; XMLElement* attrs = el->FirstChildElement("Attributes"); XMLElement* font = attrs->FirstChildElement("Font"); if (font) { std::cout << " Font: Family=" << font->Attribute("Family") << ", Size=" << font->Attribute("Size") << ", Bold=" << font->Attribute("Bold") << ", Italic=" << font->Attribute("Italic") << ", Underline=" << font->Attribute("Underline") << ", Strikeout=" << font->Attribute("Strikeout") << std::endl; } XMLElement* color = attrs->FirstChildElement("ForeColor"); if (color) { std::cout << " ForeColor: Alpha=" << color->Attribute("Alpha") << ", Red=" << color->Attribute("Red") << ", Green=" << color->Attribute("Green") << ", Blue=" << color->Attribute("Blue") << std::endl; } } } } // Add for other object types if needed XMLElement* bounds = obj->FirstChildElement("Bounds"); if (bounds) { std::cout << " Bounds: X=" << bounds->Attribute("X") << ", Y=" << bounds->Attribute("Y") << ", Width=" << bounds->Attribute("Width") << ", Height=" << bounds->Attribute("Height") << std::endl; } } } void write(const std::string& newFilepath = "") { const std::string fp = newFilepath.empty() ? filepath : newFilepath; if (doc.NoChildren()) { XMLElement* root = doc.NewElement("DieCutLabel"); root->SetAttribute("Version", "8.0"); root->SetAttribute("Units", "twips"); doc.InsertFirstChild(root); XMLElement* orientation = doc.NewElement("PaperOrientation"); orientation->SetText("Landscape"); root->InsertEndChild(orientation); XMLElement* id = doc.NewElement("Id"); id->SetText("Address"); root->InsertEndChild(id); XMLElement* paperName = doc.NewElement("PaperName"); paperName->SetText("30252 Address"); root->InsertEndChild(paperName); XMLElement* drawCommands = doc.NewElement("DrawCommands"); root->InsertEndChild(drawCommands); XMLElement* roundRect = doc.NewElement("RoundRectangle"); roundRect->SetAttribute("X", "0"); roundRect->SetAttribute("Y", "0"); roundRect->SetAttribute("Width", "1581"); roundRect->SetAttribute("Height", "5040"); roundRect->SetAttribute("Rx", "270"); roundRect->SetAttribute("Ry", "270"); drawCommands->InsertEndChild(roundRect); } doc.SaveFile(fp.c_str()); } }; // Example usage: // int main() { // LabelFile lf("example.label"); // lf.printProperties(); // lf.write("new.label"); // return 0; // } // ===== end task-349 .LABEL ===== // ===== task-350 .LATEX [C++] ===== #include #include #include #include #include #include #include class LatexFile { private: std::string filepath; struct stat fileStat; public: LatexFile(const std::string& fp) : filepath(fp) { if (filepath.length() < 6 || strcasecmp(filepath.substr(filepath.length() - 6).c_str(), ".latex") != 0) { throw std::invalid_argument("The file must have a .LATEX extension."); } if (stat(filepath.c_str(), &fileStat) != 0) { throw std::runtime_error("Failed to get file stats."); } } void printProperties() const { std::cout << "Mode: " << std::oct << fileStat.st_mode << std::dec << std::endl; std::cout << "Inode Number: " << fileStat.st_ino << std::endl; std::cout << "Device ID: " << fileStat.st_dev << std::endl; std::cout << "Number of Hard Links: " << fileStat.st_nlink << std::endl; std::cout << "User ID of Owner: " << fileStat.st_uid << std::endl; std::cout << "Group ID of Owner: " << fileStat.st_gid << std::endl; std::cout << "File Size (bytes): " << fileStat.st_size << std::endl; std::cout << "Last Access Time: " << std::ctime(&fileStat.st_atime); std::cout << "Last Modification Time: " << std::ctime(&fileStat.st_mtime); std::cout << "Creation Time: " << std::ctime(&fileStat.st_ctime); } std::string read() const { std::ifstream file(filepath, std::ios::in | std::ios::binary); if (!file) { throw std::runtime_error("Failed to open file for reading."); } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); return content; } void write(const std::string& content) const { std::ofstream file(filepath, std::ios::out | std::ios::binary); if (!file) { throw std::runtime_error("Failed to open file for writing."); } file << content; } }; // ===== end task-350 .LATEX ===== // ===== task-351 .LBR [C] ===== #include #include #include #include #include #define SECTOR_SIZE 128 #define ENTRY_SIZE 32 #define PAD_BYTE 0x1A typedef struct { char *filename; struct Member *members; int num_members; } LBRFile; typedef struct Member { char *status; char name[9]; char ext[4]; uint16_t start_sector; uint16_t length_sectors; uint16_t crc; char create_date[11]; char update_date[11]; char create_time[9]; char update_time[9]; uint8_t pad_length; uint8_t reserved; struct Member *next; } Member; uint16_t crc16_ccitt(const uint8_t *data, size_t len) { uint16_t crc = 0x0000; for (size_t i = 0; i < len; i++) { crc ^= (data[i] << 8); for (int j = 0; j < 8; j++) { crc = (crc & 0x8000) ? ((crc << 1) ^ 0x1021) : (crc << 1); } } return crc; } void parse_date(uint16_t days, char *buf) { if (days == 0) { strcpy(buf, "Unavailable"); return; } struct tm base = {.tm_year = 77, .tm_mon = 11, .tm_mday = 31, .tm_hour = 0, .tm_min = 0, .tm_sec = 0}; time_t base_time = mktime(&base) + days * 86400; struct tm *t = localtime(&base_time); sprintf(buf, "%04d-%02d-%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday); } void parse_time(uint16_t word, char *buf) { uint8_t hour = (word >> 11) & 0x1F; uint8_t min = (word >> 5) & 0x3F; uint8_t sec = (word & 0x1F) * 2; sprintf(buf, "%02d:%02d:%02d", hour, min, sec); } void lbr_read(LBRFile *lbr) { FILE *f = fopen(lbr->filename, "rb"); if (!f) return; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); uint16_t dir_length_sectors = *(uint16_t*)(data + 14); int dir_size = dir_length_sectors * SECTOR_SIZE; int offset = 0; Member *last = NULL; while (offset < dir_size) { uint8_t status = data[offset]; if (status == 0xFF) break; if (status == 0x00 || status == 0xFE) { Member *m = malloc(sizeof(Member)); memset(m, 0, sizeof(Member)); m->status = strdup(status == 0x00 ? "Active" : "Deleted"); strncpy(m->name, (char*)(data + offset + 1), 8); m->name[8] = '\0'; char *trim = strchr(m->name, ' '); if (trim) *trim = '\0'; strncpy(m->ext, (char*)(data + offset + 9), 3); m->ext[3] = '\0'; trim = strchr(m->ext, ' '); if (trim) *trim = '\0'; m->start_sector = *(uint16_t*)(data + offset + 12); m->length_sectors = *(uint16_t*)(data + offset + 14); m->crc = *(uint16_t*)(data + offset + 16); uint16_t create_date_val = *(uint16_t*)(data + offset + 18); uint16_t update_date_val = *(uint16_t*)(data + offset + 20); uint16_t create_time_val = *(uint16_t*)(data + offset + 22); uint16_t update_time_val = *(uint16_t*)(data + offset + 24); m->pad_length = data[offset + 26]; m->reserved = data[offset + 27]; parse_date(create_date_val, m->create_date); parse_date(update_date_val, m->update_date); parse_time(create_time_val, m->create_time); parse_time(update_time_val, m->update_time); m->next = NULL; if (last) last->next = m; else lbr->members = m; last = m; lbr->num_members++; } offset += ENTRY_SIZE; } free(data); } void lbr_print_properties(LBRFile *lbr) { Member *m = lbr->members; while (m) { printf("Member: %s.%s (Status: %s)\n", m->name, m->ext, m->status); printf(" Start sector: %u\n", m->start_sector); printf(" Length sectors: %u\n", m->length_sectors); printf(" Crc: %u\n", m->crc); printf(" Create date: %s\n", m->create_date); printf(" Update date: %s\n", m->update_date); printf(" Create time: %s\n", m->create_time); printf(" Update time: %s\n", m->update_time); printf(" Pad length: %u\n", m->pad_length); printf(" Reserved: %u\n\n", m->reserved); m = m->next; } } void lbr_write(LBRFile *lbr, const char *new_filename) { // Simplified: read original, rewrite directory FILE *f = fopen(lbr->filename, "rb"); if (!f) return; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); uint8_t *dir_data = malloc(ENTRY_SIZE * (lbr->num_members + 1)); memset(dir_data, 0, ENTRY_SIZE * (lbr->num_members + 1)); int offset = 0; Member *m = lbr->members; while (m) { dir_data[offset] = strcmp(m->status, "Active") == 0 ? 0x00 : 0xFE; strncpy((char*)(dir_data + offset + 1), m->name, 8); for (int i = strlen(m->name); i < 8; i++) dir_data[offset + 1 + i] = ' '; strncpy((char*)(dir_data + offset + 9), m->ext, 3); for (int i = strlen(m->ext); i < 3; i++) dir_data[offset + 9 + i] = ' '; *(uint16_t*)(dir_data + offset + 12) = m->start_sector; *(uint16_t*)(dir_data + offset + 14) = m->length_sectors; *(uint16_t*)(dir_data + offset + 16) = m->crc; // Placeholder 0 for dates/times *(uint16_t*)(dir_data + offset + 18) = 0; *(uint16_t*)(dir_data + offset + 20) = 0; *(uint16_t*)(dir_data + offset + 22) = 0; *(uint16_t*)(dir_data + offset + 24) = 0; dir_data[offset + 26] = m->pad_length; dir_data[offset + 27] = m->reserved; offset += ENTRY_SIZE; m = m->next; } dir_data[offset] = 0xFF; int dir_length = offset + ENTRY_SIZE; int dir_sectors = (dir_length + SECTOR_SIZE - 1) / SECTOR_SIZE; uint8_t *padded_dir = calloc(dir_sectors * SECTOR_SIZE, 1); memcpy(padded_dir, dir_data, dir_length); *(uint16_t*)(padded_dir + 14) = dir_sectors; FILE *out = fopen(new_filename ? new_filename : lbr->filename, "wb"); fwrite(padded_dir, 1, dir_sectors * SECTOR_SIZE, out); fwrite(data + dir_sectors * SECTOR_SIZE, 1, size - dir_sectors * SECTOR_SIZE, out); fclose(out); free(dir_data); free(padded_dir); free(data); } LBRFile *lbr_open(const char *filename) { LBRFile *lbr = malloc(sizeof(LBRFile)); lbr->filename = strdup(filename); lbr->members = NULL; lbr->num_members = 0; lbr_read(lbr); return lbr; } void lbr_free(LBRFile *lbr) { Member *m = lbr->members; while (m) { Member *next = m->next; free(m->status); free(m); m = next; } free(lbr->filename); free(lbr); } // Example usage: // int main() { // LBRFile *lbr = lbr_open("example.lbr"); // lbr_print_properties(lbr); // lbr_write(lbr, "modified.lbr"); // lbr_free(lbr); // return 0; // } // ===== end task-351 .LBR ===== // ===== task-352 .LDB [C] ===== #include #include #include #define RECORD_SIZE 64 #define FIELD_SIZE 32 typedef struct { char *filename; struct Entry *properties; int count; } LDBHandler; typedef struct Entry { char computerName[FIELD_SIZE + 1]; char userName[FIELD_SIZE + 1]; } Entry; LDBHandler* createLDBHandler(const char *filename) { LDBHandler *handler = (LDBHandler*)malloc(sizeof(LDBHandler)); handler->filename = strdup(filename); handler->properties = NULL; handler->count = 0; return handler; } void destroyLDBHandler(LDBHandler *handler) { if (handler->properties) free(handler->properties); free(handler->filename); free(handler); } int readLDB(LDBHandler *handler) { FILE *file = fopen(handler->filename, "rb"); if (!file) { perror("File not found"); return -1; } fseek(file, 0, SEEK_END); long size = ftell(file); fseek(file, 0, SEEK_SET); char *data = (char*)malloc(size); fread(data, 1, size, file); fclose(file); int maxEntries = size / RECORD_SIZE; handler->properties = (Entry*)realloc(handler->properties, maxEntries * sizeof(Entry)); handler->count = 0; for (int i = 0; i < size; i += RECORD_SIZE) { char record[RECORD_SIZE]; memcpy(record, data + i, RECORD_SIZE); char comp[FIELD_SIZE + 1] = {0}; char user[FIELD_SIZE + 1] = {0}; strncpy(comp, record, FIELD_SIZE); strncpy(user, record + FIELD_SIZE, FIELD_SIZE); // Trim nulls and spaces comp[strcspn(comp, "\0 ")] = 0; user[strcspn(user, "\0 ")] = 0; if (strlen(comp) > 0 || strlen(user) > 0) { strcpy(handler->properties[handler->count].computerName, comp); strcpy(handler->properties[handler->count].userName, user); handler->count++; } } free(data); return 0; } void printProperties(LDBHandler *handler) { if (handler->count == 0) { printf("No properties found.\n"); return; } for (int i = 0; i < handler->count; i++) { printf("Entry %d: Computer Name = %s, User Name = %s\n", i + 1, handler->properties[i].computerName, handler->properties[i].userName); } } int writeLDB(LDBHandler *handler, Entry *newProperties, int newCount) { FILE *file = fopen(handler->filename, "wb"); if (!file) { perror("Cannot write file"); return -1; } for (int i = 0; i < newCount; i++) { char record[RECORD_SIZE] = {0}; strncpy(record, newProperties[i].computerName, FIELD_SIZE); strncpy(record + FIELD_SIZE, newProperties[i].userName, FIELD_SIZE); fwrite(record, 1, RECORD_SIZE, file); } fclose(file); return 0; } // Example usage: // int main() { // LDBHandler *handler = createLDBHandler("database.ldb"); // readLDB(handler); // printProperties(handler); // Entry newProps[2] = {{"PC1", "Admin"}, {"PC2", "User"}}; // writeLDB(handler, newProps, 2); // destroyLDBHandler(handler); // return 0; // } // ===== end task-352 .LDB ===== // ===== task-353 .LDT [C++] ===== #include #include #include #include #include class LDTFile { private: std::string filepath; std::map properties; std::vector dataLines; public: LDTFile(const std::string& fp) : filepath(fp) { read(); } void read() { std::ifstream file(filepath); std::vector lines; std::string line; while (std::getline(file, line)) { // Trim line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); lines.push_back(line); } file.close(); properties["company_identification"] = lines[0]; properties["type_indicator"] = lines[1]; properties["symmetry_indicator"] = lines[2]; properties["num_c_planes"] = lines[3]; properties["dist_c_planes"] = lines[4]; properties["num_luminous_intensities"] = lines[5]; properties["dist_luminous_intensities"] = lines[6]; properties["measurement_report_num"] = lines[7]; properties["luminaire_name"] = lines[8]; properties["luminaire_num"] = lines[9]; properties["file_name"] = lines[10]; properties["date_user"] = lines[11]; properties["luminaire_length_diameter"] = lines[12]; properties["luminaire_width"] = lines[13]; properties["luminaire_height"] = lines[14]; properties["luminous_area_length_diameter"] = lines[15]; properties["luminous_area_width"] = lines[16]; properties["luminous_area_height_c0"] = lines[17]; properties["luminous_area_height_c90"] = lines[18]; properties["luminous_area_height_c180"] = lines[19]; properties["luminous_area_height_c270"] = lines[20]; properties["downward_flux_fraction"] = lines[21]; properties["light_output_ratio"] = lines[22]; properties["conversion_factor"] = lines[23]; properties["tilt_during_measurement"] = lines[24]; properties["num_lamp_sets"] = lines[25]; // Assume n=1 for simplicity; extend for multiple properties["num_lamps"] = lines[26]; properties["lamp_type"] = lines[27]; properties["luminous_flux"] = lines[28]; properties["color_appearance_temp"] = lines[29]; properties["color_rendering"] = lines[30]; properties["wattage"] = lines[31]; properties["direct_ratios"] = lines[32]; properties["angles_c"] = lines[33]; properties["angles_g"] = lines[34]; properties["tilt_angles"] = lines[35]; for (size_t i = 36; i < lines.size(); ++i) { dataLines.push_back(lines[i]); } } void printProperties() { for (const auto& pair : properties) { std::string key = pair.first; for (size_t pos = 0; (pos = key.find('_', pos)) != std::string::npos; ++pos) { key[pos] = ' '; } key[0] = toupper(key[0]); std::cout << key << ": " << pair.second << std::endl; } std::cout << "Luminous intensity distribution:" << std::endl; for (const auto& line : dataLines) { std::cout << line << std::endl; } } void write(const std::string& newFilepath = "") { std::string outPath = newFilepath.empty() ? filepath + ".new" : newFilepath; std::ofstream file(outPath); for (const auto& pair : properties) { file << pair.second << std::endl; } for (const auto& line : dataLines) { file << line << std::endl; } file.close(); std::cout << "File written to " << outPath << std::endl; } }; int main() { LDTFile ldt("sample.ldt"); ldt.printProperties(); ldt.write("modified.ldt"); return 0; } // ===== end task-353 .LDT ===== // ===== task-354 .LGR [C] ===== #include #include #include #include // Assume little-endian, no byte swap needed on x86 typedef struct { char *filename; int width; int height; int length; uint8_t *data; } PCXObject; typedef struct { char magic[4]; // Null-terminated char version[3]; // Null-terminated int32_t num_pcx; int32_t lst_version; int32_t num_lst; char **image_names; int32_t *image_types; int32_t *distances; int32_t *clippings; int32_t *trans_locs; PCXObject *pcx_objects; uint8_t end_marker[4]; FILE *file; } LGR; LGR* lgr_new() { LGR *lgr = (LGR*)malloc(sizeof(LGR)); memset(lgr, 0, sizeof(LGR)); return lgr; } void lgr_open(LGR *lgr, const char *filename) { lgr->file = fopen(filename, "rb"); } void lgr_read(LGR *lgr) { fseek(lgr->file, 0, SEEK_SET); fread(lgr->magic, 1, 3, lgr->file); lgr->magic[3] = '\0'; fread(lgr->version, 1, 2, lgr->file); lgr->version[2] = '\0'; fread(&lgr->num_pcx, sizeof(int32_t), 1, lgr->file); fread(&lgr->lst_version, sizeof(int32_t), 1, lgr->file); fread(&lgr->num_lst, sizeof(int32_t), 1, lgr->file); lgr->image_names = (char**)malloc(lgr->num_lst * sizeof(char*)); for (int i = 0; i < lgr->num_lst; i++) { lgr->image_names[i] = (char*)malloc(11); fread(lgr->image_names[i], 1, 10, lgr->file); lgr->image_names[i][10] = '\0'; // Trim null for (int j = 9; j >= 0; j--) if (lgr->image_names[i][j] == 0) lgr->image_names[i][j] = '\0'; } lgr->image_types = (int32_t*)malloc(lgr->num_lst * sizeof(int32_t)); fread(lgr->image_types, sizeof(int32_t), lgr->num_lst, lgr->file); lgr->distances = (int32_t*)malloc(lgr->num_lst * sizeof(int32_t)); fread(lgr->distances, sizeof(int32_t), lgr->num_lst, lgr->file); lgr->clippings = (int32_t*)malloc(lgr->num_lst * sizeof(int32_t)); fread(lgr->clippings, sizeof(int32_t), lgr->num_lst, lgr->file); lgr->trans_locs = (int32_t*)malloc(lgr->num_lst * sizeof(int32_t)); fread(lgr->trans_locs, sizeof(int32_t), lgr->num_lst, lgr->file); lgr->pcx_objects = (PCXObject*)malloc(lgr->num_pcx * sizeof(PCXObject)); for (int i = 0; i < lgr->num_pcx; i++) { lgr->pcx_objects[i].filename = (char*)malloc(21); fread(lgr->pcx_objects[i].filename, 1, 20, lgr->file); lgr->pcx_objects[i].filename[20] = '\0'; // Trim null for (int j = 19; j >= 0; j--) if (lgr->pcx_objects[i].filename[j] == 0) lgr->pcx_objects[i].filename[j] = '\0'; lgr->pcx_objects[i].width = 0; lgr->pcx_objects[i].height = 0; if (strcmp(lgr->version, "13") == 0) { int16_t w, h; fread(&w, sizeof(int16_t), 1, lgr->file); fread(&h, sizeof(int16_t), 1, lgr->file); lgr->pcx_objects[i].width = w; lgr->pcx_objects[i].height = h; } fread(&lgr->pcx_objects[i].length, sizeof(int32_t), 1, lgr->file); lgr->pcx_objects[i].data = (uint8_t*)malloc(lgr->pcx_objects[i].length); fread(lgr->pcx_objects[i].data, 1, lgr->pcx_objects[i].length, lgr->file); } fread(lgr->end_marker, 1, 4, lgr->file); } void lgr_write(LGR *lgr, const char *filename) { FILE *out = fopen(filename, "wb"); fwrite(lgr->magic, 1, 3, out); fwrite(lgr->version, 1, 2, out); fwrite(&lgr->num_pcx, sizeof(int32_t), 1, out); fwrite(&lgr->lst_version, sizeof(int32_t), 1, out); fwrite(&lgr->num_lst, sizeof(int32_t), 1, out); for (int i = 0; i < lgr->num_lst; i++) { fwrite(lgr->image_names[i], 1, strlen(lgr->image_names[i]), out); for (int j = strlen(lgr->image_names[i]); j < 10; j++) fputc(0, out); } fwrite(lgr->image_types, sizeof(int32_t), lgr->num_lst, out); fwrite(lgr->distances, sizeof(int32_t), lgr->num_lst, out); fwrite(lgr->clippings, sizeof(int32_t), lgr->num_lst, out); fwrite(lgr->trans_locs, sizeof(int32_t), lgr->num_lst, out); for (int i = 0; i < lgr->num_pcx; i++) { fwrite(lgr->pcx_objects[i].filename, 1, strlen(lgr->pcx_objects[i].filename), out); for (int j = strlen(lgr->pcx_objects[i].filename); j < 20; j++) fputc(0, out); if (strcmp(lgr->version, "13") == 0) { int16_t w = (int16_t)lgr->pcx_objects[i].width; int16_t h = (int16_t)lgr->pcx_objects[i].height; fwrite(&w, sizeof(int16_t), 1, out); fwrite(&h, sizeof(int16_t), 1, out); } fwrite(&lgr->pcx_objects[i].length, sizeof(int32_t), 1, out); fwrite(lgr->pcx_objects[i].data, 1, lgr->pcx_objects[i].length, out); } fwrite(lgr->end_marker, 1, 4, out); fclose(out); } void lgr_print_properties(LGR *lgr) { printf("Magic: %s\n", lgr->magic); printf("Version: %s\n", lgr->version); printf("Number of PCX files: %d\n", lgr->num_pcx); printf("Pictures.lst version: %d\n", lgr->lst_version); printf("Number of lst elements: %d\n", lgr->num_lst); printf("Image names: "); for (int i = 0; i < lgr->num_lst; i++) printf("%s%s", lgr->image_names[i], (i < lgr->num_lst - 1) ? ", " : "\n"); printf("Image types: "); for (int i = 0; i < lgr->num_lst; i++) printf("%d%s", lgr->image_types[i], (i < lgr->num_lst - 1) ? ", " : "\n"); printf("Default distances: "); for (int i = 0; i < lgr->num_lst; i++) printf("%d%s", lgr->distances[i], (i < lgr->num_lst - 1) ? ", " : "\n"); printf("Default clippings: "); for (int i = 0; i < lgr->num_lst; i++) printf("%d%s", lgr->clippings[i], (i < lgr->num_lst - 1) ? ", " : "\n"); printf("Transparent locations: "); for (int i = 0; i < lgr->num_lst; i++) printf("%d%s", lgr->trans_locs[i], (i < lgr->num_lst - 1) ? ", " : "\n"); printf("PCX objects:\n"); for (int i = 0; i < lgr->num_pcx; i++) { printf(" - Filename: %s, Width: %d, Height: %d, Length: %d\n", lgr->pcx_objects[i].filename, lgr->pcx_objects[i].width, lgr->pcx_objects[i].height, lgr->pcx_objects[i].length); } printf("End marker: [0x%02x, 0x%02x, 0x%02x, 0x%02x]\n", lgr->end_marker[0], lgr->end_marker[1], lgr->end_marker[2], lgr->end_marker[3]); } void lgr_free(LGR *lgr) { for (int i = 0; i < lgr->num_lst; i++) free(lgr->image_names[i]); free(lgr->image_names); free(lgr->image_types); free(lgr->distances); free(lgr->clippings); free(lgr->trans_locs); for (int i = 0; i < lgr->num_pcx; i++) { free(lgr->pcx_objects[i].filename); free(lgr->pcx_objects[i].data); } free(lgr->pcx_objects); if (lgr->file) fclose(lgr->file); free(lgr); } // Example usage: LGR *lgr = lgr_new(); lgr_open(lgr, "file.lgr"); lgr_read(lgr); lgr_print_properties(lgr); lgr_write(lgr, "new.lgr"); lgr_free(lgr); // ===== end task-354 .LGR ===== // ===== task-355 .LGA [C] ===== #include #include #include #include typedef struct { uint8_t header_len; uint8_t checksum; char method[6]; uint32_t comp_size; uint32_t uncomp_size; uint32_t timestamp_raw; uint8_t attr; uint8_t level; char* filename; uint16_t crc; // N/A for others in level 0 } LhaEntry; typedef struct { LhaEntry* entries; int count; } LhaHandler; LhaHandler* lha_open(const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); LhaHandler* handler = malloc(sizeof(LhaHandler)); handler->entries = NULL; handler->count = 0; int offset = 0; while (offset < size) { uint8_t header_len = data[offset]; if (header_len == 0) break; offset++; uint8_t checksum = data[offset]; offset++; char method[6]; memcpy(method, &data[offset], 5); method[5] = '\0'; offset += 5; uint32_t comp_size = *(uint32_t*)(&data[offset]); offset += 4; uint32_t uncomp_size = *(uint32_t*)(&data[offset]); offset += 4; uint32_t timestamp_raw = *(uint32_t*)(&data[offset]); offset += 4; uint8_t attr = data[offset]; offset++; uint8_t level = data[offset]; offset++; if (level == 0) { uint8_t name_len = data[offset]; offset++; char* name = malloc(name_len + 1); memcpy(name, &data[offset], name_len); name[name_len] = '\0'; offset += name_len; uint16_t crc = *(uint16_t*)(&data[offset]); offset += 2; handler->entries = realloc(handler->entries, sizeof(LhaEntry) * (handler->count + 1)); LhaEntry* entry = &handler->entries[handler->count++]; entry->header_len = header_len; entry->checksum = checksum; strcpy(entry->method, method); entry->comp_size = comp_size; entry->uncomp_size = uncomp_size; entry->timestamp_raw = timestamp_raw; entry->attr = attr; entry->level = level; entry->filename = name; entry->crc = crc; offset += comp_size; } else { free(data); // Cleanup entries for (int i = 0; i < handler->count; i++) free(handler->entries[i].filename); free(handler->entries); free(handler); return NULL; // Only level 0 } } free(data); return handler; } void lha_print_properties(LhaHandler* handler) { for (int i = 0; i < handler->count; i++) { LhaEntry* e = &handler->entries[i]; printf("Entry Properties:\n"); printf("Header Length: %u\n", e->header_len); printf("Header Checksum: %u\n", e->checksum); printf("Compression Method: %s\n", e->method); printf("Compressed Size: %u\n", e->comp_size); printf("Uncompressed Size: %u\n", e->uncomp_size); printf("File Timestamp (raw): %u\n", e->timestamp_raw); printf("Attributes: %u\n", e->attr); printf("Level: %u\n", e->level); printf("Filename: %s\n", e->filename); printf("Uncompressed CRC: %u\n", e->crc); printf("OS Type: N/A\n"); printf("Extended Header Size: N/A\n"); printf("Extended Headers: N/A\n"); printf("---\n"); } } void lha_write(const char* output_filename, const char* filename_to_add, const uint8_t* content, size_t content_size) { // Simple level 0 write, single entry, uncompressed FILE* f = fopen(output_filename, "wb"); if (!f) return; const char* name = filename_to_add; uint32_t uncomp_size = (uint32_t)content_size; uint32_t comp_size = uncomp_size; char method[6] = "-lh0-"; uint8_t attr = 0x20; uint8_t level = 0; uint16_t crc = 0; // Dummy uint32_t timestamp_raw = 0; // Dummy uint8_t name_len = strlen(name); uint8_t header_size_inner = 20 + 1 + name_len; uint8_t header_len = header_size_inner + 1; uint8_t checksum = 0; // Dummy fwrite(&header_len, 1, 1, f); fwrite(&checksum, 1, 1, f); fwrite(method, 5, 1, f); fwrite(&comp_size, 4, 1, f); fwrite(&uncomp_size, 4, 1, f); fwrite(×tamp_raw, 4, 1, f); fwrite(&attr, 1, 1, f); fwrite(&level, 1, 1, f); fwrite(&name_len, 1, 1, f); fwrite(name, name_len, 1, f); fwrite(&crc, 2, 1, f); fwrite(content, content_size, 1, f); uint8_t end = 0; fwrite(&end, 1, 1, f); fclose(f); } void lha_close(LhaHandler* handler) { for (int i = 0; i < handler->count; i++) free(handler->entries[i].filename); free(handler->entries); free(handler); } // Example usage: // LhaHandler* handler = lha_open("example.lha"); // lha_print_properties(handler); // lha_close(handler); // uint8_t content[] = "Hello"; // lha_write("new.lha", "test.txt", (uint8_t*)content, 5); // ===== end task-355 .LGA ===== // ===== task-356 .LISP [C] ===== #include #include #include #include #define MAX_CONTENT_SIZE 1048576 // 1MB max for simplicity typedef struct { char *filepath; char *content; char *properties[6][2]; // Key-value pairs } LispFileHandler; void init_handler(LispFileHandler *handler, const char *filepath) { handler->filepath = strdup(filepath); handler->content = NULL; for (int i = 0; i < 6; i++) { handler->properties[i][0] = NULL; handler->properties[i][1] = NULL; } } int read_and_decode(LispFileHandler *handler) { FILE *file = fopen(handler->filepath, "r"); if (!file) { printf("Error opening file.\n"); return 0; } handler->content = malloc(MAX_CONTENT_SIZE); size_t len = fread(handler->content, 1, MAX_CONTENT_SIZE - 1, file); handler->content[len] = '\0'; fclose(file); // Extract properties int is_ascii = 1; for (size_t i = 0; i < len; i++) { if ((unsigned char)handler->content[i] >= 128) { is_ascii = 0; break; } } handler->properties[0][0] = strdup("Encoding"); handler->properties[0][1] = strdup(is_ascii ? "ASCII" : "UTF-8"); handler->properties[1][0] = strdup("MIME type"); handler->properties[1][1] = strdup("text/plain or application/x-lisp"); handler->properties[2][0] = strdup("Magic number/signature"); handler->properties[2][1] = strdup("None"); int has_sexpr = (strchr(handler->content, '(') && strchr(handler->content, ')')); handler->properties[3][0] = strdup("Structure"); handler->properties[3][1] = strdup(has_sexpr ? "S-expressions" : "Plain text"); handler->properties[4][0] = strdup("Content"); handler->properties[4][1] = strdup(handler->content); const char *ext = strrchr(handler->filepath, '.'); handler->properties[5][0] = strdup("File extension"); handler->properties[5][1] = strdup(ext ? ext + 1 : "none"); return 1; } void print_properties(LispFileHandler *handler) { for (int i = 0; i < 6; i++) { if (handler->properties[i][0]) { char *value = handler->properties[i][1]; if (strcmp(handler->properties[i][0], "Content") == 0) { size_t val_len = strlen(value); if (val_len > 500) { char truncated[504]; strncpy(truncated, value, 500); truncated[500] = '.'; truncated[501] = '.'; truncated[502] = '.'; truncated[503] = '\0'; printf("%s: %s\n", handler->properties[i][0], truncated); } else { printf("%s: %s\n", handler->properties[i][0], value); } } else { printf("%s: %s\n", handler->properties[i][0], value); } } } } int write_file(LispFileHandler *handler, const char *new_content) { const char *content_to_write = new_content ? new_content : handler->content; if (!content_to_write) { printf("No content to write.\n"); return 0; } FILE *file = fopen(handler->filepath, "w"); if (!file) { printf("Error opening file for write.\n"); return 0; } fprintf(file, "%s", content_to_write); fclose(file); printf("File written successfully.\n"); return 1; } void free_handler(LispFileHandler *handler) { free(handler->filepath); free(handler->content); for (int i = 0; i < 6; i++) { free(handler->properties[i][0]); free(handler->properties[i][1]); } } // Example usage: // int main() { // LispFileHandler handler; // init_handler(&handler, "example.lisp"); // if (read_and_decode(&handler)) { // print_properties(&handler); // write_file(&handler, "(defun example () (print \"Hello\"))"); // } // free_handler(&handler); // return 0; // } // ===== end task-356 .LISP ===== // ===== task-358 .LM [C] ===== #include #include #include #include #define MAX_LINE 1024 #define MAX_WORDS 10000 typedef struct Ngram { double log_prob; char *words; double backoff; // -1 if N/A struct Ngram *next; } Ngram; typedef struct { char *header; int max_order; int *ngram_counts; // array indexed by order-1 char **vocabulary; int vocab_size; char *special_tokens[3]; Ngram **ngrams; // array of lists, indexed by order-1 char *end_marker; } LMFile; LMFile *lm_create() { LMFile *lm = malloc(sizeof(LMFile)); lm->header = strdup("\\data\\"); lm->max_order = 0; lm->ngram_counts = NULL; lm->vocabulary = NULL; lm->vocab_size = 0; lm->special_tokens[0] = strdup(""); lm->special_tokens[1] = strdup(""); lm->special_tokens[2] = strdup(""); lm->ngrams = NULL; lm->end_marker = strdup("\\end\\"); return lm; } void lm_free(LMFile *lm) { free(lm->header); free(lm->ngram_counts); for (int i = 0; i < lm->vocab_size; i++) free(lm->vocabulary[i]); free(lm->vocabulary); for (int i = 0; i < 3; i++) free(lm->special_tokens[i]); for (int order = 0; order < lm->max_order; order++) { Ngram *ng = lm->ngrams[order]; while (ng) { Ngram *next = ng->next; free(ng->words); free(ng); ng = next; } } free(lm->ngrams); free(lm->end_marker); free(lm); } void lm_open_and_read(LMFile *lm, const char *filepath) { FILE *file = fopen(filepath, "r"); if (!file) { perror("Failed to open file"); return; } char line[MAX_LINE]; int section = -1; // -1: none, 0: header, >0: order while (fgets(line, MAX_LINE, file)) { char *trimmed = strtok(line, "\r\n"); if (!trimmed || strlen(trimmed) == 0) continue; if (strcmp(trimmed, "\\data\\") == 0) { section = 0; lm->header = strdup(trimmed); } else if (strstr(trimmed, "-grams:")) { sscanf(trimmed, "\\%d-grams:", §ion); lm->max_order = section > lm->max_order ? section : lm->max_order; if (!lm->ngrams) lm->ngrams = calloc(lm->max_order, sizeof(Ngram*)); if (!lm->ngram_counts) lm->ngram_counts = calloc(lm->max_order, sizeof(int)); } else if (strcmp(trimmed, "\\end\\") == 0) { lm->end_marker = strdup(trimmed); section = -1; } else if (section == 0 && strstr(trimmed, "ngram ")) { int order, count; sscanf(trimmed, "ngram %d=%d", &order, &count); lm->ngram_counts[order - 1] = count; } else if (section > 0) { double log_prob, backoff = -1.0; char words[MAX_LINE]; char *token = strtok(trimmed, " \t"); log_prob = atof(token); char *word_start = trimmed + strlen(token) + 1; char *backoff_str = strrchr(word_start, '\t'); if (backoff_str && isdigit(backoff_str[1]) || backoff_str[1] == '-') { backoff = atof(backoff_str + 1); *backoff_str = '\0'; } strcpy(words, word_start); Ngram *ng = malloc(sizeof(Ngram)); ng->log_prob = log_prob; ng->words = strdup(words); ng->backoff = backoff; ng->next = lm->ngrams[section - 1]; lm->ngrams[section - 1] = ng; char *word = strtok(words, " "); if (word && !strtok(NULL, " ")) { // unigram lm->vocabulary = realloc(lm->vocabulary, (lm->vocab_size + 1) * sizeof(char*)); lm->vocabulary[lm->vocab_size++] = strdup(word); } } } fclose(file); } void lm_print_properties(const LMFile *lm) { printf("Header: %s\n", lm->header); printf("Max n-gram Order: %d\n", lm->max_order); printf("n-gram Counts:\n"); for (int order = 1; order <= lm->max_order; order++) { printf(" Order %d: %d\n", order, lm->ngram_counts[order - 1]); } printf("Vocabulary: "); for (int i = 0; i < lm->vocab_size; i++) { printf("%s%s", lm->vocabulary[i], i < lm->vocab_size - 1 ? ", " : "\n"); } printf("Special Tokens: %s, %s, %s\n", lm->special_tokens[0], lm->special_tokens[1], lm->special_tokens[2]); printf("n-grams:\n"); for (int order = 1; order <= lm->max_order; order++) { printf(" Order %d:\n", order); Ngram *ng = lm->ngrams[order - 1]; while (ng) { printf(" Log Prob: %.4f, Sequence: %s, Backoff: %s\n", ng->log_prob, ng->words, ng->backoff >= 0 ? ng->backoff_str : "N/A"); ng = ng->next; } } printf("End Marker: %s\n", lm->end_marker); } void lm_write(const LMFile *lm, const char *filepath) { FILE *file = fopen(filepath, "w"); if (!file) { perror("Failed to write file"); return; } fprintf(file, "%s\n", lm->header); for (int order = 1; order <= lm->max_order; order++) { fprintf(file, "ngram %d=%d\n", order, lm->ngram_counts[order - 1]); } fprintf(file, "\n"); for (int order = 1; order <= lm->max_order; order++) { fprintf(file, "\\%d-grams:\n", order); Ngram *ng = lm->ngrams[order - 1]; while (ng) { fprintf(file, "%.4f\t%s", ng->log_prob, ng->words); if (ng->backoff >= 0) fprintf(file, "\t%.4f", ng->backoff); fprintf(file, "\n"); ng = ng->next; } fprintf(file, "\n"); } fprintf(file, "%s\n", lm->end_marker); fclose(file); } // Example usage: // int main() { // LMFile *lm = lm_create(); // lm_open_and_read(lm, "example.lm"); // lm_print_properties(lm); // lm_write(lm, "output.lm"); // lm_free(lm); // return 0; // } // ===== end task-358 .LM ===== // ===== task-359 .LMD [C] ===== #include #include #include typedef struct { char key[256]; char value[1024]; } KeyValue; typedef struct { KeyValue *kvs; int count; } Dataset; typedef struct { Dataset *datasets; int dataset_count; unsigned char *data; long size; } LMDFile; LMDFile* lmd_create() { LMDFile* lmd = malloc(sizeof(LMDFile)); lmd->datasets = NULL; lmd->dataset_count = 0; lmd->data = NULL; lmd->size = 0; return lmd; } void lmd_open(LMDFile* lmd, const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) return; fseek(f, 0, SEEK_END); lmd->size = ftell(f); fseek(f, 0, SEEK_SET); lmd->data = malloc(lmd->size); fread(lmd->data, 1, lmd->size, f); fclose(f); lmd_parse(lmd, 0); } void lmd_parse(LMDFile* lmd, long offset) { long current_offset = offset; while (1) { char header[59]; memcpy(header, lmd->data + current_offset, 58); header[58] = '\0'; if (strncmp(header, "FCS3.1", 6) != 0) { break; // Error handling omitted for brevity } long text_begin = atol(header + 10); long text_end = atol(header + 18); char* text = malloc(text_end - text_begin + 2); memcpy(text, lmd->data + current_offset + text_begin, text_end - text_begin + 1); text[text_end - text_begin + 1] = '\0'; char delimiter = text[0]; char* token = strtok(text + 1, &delimiter); Dataset ds = { .kvs = NULL, .count = 0 }; while (token) { char* key = token; token = strtok(NULL, &delimiter); if (token) { ds.kvs = realloc(ds.kvs, sizeof(KeyValue) * (ds.count + 1)); strcpy(ds.kvs[ds.count].key, key); strcpy(ds.kvs[ds.count].value, token); ds.count++; token = strtok(NULL, &delimiter); } } free(text); lmd->datasets = realloc(lmd->datasets, sizeof(Dataset) * (lmd->dataset_count + 1)); lmd->datasets[lmd->dataset_count] = ds; lmd->dataset_count++; long next_data = atol(ds.kvs[ds.count - 1].value); // Assume last is $NEXTDATA for simplicity if (next_data == 0) break; current_offset += next_data; } } void lmd_print_properties(LMDFile* lmd) { for (int i = 0; i < lmd->dataset_count; i++) { printf("Dataset %d:\n", i + 1); for (int j = 0; j < lmd->datasets[i].count; j++) { printf("%s: %s\n", lmd->datasets[i].kvs[j].key, lmd->datasets[i].kvs[j].value); } printf("\n"); } } void lmd_write(LMDFile* lmd, const char* output_filename) { FILE* f = fopen(output_filename, "wb"); if (!f) return; for (int i = 0; i < lmd->dataset_count; i++) { char text[10240] = "|"; // Buffer for (int j = 0; j < lmd->datasets[i].count; j++) { strcat(text, lmd->datasets[i].kvs[j].key); strcat(text, "|"); strcat(text, lmd->datasets[i].kvs[j].value); strcat(text, "|"); } size_t text_len = strlen(text); char header[59]; sprintf(header, "FCS3.1 %8ld%8ld%8d%8d%8d%8d", 58L, 58L + text_len - 1, 0, 0, 0, 0); fwrite(header, 1, 58, f); fwrite(text, 1, text_len, f); } fclose(f); } void lmd_free(LMDFile* lmd) { for (int i = 0; i < lmd->dataset_count; i++) { free(lmd->datasets[i].kvs); } free(lmd->datasets); free(lmd->data); free(lmd); } // ===== end task-359 .LMD ===== // ===== task-360 .LNK [C++] ===== #include #include #include #include #include #include #include class LnkFile { private: std::map properties; uint32_t readUInt32(const std::vector& data, size_t& offset) { uint32_t val = *reinterpret_cast(&data[offset]); offset += 4; return val; } uint16_t readUInt16(const std::vector& data, size_t& offset) { uint16_t val = *reinterpret_cast(&data[offset]); offset += 2; return val; } std::string readFileTime(const std::vector& data, size_t& offset) { uint64_t time = *reinterpret_cast(&data[offset]); offset += 8; if (time == 0) return "0"; time /= 10000000; time -= 11644473600LL; std::time_t tt = static_cast(time); std::tm* tm = std::gmtime(&tt); std::stringstream ss; ss << std::put_time(tm, "%Y-%m-%d %H:%M:%S"); return ss.str(); } std::string readString(const std::vector& data, size_t& offset, size_t length, bool unicode) { std::string str; for (size_t i = 0; i < length; ++i) { uint16_t char_val = unicode ? readUInt16(data, offset) : data[offset++]; if (char_val == 0) break; str += static_cast(char_val); } return str; } public: LnkFile(const std::string& filepath = "") { if (!filepath.empty()) { read(filepath); } } void read(const std::string& filepath) { std::ifstream file(filepath, std::ios::binary); if (!file) throw std::runtime_error("Cannot open file"); std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); size_t offset = 0; // Header uint32_t headerSize = readUInt32(data, offset); if (headerSize != 76) throw std::runtime_error("Invalid header size"); offset += 16; // GUID properties["Data Flags"] = std::to_string(readUInt32(data, offset)); properties["File Attributes"] = std::to_string(readUInt32(data, offset)); properties["Creation Time"] = readFileTime(data, offset); properties["Access Time"] = readFileTime(data, offset); properties["Modification Time"] = readFileTime(data, offset); properties["File Size"] = std::to_string(readUInt32(data, offset)); properties["Icon Index"] = std::to_string(static_cast(readUInt32(data, offset))); properties["Show Window"] = std::to_string(readUInt32(data, offset)); properties["Hot Key"] = std::to_string(readUInt16(data, offset)); offset += 10; // Reserved // Similar parsing for other sections as in previous languages... // Implement Link Target ID List, Link Info, String Data, Extra Data similarly } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& filepath) { std::ofstream file(filepath, std::ios::binary); if (!file) throw std::runtime_error("Cannot write file"); // Serialize header uint32_t headerSize = 76; file.write(reinterpret_cast(&headerSize), 4); // Serialize GUID, flags, etc. // Full implementation similar to read in reverse std::cout << "Written to " << filepath << std::endl; } }; // Example usage // int main() { // try { // LnkFile lnk("sample.lnk"); // lnk.printProperties(); // lnk.write("new.lnk"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-360 .LNK ===== // ===== task-361 .LOGICX [C++] ===== #include #include #include #include #include // Requires libzip library using namespace std; class LogicXHandler { private: string filepath; map properties; public: LogicXHandler(const string& fp) : filepath(fp) { decode(); } void decode() { // Use libzip to open as ZIP int err = 0; zip* z = zip_open(filepath.c_str(), 0, &err); if (z) { properties["extension"] = ".logicx"; properties["type"] = "Apple Logic Pro X Project Bundle (ZIP-compressed)"; string contents = ""; int num_entries = zip_get_num_entries(z, 0); for (int i = 0; i < num_entries; ++i) { contents += zip_get_name(z, i, 0) + "\n"; } properties["contents"] = contents; struct zip_stat st; if (zip_stat(z, "Alternatives/000/ProjectData", 0, &st) == 0) { properties["main_data_file"] = "Alternatives/000/ProjectData"; zip_file* f = zip_fopen(z, "Alternatives/000/ProjectData", 0); char* data = new char[st.size]; zip_fread(f, data, st.size); string printable = ""; for (size_t j = 0; j < st.size; ++j) { if (data[j] >= 32 && data[j] < 127) printable += data[j]; } properties["project_data_strings"] = printable.substr(0, 500) + "..."; delete[] data; zip_fclose(f); } zip_close(z); } else { cerr << "Error opening ZIP: " << err << endl; } } map read() { return properties; } void printProperties() { for (const auto& pair : properties) { cout << pair.first << ": " << pair.second << endl; } } void write(const string& newFilepath) { zip* z = zip_open(newFilepath.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); if (z) { // Create basic directories zip_add_dir(z, "Alternatives/000"); zip_add_dir(z, "Media/Audio"); zip_add_dir(z, "Resources"); // Add dummy ProjectData string dummyData = "SongTrakEvSqDummyData"; zip_source* src = zip_source_buffer(z, dummyData.c_str(), dummyData.size(), 0); zip_file_add(z, "Alternatives/000/ProjectData", src, ZIP_FL_ENC_UTF_8); zip_close(z); cout << "Written basic .logicx to " << newFilepath << endl; } else { cerr << "Error creating ZIP" << endl; } } }; // Example usage // int main() { // LogicXHandler handler("example.logicx"); // handler.printProperties(); // handler.write("new.logicx"); // return 0; // } // ===== end task-361 .LOGICX ===== // ===== task-362 .LRC [C] ===== #include #include #include #include typedef struct { char *filepath; char *artist; char *title; char *album; char *author; char *lyricist; char *length; char *creator; char *offset; char *editor; char *version; char **comments; int comments_count; char **lyrics; int lyrics_count; } LRCFile; LRCFile* lrc_new(const char *filepath) { LRCFile *lrc = malloc(sizeof(LRCFile)); lrc->filepath = strdup(filepath); lrc->artist = NULL; lrc->title = NULL; lrc->album = NULL; lrc->author = NULL; lrc->lyricist = NULL; lrc->length = NULL; lrc->creator = NULL; lrc->offset = NULL; lrc->editor = NULL; lrc->version = NULL; lrc->comments = NULL; lrc->comments_count = 0; lrc->lyrics = NULL; lrc->lyrics_count = 0; return lrc; } void lrc_read(LRCFile *lrc) { FILE *file = fopen(lrc->filepath, "r"); if (!file) return; char line[1024]; regex_t time_regex; regcomp(&time_regex, "^\\[\\d+:\\d+\\.\\d+\\]", REG_EXTENDED); while (fgets(line, sizeof(line), file)) { char *trimmed = strtok(line, "\n"); if (trimmed) { if (strstr(trimmed, "[ar:")) lrc->artist = strdup(trimmed + 5); else if (strstr(trimmed, "[ti:")) lrc->title = strdup(trimmed + 5); else if (strstr(trimmed, "[al:")) lrc->album = strdup(trimmed + 5); else if (strstr(trimmed, "[au:")) lrc->author = strdup(trimmed + 5); else if (strstr(trimmed, "[lr:")) lrc->lyricist = strdup(trimmed + 5); else if (strstr(trimmed, "[length:")) lrc->length = strdup(trimmed + 9); else if (strstr(trimmed, "[by:")) lrc->creator = strdup(trimmed + 5); else if (strstr(trimmed, "[offset:")) lrc->offset = strdup(trimmed + 9); else if (strstr(trimmed, "[re:") || strstr(trimmed, "[tool:")) lrc->editor = strdup(strchr(trimmed, ':') + 1); else if (strstr(trimmed, "[ve:")) lrc->version = strdup(trimmed + 5); else if (strstr(trimmed, "[#")) { lrc->comments = realloc(lrc->comments, (lrc->comments_count + 1) * sizeof(char*)); lrc->comments[lrc->comments_count++] = strdup(trimmed + 2); } else if (regexec(&time_regex, trimmed, 0, NULL, 0) == 0) { lrc->lyrics = realloc(lrc->lyrics, (lrc->lyrics_count + 1) * sizeof(char*)); lrc->lyrics[lrc->lyrics_count++] = strdup(trimmed); } } } regfree(&time_regex); fclose(file); } void lrc_print_properties(LRCFile *lrc) { printf("Artist: %s\n", lrc->artist ? lrc->artist : ""); printf("Title: %s\n", lrc->title ? lrc->title : ""); printf("Album: %s\n", lrc->album ? lrc->album : ""); printf("Author: %s\n", lrc->author ? lrc->author : ""); printf("Lyricist: %s\n", lrc->lyricist ? lrc->lyricist : ""); printf("Length: %s\n", lrc->length ? lrc->length : ""); printf("Creator: %s\n", lrc->creator ? lrc->creator : ""); printf("Offset: %s\n", lrc->offset ? lrc->offset : ""); printf("Editor: %s\n", lrc->editor ? lrc->editor : ""); printf("Version: %s\n", lrc->version ? lrc->version : ""); printf("Comments: "); for (int i = 0; i < lrc->comments_count; i++) { printf("%s%s", lrc->comments[i], i < lrc->comments_count - 1 ? ", " : "\n"); } printf("Lyrics:\n"); for (int i = 0; i < lrc->lyrics_count; i++) { printf("%s\n", lrc->lyrics[i]); } } void lrc_write(LRCFile *lrc, const char *new_filepath) { const char *path = new_filepath ? new_filepath : lrc->filepath; FILE *file = fopen(path, "w"); if (!file) return; if (lrc->artist) fprintf(file, "[ar:%s\n", lrc->artist); if (lrc->title) fprintf(file, "[ti:%s\n", lrc->title); if (lrc->album) fprintf(file, "[al:%s\n", lrc->album); if (lrc->author) fprintf(file, "[au:%s\n", lrc->author); if (lrc->lyricist) fprintf(file, "[lr:%s\n", lrc->lyricist); if (lrc->length) fprintf(file, "[length:%s\n", lrc->length); if (lrc->creator) fprintf(file, "[by:%s\n", lrc->creator); if (lrc->offset) fprintf(file, "[offset:%s\n", lrc->offset); if (lrc->editor) fprintf(file, "[re:%s\n", lrc->editor); if (lrc->version) fprintf(file, "[ve:%s\n", lrc->version); for (int i = 0; i < lrc->comments_count; i++) { fprintf(file, "[#%s\n", lrc->comments[i]); } for (int i = 0; i < lrc->lyrics_count; i++) { fprintf(file, "%s\n", lrc->lyrics[i]); } fclose(file); } void lrc_free(LRCFile *lrc) { free(lrc->filepath); free(lrc->artist); free(lrc->title); free(lrc->album); free(lrc->author); free(lrc->lyricist); free(lrc->length); free(lrc->creator); free(lrc->offset); free(lrc->editor); free(lrc->version); for (int i = 0; i < lrc->comments_count; i++) free(lrc->comments[i]); free(lrc->comments); for (int i = 0; i < lrc->lyrics_count; i++) free(lrc->lyrics[i]); free(lrc->lyrics); free(lrc); } // Example usage: // int main() { // LRCFile *lrc = lrc_new("example.lrc"); // lrc_read(lrc); // lrc_print_properties(lrc); // lrc_write(lrc, "output.lrc"); // lrc_free(lrc); // return 0; // } // ===== end task-362 .LRC ===== // ===== task-363 .LUA [C++] ===== #include #include #include #include #include #include class LuaFileHandler { private: std::string filepath; public: LuaFileHandler(const std::string& fp) : filepath(fp) {} void printProperties() { struct stat st; if (stat(filepath.c_str(), &st) != 0) { std::cerr << "Error accessing file properties." << std::endl; return; } std::cout << "File name: " << filepath.substr(filepath.find_last_of("/\\") + 1) << std::endl; std::cout << "File size (in bytes): " << st.st_size << std::endl; std::cout << "Permissions (mode): " << std::oct << st.st_mode << std::endl; std::cout << "Inode number: " << st.st_ino << std::endl; std::cout << "Owner user ID (UID): " << st.st_uid << std::endl; std::cout << "Owner group ID (GID): " << st.st_gid << std::endl; std::cout << "Device ID: " << st.st_dev << std::endl; std::cout << "Number of hard links: " << st.st_nlink << std::endl; std::cout << "Last access time: " << std::ctime(&st.st_atime); std::cout << "Last modification time: " << std::ctime(&st.st_mtime); std::cout << "Last status change time: " << std::ctime(&st.st_ctime); std::cout << "Creation time: Not available in standard stat" << std::endl; } // Example write method to update modification time (as an illustration of 'write') void writeModificationTime(time_t newTime = time(nullptr)) { struct timespec times[2]; times[0].tv_sec = newTime; times[0].tv_nsec = UTIME_OMIT; times[1].tv_sec = newTime; times[1].tv_nsec = 0; if (utimensat(AT_FDCWD, filepath.c_str(), times, 0) != 0) { std::cerr << "Error updating modification time." << std::endl; } } }; // Usage example: // int main() { // LuaFileHandler handler("example.lua"); // handler.printProperties(); // handler.writeModificationTime(); // return 0; // } // ===== end task-363 .LUA ===== // ===== task-364 .LWO [C++] ===== #include #include #include #include #include #include class LWOParser { private: std::vector data; size_t offset = 0; std::vector properties; std::string readID4() { char buf[5] = {0}; memcpy(buf, &data[offset], 4); offset += 4; return std::string(buf); } uint32_t readU4() { uint32_t val; memcpy(&val, &data[offset], 4); offset += 4; return __builtin_bswap32(val); // big-endian } uint16_t readU2() { uint16_t val; memcpy(&val, &data[offset], 2); offset += 2; return __builtin_bswap16(val); } float readF4() { uint32_t val = readU4(); float f; memcpy(&f, &val, 4); return f; } std::string readS0() { std::string str; char b; while ((b = data[offset++]) != 0) { str += b; } if (offset % 2 != 0) offset++; return str; } uint32_t readVX() { uint16_t val = readU2(); if (val >= 0xFF00) { uint16_t low = readU2(); val = ((val & 0x00FF) << 16) | low; } return val; } public: LWOParser(const std::string& filename = "") { if (!filename.empty()) { read(filename); } } void read(const std::string& filename) { std::ifstream file(filename, std::ios::binary | std::ios::ate); std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(data.data(), size); parse(); } void parse() { std::string form = readID4(); if (form != "FORM") { properties.push_back("Invalid header"); return; } uint32_t length = readU4(); std::string type = readID4(); if (type != "LWO2") { properties.push_back("Not LWO2 format"); return; } properties.push_back("Header: FORM, Length: " + std::to_string(length) + ", Type: " + type); while (offset < data.size()) { std::string chunkID = readID4(); uint32_t chunkLen = readU4(); properties.push_back("Chunk: " + chunkID + ", Length: " + std::to_string(chunkLen)); size_t startOffset = offset; // Simplified parsing if (chunkID == "LAYR") { uint16_t num = readU2(); uint16_t flags = readU2(); float pivot[3] = {readF4(), readF4(), readF4()}; std::string name = readS0(); int16_t parent = (chunkLen > 26) ? readU2() : -1; std::string prop = " Layer: Number " + std::to_string(num) + ", Flags " + std::to_string(flags); prop += ", Pivot [" + std::to_string(pivot[0]) + ", " + std::to_string(pivot[1]) + ", " + std::to_string(pivot[2]) + "]"; prop += ", Name " + name + ", Parent " + std::to_string(parent); properties.push_back(prop); } else if (chunkID == "PNTS") { uint32_t numPoints = chunkLen / 12; properties.push_back(" Points: " + std::to_string(numPoints)); for (uint32_t i = 0; i < numPoints; i++) { float point[3] = {readF4(), readF4(), readF4()}; std::string prop = " Point " + std::to_string(i) + ": [" + std::to_string(point[0]) + ", " + std::to_string(point[1]) + ", " + std::to_string(point[2]) + "]"; properties.push_back(prop); } } else if (chunkID == "POLS") { std::string polyType = readID4(); properties.push_back(" Polygons Type: " + polyType); while (offset < startOffset + chunkLen) { uint16_t numVertFlags = readU2(); uint16_t numVert = numVertFlags & 0x03FF; uint16_t flags = numVertFlags >> 10; properties.push_back(" Polygon: Verts " + std::to_string(numVert) + ", Flags " + std::to_string(flags)); for (uint16_t j = 0; j < numVert; j++) { uint32_t vert = readVX(); properties.push_back(" Vert " + std::to_string(j) + ": " + std::to_string(vert)); } } } else if (chunkID == "SURF") { std::string name = readS0(); std::string source = readS0(); properties.push_back(" Surface: Name " + name + ", Source " + source); while (offset < startOffset + chunkLen) { std::string subID = readID4(); uint16_t subLen = readU2(); properties.push_back(" Subchunk: " + subID + ", Length " + std::to_string(subLen)); offset += subLen; if (subLen % 2 != 0) offset++; } } else { offset = startOffset + chunkLen; } if (chunkLen % 2 != 0) offset++; } } void printProperties() { for (const auto& prop : properties) { std::cout << prop << std::endl; } } void write(const std::string& filename) { if (data.empty()) return; std::ofstream file(filename, std::ios::binary); file.write(data.data(), data.size()); } }; // Example usage: // int main() { // LWOParser parser("example.lwo"); // parser.printProperties(); // parser.write("output.lwo"); // return 0; // } // ===== end task-364 .LWO ===== // ===== task-365 .LZ [C] ===== #include #include #include #include #include // For CRC32 typedef struct { char *filename; char magic[5]; uint8_t version; uint64_t dict_size; uint32_t crc32; uint64_t uncompressed_size; uint64_t member_size; } LZFile; LZFile* lzfile_new(const char *filename) { LZFile *lz = malloc(sizeof(LZFile)); lz->filename = strdup(filename); return lz; } void lzfile_free(LZFile *lz) { free(lz->filename); free(lz); } int lzfile_read_and_decode(LZFile *lz) { FILE *f = fopen(lz->filename, "rb"); if (!f) return -1; fseek(f, 0, SEEK_END); long file_size = ftell(f); if (file_size < 26) { fclose(f); return -2; } fseek(f, 0, SEEK_SET); uint8_t header[6]; fread(header, 1, 6, f); strncpy(lz->magic, (char*)header, 4); lz->magic[4] = '\0'; lz->version = header[4]; uint8_t ds = header[5]; uint8_t exponent = ds & 0x1F; uint8_t numerator = ds >> 5; uint64_t base_size = (uint64_t)1 << exponent; uint64_t subtract = (base_size >> 4) * numerator; lz->dict_size = base_size - subtract; fseek(f, file_size - 20, SEEK_SET); uint8_t trailer[20]; fread(trailer, 1, 20, f); fclose(f); lz->crc32 = trailer[0] | (trailer[1] << 8) | (trailer[2] << 16) | (trailer[3] << 24); lz->uncompressed_size = (uint64_t)trailer[4] | ((uint64_t)trailer[5] << 8) | ((uint64_t)trailer[6] << 16) | ((uint64_t)trailer[7] << 24) | ((uint64_t)trailer[8] << 32) | ((uint64_t)trailer[9] << 40) | ((uint64_t)trailer[10] << 48) | ((uint64_t)trailer[11] << 56); lz->member_size = (uint64_t)trailer[12] | ((uint64_t)trailer[13] << 8) | ((uint64_t)trailer[14] << 16) | ((uint64_t)trailer[15] << 24) | ((uint64_t)trailer[16] << 32) | ((uint64_t)trailer[17] << 40) | ((uint64_t)trailer[18] << 48) | ((uint64_t)trailer[19] << 56); if (lz->member_size != (uint64_t)file_size) { return -3; // Multimember not supported } return 0; } void lzfile_print_properties(LZFile *lz) { printf("Magic Number: %s\n", lz->magic); printf("Version Number: %u\n", lz->version); printf("Dictionary Size: %lu bytes\n", lz->dict_size); printf("CRC32: 0x%08X\n", lz->crc32); printf("Uncompressed Data Size: %lu bytes\n", lz->uncompressed_size); printf("Member Size: %lu bytes\n", lz->member_size); } // For full decompress/verify or write, integrate lzlib or similar library // Example stub for verify: // int lzfile_verify_decompress(LZFile *lz) { // // Open file, skip header, decompress with lzlib, compute CRC and size, compare // } int main() { LZFile *lz = lzfile_new("example.lz"); if (lzfile_read_and_decode(lz) == 0) { lzfile_print_properties(lz); } lzfile_free(lz); return 0; } // ===== end task-365 .LZ ===== // ===== task-366 .M [C] ===== #include #include #include #define MAX_LINE 1024 #define MAX_PROPS 100 typedef struct { char *filepath; char *properties[MAX_PROPS]; int prop_count; char *content; long content_size; } MFileHandler; MFileHandler* createMFileHandler(const char *filepath) { MFileHandler *handler = (MFileHandler*)malloc(sizeof(MFileHandler)); handler->filepath = strdup(filepath); handler->prop_count = 0; handler->content = NULL; handler->content_size = 0; return handler; } void readAndDecode(MFileHandler *handler) { FILE *file = fopen(handler->filepath, "r"); if (!file) { printf("Error opening file.\n"); return; } fseek(file, 0, SEEK_END); handler->content_size = ftell(file); fseek(file, 0, SEEK_SET); handler->content = (char*)malloc(handler->content_size + 1); fread(handler->content, 1, handler->content_size, file); handler->content[handler->content_size] = '\0'; fclose(file); char *line = strtok(handler->content, "\n"); while (line) { if (strstr(line, "%[")) { char *start = strstr(line, "%[") + 2; char *end = strchr(start, ']'); if (end) { *end = '\0'; handler->properties[handler->prop_count] = strdup(start); handler->prop_count++; *end = ']'; } } line = strtok(NULL, "\n"); } } void printProperties(MFileHandler *handler) { if (handler->prop_count == 0) { printf("No properties found.\n"); } else { for (int i = 0; i < handler->prop_count; i++) { printf("%s\n", handler->properties[i]); } } } void write(MFileHandler *handler, const char *newFilepath) { const char *path = newFilepath ? newFilepath : handler->filepath; FILE *file = fopen(path, "w"); if (!file) { printf("Error writing file.\n"); return; } fwrite(handler->content, 1, handler->content_size, file); fclose(file); printf("File written to %s\n", path); } void destroyMFileHandler(MFileHandler *handler) { free(handler->filepath); for (int i = 0; i < handler->prop_count; i++) { free(handler->properties[i]); } free(handler->content); free(handler); } // Example usage: // int main() { // MFileHandler *handler = createMFileHandler("example.m"); // readAndDecode(handler); // printProperties(handler); // write(handler, "new_example.m"); // destroyMFileHandler(handler); // return 0; // } // ===== end task-366 .M ===== // ===== task-367 .M2TS [C++] ===== #include #include #include #include #include #include class M2TSHandler { private: std::string filepath; std::map properties; public: M2TSHandler(const std::string& fp) : filepath(fp) { properties["File extension"] = ".m2ts"; properties["MIME type"] = "video/mp2t"; properties["Base format"] = "Modified MPEG-2 Transport Stream (ITU-T H.222.0 | ISO/IEC 13818-1)"; properties["Source packet size"] = "192 bytes"; properties["TP_extra_header size"] = "4 bytes"; properties["TP_extra_header fields"] = "Copy permission indicator (2 bits), Arrival time stamp (30 bits)"; properties["MPEG-2 TS packet size"] = "188 bytes"; properties["Aligned unit size"] = "6144 bytes"; properties["Packets per aligned unit"] = "32"; properties["Bit rate type"] = "Variable (VBR)"; properties["Maximum multiplex rate"] = "48 Mbps"; properties["Supported video codecs"] = "H.262/MPEG-2 Part 2, H.264/MPEG-4 AVC, SMPTE VC-1"; properties["Supported audio codecs"] = "Dolby Digital (AC-3), DTS, Linear PCM, Dolby Digital Plus, DTS-HD High Resolution Audio, DTS-HD Master Audio, Dolby TrueHD"; properties["Multiplexing"] = "Audio, video, subtitles, and other streams"; properties["Random access support"] = "Yes"; properties["Encryption support"] = "None intrinsic"; properties["Validation traits"] = "File size modulo 192 == 0, TS sync byte at offset 4"; } std::map decodeRead() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { throw std::runtime_error("Cannot open file"); } size_t fileSize = file.tellg(); file.seekg(0); std::vector data(fileSize); file.read(reinterpret_cast(data.data()), fileSize); if (fileSize % 192 != 0 || data[4] != 0x47) { throw std::runtime_error("Invalid .M2TS file"); } double numPackets = static_cast(fileSize) / 192.0; // Decode first packet (big-endian) uint32_t tpExtraHeader = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]; uint32_t copyPermission = (tpExtraHeader >> 30) & 0x03; uint32_t firstAts = tpExtraHeader & 0x3FFFFFFF; // Decode last packet size_t lastOffset = fileSize - 192; uint32_t lastTpExtraHeader = (data[lastOffset] << 24) | (data[lastOffset+1] << 16) | (data[lastOffset+2] << 8) | data[lastOffset+3]; uint32_t lastAts = lastTpExtraHeader & 0x3FFFFFFF; double duration = static_cast(lastAts - firstAts) / 27000000.0; std::map instanceProps; instanceProps["file_size"] = fileSize; instanceProps["num_packets"] = numPackets; instanceProps["copy_permission"] = copyPermission; instanceProps["first_ats"] = firstAts; instanceProps["last_ats"] = lastAts; instanceProps["duration"] = duration; return instanceProps; } void printProperties() { auto instanceProps = decodeRead(); std::cout << "General Properties:" << std::endl; for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } std::cout << "\nInstance Properties:" << std::endl; for (const auto& prop : instanceProps) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& outputPath, bool modifyAts) { std::ifstream inFile(filepath, std::ios::binary); if (!inFile) { throw std::runtime_error("Cannot open input file"); } std::vector data((std::istreambuf_iterator(inFile)), std::istreambuf_iterator()); if (modifyAts) { // Example: increment first ATS by 1 uint32_t tpExtraHeader = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]; uint32_t copyPermission = (tpExtraHeader >> 30) & 0x03; uint32_t ats = (tpExtraHeader & 0x3FFFFFFF) + 1; uint32_t newHeader = (copyPermission << 30) | ats; data[0] = (newHeader >> 24) & 0xFF; data[1] = (newHeader >> 16) & 0xFF; data[2] = (newHeader >> 8) & 0xFF; data[3] = newHeader & 0xFF; } std::ofstream outFile(outputPath, std::ios::binary); outFile.write(reinterpret_cast(data.data()), data.size()); std::cout << "Written to " << outputPath << std::endl; } }; // Example usage: // int main() { // try { // M2TSHandler handler("sample.m2ts"); // handler.printProperties(); // handler.write("modified.m2ts", true); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-367 .M2TS ===== // ===== task-368 .MCU [C] ===== #include #include #include #define MAX_LINES 1000 #define MAX_LINE_LEN 1024 typedef struct { char *filepath; char *extension; char *mime_type; char *encoding; char *structure; char *header; char **extinf; int extinf_count; char *playlist; char **extgrp; int extgrp_count; char *extalb; char *extart; char *extgenre; char *extm3a; char **extbyt; int extbyt_count; char *extbin; char *extalbumarturl; char **comments; int comments_count; char **media_entries; int media_entries_count; } M3UHandler; M3UHandler* create_m3u_handler(const char *filepath) { M3UHandler *handler = (M3UHandler*)malloc(sizeof(M3UHandler)); handler->filepath = strdup(filepath); handler->extension = ".m3u"; handler->mime_type = "audio/x-mpegurl"; handler->encoding = "UTF-8"; handler->structure = "Plain text lines"; handler->header = NULL; handler->extinf = (char**)malloc(MAX_LINES * sizeof(char*)); handler->extinf_count = 0; handler->playlist = NULL; handler->extgrp = (char**)malloc(MAX_LINES * sizeof(char*)); handler->extgrp_count = 0; handler->extalb = NULL; handler->extart = NULL; handler->extgenre = NULL; handler->extm3a = NULL; handler->extbyt = (char**)malloc(MAX_LINES * sizeof(char*)); handler->extbyt_count = 0; handler->extbin = NULL; handler->extalbumarturl = NULL; handler->comments = (char**)malloc(MAX_LINES * sizeof(char*)); handler->comments_count = 0; handler->media_entries = (char**)malloc(MAX_LINES * sizeof(char*)); handler->media_entries_count = 0; return handler; } void read_and_decode(M3UHandler *handler) { FILE *file = fopen(handler->filepath, "r"); if (!file) { printf("Error opening file: %s\n", handler->filepath); return; } char line[MAX_LINE_LEN]; while (fgets(line, sizeof(line), file)) { char *trimmed = strtok(line, "\r\n"); if (!trimmed) continue; if (strstr(trimmed, "#EXTM3U") == trimmed) { handler->header = strdup(trimmed); } else if (strstr(trimmed, "#EXTINF:") == trimmed) { handler->extinf[handler->extinf_count++] = strdup(trimmed); } else if (strstr(trimmed, "#PLAYLIST:") == trimmed) { handler->playlist = strdup(trimmed); } else if (strstr(trimmed, "#EXTGRP:") == trimmed) { handler->extgrp[handler->extgrp_count++] = strdup(trimmed); } else if (strstr(trimmed, "#EXTALB:") == trimmed) { handler->extalb = strdup(trimmed); } else if (strstr(trimmed, "#EXTART:") == trimmed) { handler->extart = strdup(trimmed); } else if (strstr(trimmed, "#EXTGENRE:") == trimmed) { handler->extgenre = strdup(trimmed); } else if (strstr(trimmed, "#EXTM3A") == trimmed) { handler->extm3a = strdup(trimmed); } else if (strstr(trimmed, "#EXTBYT:") == trimmed) { handler->extbyt[handler->extbyt_count++] = strdup(trimmed); } else if (strstr(trimmed, "#EXTBIN") == trimmed) { handler->extbin = strdup(trimmed); } else if (strstr(trimmed, "#EXTALBUMARTURL:") == trimmed) { handler->extalbumarturl = strdup(trimmed); } else if (trimmed[0] == '#' && strstr(trimmed, "#EXT") != trimmed) { handler->comments[handler->comments_count++] = strdup(trimmed); } else if (strlen(trimmed) > 0) { handler->media_entries[handler->media_entries_count++] = strdup(trimmed); } } fclose(file); } void print_properties(M3UHandler *handler) { printf("extension: %s\n", handler->extension); printf("mime_type: %s\n", handler->mime_type); printf("encoding: %s\n", handler->encoding); printf("structure: %s\n", handler->structure); printf("header: %s\n", handler->header ? handler->header : "None"); printf("extinf: "); if (handler->extinf_count == 0) printf("None\n"); else { for (int i = 0; i < handler->extinf_count; i++) printf("%s ", handler->extinf[i]); printf("\n"); } printf("playlist: %s\n", handler->playlist ? handler->playlist : "None"); printf("extgrp: "); if (handler->extgrp_count == 0) printf("None\n"); else { for (int i = 0; i < handler->extgrp_count; i++) printf("%s ", handler->extgrp[i]); printf("\n"); } printf("extalb: %s\n", handler->extalb ? handler->extalb : "None"); printf("extart: %s\n", handler->extart ? handler->extart : "None"); printf("extgenre: %s\n", handler->extgenre ? handler->extgenre : "None"); printf("extm3a: %s\n", handler->extm3a ? handler->extm3a : "None"); printf("extbyt: "); if (handler->extbyt_count == 0) printf("None\n"); else { for (int i = 0; i < handler->extbyt_count; i++) printf("%s ", handler->extbyt[i]); printf("\n"); } printf("extbin: %s\n", handler->extbin ? handler->extbin : "None"); printf("extalbumarturl: %s\n", handler->extalbumarturl ? handler->extalbumarturl : "None"); printf("comments: "); if (handler->comments_count == 0) printf("None\n"); else { for (int i = 0; i < handler->comments_count; i++) printf("%s ", handler->comments[i]); printf("\n"); } printf("media_entries: "); if (handler->media_entries_count == 0) printf("None\n"); else { for (int i = 0; i < handler->media_entries_count; i++) printf("%s ", handler->media_entries[i]); printf("\n"); } } void write_m3u(M3UHandler *handler, const char *new_filepath) { FILE *file = fopen(new_filepath, "w"); if (!file) { printf("Error opening file for write: %s\n", new_filepath); return; } if (handler->header) fprintf(file, "%s\n", handler->header); if (handler->playlist) fprintf(file, "%s\n", handler->playlist); if (handler->extalb) fprintf(file, "%s\n", handler->extalb); if (handler->extart) fprintf(file, "%s\n", handler->extart); if (handler->extgenre) fprintf(file, "%s\n", handler->extgenre); if (handler->extm3a) fprintf(file, "%s\n", handler->extm3a); if (handler->extbin) fprintf(file, "%s\n", handler->extbin); if (handler->extalbumarturl) fprintf(file, "%s\n", handler->extalbumarturl); for (int i = 0; i < handler->comments_count; i++) fprintf(file, "%s\n", handler->comments[i]); for (int i = 0; i < handler->extgrp_count; i++) fprintf(file, "%s\n", handler->extgrp[i]); int max_count = handler->extinf_count > handler->extbyt_count ? handler->extinf_count : handler->extbyt_count; max_count = max_count > handler->media_entries_count ? max_count : handler->media_entries_count; for (int i = 0; i < max_count; i++) { if (i < handler->extinf_count) fprintf(file, "%s\n", handler->extinf[i]); if (i < handler->extbyt_count) fprintf(file, "%s\n", handler->extbyt[i]); if (i < handler->media_entries_count) fprintf(file, "%s\n", handler->media_entries[i]); } fclose(file); printf("File written to %s\n", new_filepath); } void free_m3u_handler(M3UHandler *handler) { free(handler->filepath); if (handler->header) free(handler->header); for (int i = 0; i < handler->extinf_count; i++) free(handler->extinf[i]); free(handler->extinf); if (handler->playlist) free(handler->playlist); for (int i = 0; i < handler->extgrp_count; i++) free(handler->extgrp[i]); free(handler->extgrp); if (handler->extalb) free(handler->extalb); if (handler->extart) free(handler->extart); if (handler->extgenre) free(handler->extgenre); if (handler->extm3a) free(handler->extm3a); for (int i = 0; i < handler->extbyt_count; i++) free(handler->extbyt[i]); free(handler->extbyt); if (handler->extbin) free(handler->extbin); if (handler->extalbumarturl) free(handler->extalbumarturl); for (int i = 0; i < handler->comments_count; i++) free(handler->comments[i]); free(handler->comments); for (int i = 0; i < handler->media_entries_count; i++) free(handler->media_entries[i]); free(handler->media_entries); free(handler); } // Example usage: // int main() { // M3UHandler *handler = create_m3u_handler("example.m3u"); // read_and_decode(handler); // print_properties(handler); // write_m3u(handler, "new.m3u"); // free_m3u_handler(handler); // return 0; // } // ===== end task-368 .MCU ===== // ===== task-370 .M4A [C++] ===== #include #include #include #include #include #include #include #include // For big-endian if needed; assume host is little class M4AHandler { private: std::string filepath; std::map properties; // Use string for simplicity; convert as needed std::vector data; uint32_t readUInt32(size_t& offset) { uint32_t val = (data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]; offset += 4; return val; } std::string readString(size_t& offset, size_t len) { std::string str(data.begin() + offset, data.begin() + offset + len); offset += len; return str; } size_t findBox(const std::vector& types, size_t start = 0, size_t end = 0) { if (end == 0) end = data.size(); auto path = types; std::string target = path.back(); path.pop_back(); size_t offset = start; while (offset < end) { size_t sizeStart = offset; uint32_t size = readUInt32(offset); std::string type = readString(offset, 4); size_t boxStart = offset; if (size == 1) { uint64_t largeSize = ((uint64_t)readUInt32(offset) << 32) | readUInt32(offset); size = static_cast(largeSize); // Assume fits boxStart += 8; } size_t boxEnd = sizeStart + size; if (type == target) { return sizeStart; } else if (!path.empty() && type == path.front()) { path.erase(path.begin()); start = boxStart; } offset = boxEnd; } return std::string::npos; } void parseMetadata() { size_t moovStart = findBox({"moov"}); if (moovStart == std::string::npos) return; size_t udtaStart = findBox({"udta"}, moovStart + 8); if (udtaStart == std::string::npos) return; size_t metaStart = findBox({"meta"}, udtaStart + 8); if (metaStart == std::string::npos) return; size_t ilstStart = findBox({"ilst"}, metaStart + 12); if (ilstStart == std::string::npos) return; size_t offset = ilstStart + 8; uint32_t ilstSize = (data[ilstStart] << 24) | (data[ilstStart+1] << 16) | (data[ilstStart+2] << 8) | data[ilstStart+3]; size_t ilstEnd = ilstStart + ilstSize; while (offset < ilstEnd) { size_t itemStart = offset; uint32_t size = readUInt32(offset); std::string key = readString(offset, 4); offset = itemStart + 24; // Skip to data value uint32_t dataLen = size - 24; std::string value; // Simplified: treat most as string; real would parse per type if (key == "covr") { value = "Cover art present (binary data)"; } else if (key == "----") { value = "Custom freeform"; } else { value = std::string(data.begin() + offset, data.begin() + offset + dataLen); } properties[key] = value; offset = itemStart + size; } } public: M4AHandler(const std::string& fp) : filepath(fp) { std::ifstream file(filepath, std::ios::binary); data = std::vector((std::istreambuf_iterator(file)), std::istreambuf_iterator()); parseMetadata(); } void printProperties() { std::cout << "{" << std::endl; for (const auto& p : properties) { std::cout << " \"" << p.first << "\": \"" << p.second << "\"," << std::endl; } std::cout << "}" << std::endl; } void writeProperty(const std::string& key, const std::string& value) { properties[key] = value; // Stub: write original std::ofstream out(filepath + ".new", std::ios::binary); out.write(reinterpret_cast(data.data()), data.size()); std::cout << "Updated (stub):" << std::endl; printProperties(); } }; // ===== end task-370 .M4A ===== // ===== task-371 .M4P [C] ===== #include #include #include #include #include typedef struct { char *filepath; char **keys; char **values; int count; uint8_t *buffer; size_t buffer_size; } M4PParser; M4PParser* m4p_parser_new(const char *filepath) { M4PParser *parser = malloc(sizeof(M4PParser)); parser->filepath = strdup(filepath); parser->keys = NULL; parser->values = NULL; parser->count = 0; parser->buffer = NULL; parser->buffer_size = 0; return parser; } void m4p_parser_free(M4PParser *parser) { free(parser->filepath); for (int i = 0; i < parser->count; i++) { free(parser->keys[i]); free(parser->values[i]); } free(parser->keys); free(parser->values); free(parser->buffer); free(parser); } void read_file(M4PParser *parser) { FILE *f = fopen(parser->filepath, "rb"); if (!f) { perror("Failed to open file"); exit(1); } fseek(f, 0, SEEK_END); parser->buffer_size = ftell(f); fseek(f, 0, SEEK_SET); parser->buffer = malloc(parser->buffer_size); fread(parser->buffer, 1, parser->buffer_size, f); fclose(f); } void add_property(M4PParser *parser, const char *key, const char *value) { parser->keys = realloc(parser->keys, (parser->count + 1) * sizeof(char*)); parser->values = realloc(parser->values, (parser->count + 1) * sizeof(char*)); parser->keys[parser->count] = strdup(key); parser->values[parser->count] = strdup(value); parser->count++; } uint32_t get_be32(const uint8_t *data) { return (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]; } uint16_t get_be16(const uint8_t *data) { return (data[0] << 8) | data[1]; } void parse_properties(M4PParser *parser) { size_t offset = 0; while (offset < parser->buffer_size) { uint32_t size = get_be32(parser->buffer + offset); char type[5] = {0}; memcpy(type, parser->buffer + offset + 4, 4); offset += 8; if (strcmp(type, "moov") == 0) { size_t moov_end = offset + size - 8; while (offset < moov_end) { uint32_t sub_size = get_be32(parser->buffer + offset); char sub_type[5] = {0}; memcpy(sub_type, parser->buffer + offset + 4, 4); offset += 8; if (strcmp(sub_type, "udta") == 0) { size_t udta_end = offset + sub_size - 8; while (offset < udta_end) { uint32_t meta_size = get_be32(parser->buffer + offset); char meta_type[5] = {0}; memcpy(meta_type, parser->buffer + offset + 4, 4); offset += 8; if (strcmp(meta_type, "meta") == 0) { offset += 4; // Skip version/flags size_t meta_end = offset + meta_size - 12; while (offset < meta_end) { uint32_t ilst_size = get_be32(parser->buffer + offset); char ilst_type[5] = {0}; memcpy(ilst_type, parser->buffer + offset + 4, 4); offset += 8; if (strcmp(ilst_type, "ilst") == 0) { size_t ilst_end = offset + ilst_size - 8; while (offset < ilst_end) { uint32_t prop_size = get_be32(parser->buffer + offset); char prop_type[5] = {0}; memcpy(prop_type, parser->buffer + offset + 4, 4); offset += 8; uint32_t data_size = get_be32(parser->buffer + offset); char data_type[5] = {0}; memcpy(data_type, parser->buffer + offset + 4, 4); offset += 8; if (strcmp(data_type, "data") == 0) { offset += 8; // Skip type/flags/locale uint32_t value_length = data_size - 16; char value_str[1024]; get_value(parser->buffer + offset, value_length, prop_type, value_str); add_property(parser, prop_type, value_str); offset += value_length; } else { offset += data_size - 8; } } } else { offset += ilst_size - 8; } } } else { offset += meta_size - 8; } } } else { offset += sub_size - 8; } } } else { offset += size - 8; } } } void get_value(const uint8_t *data, uint32_t length, const char *prop_type, char *out) { if (strcmp(prop_type, "covr") == 0) { sprintf(out, "Binary data (length: %u)", length); } else if (strcmp(prop_type, "trkn") == 0 || strcmp(prop_type, "disk") == 0) { uint16_t num = get_be16(data + 2); uint16_t total = get_be16(data + 4); sprintf(out, "[%u, %u]", num, total); } else if (strcmp(prop_type, "tmpo") == 0 || strcmp(prop_type, "rtng") == 0 || strcmp(prop_type, "stik") == 0 || strcmp(prop_type, "hdvd") == 0 || strcmp(prop_type, "tves") == 0 || strcmp(prop_type, "tvsn") == 0) { uint32_t val = get_be32(data); sprintf(out, "%u", val); } else if (strcmp(prop_type, "cpil") == 0 || strcmp(prop_type, "pgap") == 0 || strcmp(prop_type, "pcst") == 0) { sprintf(out, "%s", data[0] ? "true" : "false"); } else { strncpy(out, (const char*)data, length); out[length] = '\0'; } } void print_properties(M4PParser *parser) { for (int i = 0; i < parser->count; i++) { printf("%s: %s\n", parser->keys[i], parser->values[i]); } } void write(M4PParser *parser, const char *output_path) { FILE *f = fopen(output_path, "wb"); if (!f) { perror("Failed to write file"); exit(1); } fwrite(parser->buffer, 1, parser->buffer_size, f); fclose(f); } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } M4PParser *parser = m4p_parser_new(argv[1]); read_file(parser); parse_properties(parser); print_properties(parser); write(parser, "output.m4p"); m4p_parser_free(parser); return 0; } // ===== end task-371 .M4P ===== // ===== task-372 .M4R [C++] ===== #include #include #include #include #include #include #include class M4RParser { private: std::vector data; size_t pos; std::map properties; uint32_t readBE32() { uint32_t val = (data[pos] << 24) | (data[pos+1] << 16) | (data[pos+2] << 8) | data[pos+3]; pos += 4; return val; } uint16_t readBE16() { uint16_t val = (data[pos] << 8) | data[pos+1]; pos += 2; return val; } uint64_t readBE64() { uint64_t val = ((uint64_t)readBE32() << 32) | readBE32(); return val; } std::string readString(size_t len) { std::string str(data.begin() + pos, data.begin() + pos + len); pos += len; return str; } struct Box { std::string type; uint64_t size; size_t start; size_t boxDataStart; size_t end; }; Box parseBox() { Box box; box.start = pos; uint32_t size32 = readBE32(); box.type = readString(4); box.size = size32; if (size32 == 1) { box.size = readBE64(); } box.boxDataStart = pos; box.end = box.start + box.size; return box; } void parse() { while (pos < data.size()) { Box box = parseBox(); pos = box.boxDataStart; if (box.type == "ftyp") { parseFtyp(); } else if (box.type == "moov") { parseMoov(); } pos = box.end; } } void parseFtyp() { properties["Major Brand"] = readString(4); properties["Minor Version"] = std::to_string(readBE32()); std::string compat; while (pos < data.size()) { compat += readString(4) + " "; } properties["Compatible Brands"] = compat; } void parseMoov() { size_t moovEnd = pos + readBE32() - 8; while (pos < moovEnd) { Box box = parseBox(); if (box.type == "mvhd") { parseMvhd(); } else if (box.type == "trak") { parseTrak(); } else if (box.type == "udta") { parseUdta(); } pos = box.end; } } void parseMvhd() { uint8_t version = data[pos++]; pos += 3; uint64_t ct, mt, dur; uint32_t ts; if (version == 0) { ct = readBE32(); mt = readBE32(); ts = readBE32(); dur = readBE32(); } else { ct = readBE64(); mt = readBE64(); ts = readBE32(); dur = readBE64(); } properties["Creation Time"] = std::to_string(ct); properties["Modification Time"] = std::to_string(mt); properties["Timescale"] = std::to_string(ts); properties["Duration"] = std::to_string(dur); properties["Preferred Rate"] = std::to_string(static_cast(readBE32()) / 65536.0); properties["Preferred Volume"] = std::to_string(static_cast(readBE16()) / 256.0); pos += 76; } // Similar parse methods as in Python/Java, omitting for brevity. Implement analogously using read functions. public: M4RParser(const std::string& filename) { std::ifstream file(filename, std::ios::binary); data = std::vector((std::istreambuf_iterator(file)), std::istreambuf_iterator()); pos = 0; parse(); } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& outputFilename) { std::ofstream file(outputFilename, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); } }; // Example usage: // int main() { // M4RParser parser("example.m4r"); // parser.printProperties(); // parser.write("modified.m4r"); // return 0; // } // ===== end task-372 .M4R ===== // ===== task-373 .M4V [C++] ===== #include #include #include #include #include #include #include class M4VHandler { private: std::string filepath; std::vector buffer; std::string major_brand; uint32_t minor_version; std::vector compat_brands; std::map properties; public: M4VHandler(const std::string& fp) : filepath(fp) { properties["Filename Extension"] = ".m4v"; properties["MIME Type"] = "video/x-m4v"; properties["Developer"] = "Apple Inc."; properties["Container Basis"] = "MPEG-4 Part 14"; properties["File Signature"] = "offset 4-7 'ftyp'"; properties["Supported Video Codecs"] = "H.264/AVC, H.265/HEVC"; properties["Supported Audio Codecs"] = "AAC, Dolby Digital"; properties["DRM Support"] = "Optional FairPlay"; properties["Box Structure"] = "Series of nested boxes with 8-byte headers"; properties["Subtitles/Chapters Support"] = "Yes"; } void read_and_decode() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { throw std::runtime_error("Failed to open file"); } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); buffer.resize(size); file.read(reinterpret_cast(buffer.data()), size); // Decode ftyp uint32_t box_size = (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]; char type[5] = {static_cast(buffer[4]), static_cast(buffer[5]), static_cast(buffer[6]), static_cast(buffer[7]), '\0'}; if (std::strcmp(type, "ftyp") != 0) { throw std::runtime_error("Not a valid .M4V file (missing ftyp)"); } char mb[5] = {static_cast(buffer[8]), static_cast(buffer[9]), static_cast(buffer[10]), static_cast(buffer[11]), '\0'}; major_brand = mb; if (major_brand != "M4V ") { throw std::runtime_error("Not a standard M4V file (major brand not M4V )"); } minor_version = (buffer[12] << 24) | (buffer[13] << 16) | (buffer[14] << 8) | buffer[15]; for (uint32_t i = 16; i < box_size; i += 4) { char cb[5] = {static_cast(buffer[i]), static_cast(buffer[i+1]), static_cast(buffer[i+2]), static_cast(buffer[i+3]), '\0'}; compat_brands.push_back(cb); } } void print_properties() { if (major_brand.empty()) { read_and_decode(); } std::cout << "Extracted Properties:" << std::endl; std::cout << "- Major Brand: " << major_brand << std::endl; std::cout << "- Minor Version: " << minor_version << std::endl; std::cout << "- Compatible Brands: "; for (size_t i = 0; i < compat_brands.size(); ++i) { std::cout << compat_brands[i]; if (i < compat_brands.size() - 1) std::cout << ", "; } std::cout << std::endl << std::endl << "General Format Properties:" << std::endl; for (const auto& prop : properties) { std::cout << "- " << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& output_path = "") { if (buffer.empty()) { read_and_decode(); } std::string out = output_path.empty() ? filepath : output_path; std::ofstream outfile(out, std::ios::binary); if (!outfile) { throw std::runtime_error("Failed to write file"); } outfile.write(reinterpret_cast(buffer.data()), buffer.size()); std::cout << "File written to " << out << std::endl; } }; // Example usage: // int main() { // try { // M4VHandler handler("sample.m4v"); // handler.print_properties(); // handler.write("output.m4v"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-373 .M4V ===== // ===== task-374 .M64 [C++] ===== #include #include #include #include #include #include class M64File { private: std::string filepath; std::map properties; // Use string for simplicity in printing char header[1024]; public: M64File(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file"); } file.read(header, 1024); if (file.gcount() < 1024) { throw std::runtime_error("Invalid .M64 file: Header too short"); } file.close(); decodeProperties(); printProperties(); } void decodeProperties() { properties["Signature"] = std::string(header, 4); uint32_t version; memcpy(&version, header + 4, 4); std::swap(version & 0xFFFF, (version >> 16) & 0xFFFF); // LE to host (assuming little-endian host) properties["Version"] = std::to_string(version); uint32_t uid; memcpy(&uid, header + 8, 4); properties["Movie UID"] = std::to_string(uid); uint32_t vis; memcpy(&vis, header + 12, 4); properties["Number of VIs (Frames)"] = std::to_string(vis); uint32_t rerecord; memcpy(&rerecord, header + 16, 4); properties["Rerecord Count"] = std::to_string(rerecord); properties["VIs per Second (FPS)"] = std::to_string(static_cast(header[20])); properties["Number of Controllers"] = std::to_string(static_cast(header[21])); properties["Extended Version Number"] = std::to_string(static_cast(header[22])); properties["Extended Flags"] = std::to_string(static_cast(header[23])); uint32_t samples; memcpy(&samples, header + 24, 4); properties["Number of Input Samples"] = std::to_string(samples); uint16_t startType; memcpy(&startType, header + 28, 2); properties["Movie Start Type"] = std::to_string(startType); uint16_t reserved1; memcpy(&reserved1, header + 30, 2); properties["Reserved1"] = std::to_string(reserved1); uint32_t ctrlFlags; memcpy(&ctrlFlags, header + 32, 4); properties["Controller Flags"] = std::to_string(ctrlFlags); uint32_t extAuth; memcpy(&extAuth, header + 36, 4); properties["Extended Data (Authorship)"] = std::to_string(extAuth); uint32_t extBrute; memcpy(&extBrute, header + 40, 4); properties["Extended Data (Bruteforcing)"] = std::to_string(extBrute); uint32_t extHigh; memcpy(&extHigh, header + 44, 4); properties["Extended Data (High Rerecord)"] = std::to_string(extHigh); properties["ROM Internal Name"] = getString(196, 32); uint32_t crc; memcpy(&crc, header + 228, 4); properties["ROM CRC32"] = std::to_string(crc); uint16_t country; memcpy(&country, header + 232, 2); properties["ROM Country Code"] = std::to_string(country); properties["Video Plugin Name"] = getString(290, 64); properties["Sound Plugin Name"] = getString(354, 64); properties["Input Plugin Name"] = getString(418, 64); properties["RSP Plugin Name"] = getString(482, 64); properties["Author Info"] = getString(546, 222); properties["Movie Description"] = getString(768, 256); } std::string getString(int offset, int length) { std::string str(header + offset, length); str.erase(std::find(str.begin(), str.end(), '\0'), str.end()); return str; } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& newFilepath, const std::map& updates) { for (const auto& update : updates) { if (properties.count(update.first)) { properties[update.first] = update.second; } } encodeProperties(); std::ifstream inFile(filepath, std::ios::binary); std::ofstream outFile(newFilepath, std::ios::binary); outFile.write(header, 1024); char buf[1024]; inFile.seekg(1024); while (inFile.read(buf, 1024)) { outFile.write(buf, inFile.gcount()); } inFile.close(); outFile.close(); } void encodeProperties() { // Similar to decode, but write back (omitted full impl for brevity; use memcpy in reverse) // For example: std::string sig = properties["Signature"]; memcpy(header, sig.c_str(), 4); // ... Implement similar for each field, handling LE. // Note: Full encoding would mirror decode with stoi/stoul and memcpy. } }; // Example usage: // int main() { // try { // M64File m64("example.m64"); // m64.read(); // std::map updates = {{"Rerecord Count", "100"}}; // m64.write("modified.m64", updates); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-374 .M64 ===== // ===== task-376 .MAT [C++] ===== #include #include #include #include #include #include #include // Link with -lz class MatFileHandler { private: std::string filename; bool littleEndian; std::map properties; // Simplified to strings for print std::vector> elements; public: MatFileHandler(const std::string& fn) : filename(fn), littleEndian(true) {} void readDecode() { std::ifstream file(filename, std::ios::binary | std::ios::ate); std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); std::vector data(size); file.read(data.data(), size); // Header std::string text(data.begin(), data.begin() + 116); text.erase(std::remove(text.begin(), text.end(), '\0'), text.end()); // Trim nulls long long subsystemOffset; std::memcpy(&subsystemOffset, &data[116], 8); unsigned short version; std::memcpy(&version, &data[124], 2); char endian[3]; std::memcpy(endian, &data[126], 2); endian[2] = '\0'; if (std::string(endian) == "IM") { littleEndian = false; // For simplicity, assume LE; in practice, implement swap } properties["Descriptive Text"] = text; properties["Subsystem Data Offset"] = std::to_string(subsystemOffset); properties["Version"] = std::to_string(version); properties["Endian Indicator"] = endian; if (subsystemOffset > 0) { properties["Subsystem Data"] = "Present"; } // Data elements size_t offset = 128; int elementCount = 0; while (offset < static_cast(size)) { unsigned int type, bytes; std::memcpy(&type, &data[offset], 4); std::memcpy(&bytes, &data[offset + 4], 4); bool isSmall = (type & 0xFFFF0000) == 0; if (isSmall) { type &= 0xFFFF; bytes >>= 16; } size_t tagSize = isSmall ? 4 : 8; elementCount++; std::map elemProps; elemProps["Type"] = std::to_string(type); elemProps["Byte Count"] = std::to_string(bytes); elemProps["Compression Flag"] = "No"; std::vector elemData(data.begin() + offset + tagSize, data.begin() + offset + tagSize + bytes); if (type == 15) { // miCOMPRESSED elemProps["Compression Flag"] = "Yes"; uLongf decompLen = bytes * 2; // Estimate std::vector decomp(decompLen); if (uncompress(reinterpret_cast(decomp.data()), &decompLen, reinterpret_cast(elemData.data()), bytes) == Z_OK) { elemData.resize(decompLen); std::memcpy(elemData.data(), decomp.data(), decompLen); } std::memcpy(&type, elemData.data(), 4); std::memcpy(&bytes, elemData.data() + 4, 4); elemProps["Decompressed Type"] = std::to_string(type); elemProps["Decompressed Byte Count"] = std::to_string(bytes); elemData = std::vector(elemData.begin() + 8, elemData.begin() + 8 + bytes); } if (type == 14) { // miMATRIX size_t subOffset = 0; unsigned int flagBytes; std::memcpy(&flagBytes, &elemData[subOffset + 4], 4); subOffset += 8; unsigned char matrixClass = elemData[subOffset]; unsigned char flags = elemData[subOffset + 2]; unsigned int nzmax; std::memcpy(&nzmax, &elemData[subOffset + 4], 4); elemProps["Matrix Class"] = std::to_string(matrixClass); elemProps["Matrix Flags"] = std::to_string(flags); elemProps["Complex"] = (flags & 8) ? "true" : "false"; elemProps["Global"] = (flags & 4) ? "true" : "false"; elemProps["Logical"] = (flags & 2) ? "true" : "false"; elemProps["NZMax"] = std::to_string(nzmax); subOffset += flagBytes; unsigned int dimBytes; std::memcpy(&dimBytes, &elemData[subOffset + 4], 4); subOffset += 8; int numDims = dimBytes / 4; std::string dimsStr; for (int i = 0; i < numDims; i++) { int dim; std::memcpy(&dim, &elemData[subOffset + i * 4], 4); dimsStr += std::to_string(dim) + " "; } elemProps["Dimensions"] = dimsStr; subOffset += dimBytes; unsigned int nameBytes; std::memcpy(&nameBytes, &elemData[subOffset + 4], 4); subOffset += 8; std::string name(elemData.begin() + subOffset, elemData.begin() + subOffset + nameBytes); name.erase(std::remove(name.begin(), name.end(), '\0'), name.end()); elemProps["Array Name"] = name; } elements.push_back(elemProps); size_t padding = (8 - (bytes % 8)) % 8; offset += tagSize + bytes + padding; } properties["Data Element Count"] = std::to_string(elementCount); } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } for (size_t i = 0; i < elements.size(); ++i) { std::cout << "Data Element " << (i + 1) << ":" << std::endl; for (const auto& e : elements[i]) { std::cout << " " << e.first << ": " << e.second << std::endl; } } } void writeSimple(const std::string& outFilename) { std::ofstream file(outFilename, std::ios::binary); std::string headerText = "MATLAB 5.0 MAT-file, Platform: c++, Created on: Mon Sep 29 2025"; headerText.resize(116, ' '); file.write(headerText.data(), 116); char zero[8] = {0}; file.write(zero, 8); // subsystem unsigned short ver = 0x0100; file.write(reinterpret_cast(&ver), 2); file.write("MI", 2); // Simple matrix tag unsigned int matType = 14; file.write(reinterpret_cast(&matType), 4); unsigned int matBytes = 64; // Calculate based on content file.write(reinterpret_cast(&matBytes), 4); // Flags unsigned int flagType = 6; file.write(reinterpret_cast(&flagType), 4); unsigned int flagBytes = 8; file.write(reinterpret_cast(&flagBytes), 4); char flagsData[8] = {6, 0, 0, 0, 0, 0, 0, 0}; file.write(flagsData, 8); // Dims unsigned int dimType = 5; file.write(reinterpret_cast(&dimType), 4); unsigned int dimBytes = 8; file.write(reinterpret_cast(&dimBytes), 4); int dims[2] = {1, 1}; file.write(reinterpret_cast(dims), 8); // Name unsigned int nameType = 1; file.write(reinterpret_cast(&nameType), 4); unsigned int nameBytes = 4; file.write(reinterpret_cast(&nameBytes), 4); file.write("test", 4); file.write(zero, 4); // Pad // Real unsigned int realType = 9; file.write(reinterpret_cast(&realType), 4); unsigned int realBytes = 8; file.write(reinterpret_cast(&realBytes), 4); double val = 42.0; file.write(reinterpret_cast(&val), 8); } }; int main() { MatFileHandler handler("example.mat"); handler.readDecode(); handler.printProperties(); handler.writeSimple("output.mat"); return 0; } // ===== end task-376 .MAT ===== // ===== task-377 .MBOX [C++] ===== #include #include #include #include #include #include struct MboxHandler { std::string filepath; std::string content; std::vector messages; MboxHandler(const std::string& fp) : filepath(fp) { read(); } void read() { std::ifstream file(filepath, std::ios::binary); if (file) { content.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); size_t pos = 0; size_t last = 0; while ((pos = content.find("\nFrom ", last)) != std::string::npos) { messages.push_back(content.substr(last, pos - last)); last = pos + 1; } messages.push_back(content.substr(last)); } } void printProperties() { struct stat st; if (stat(filepath.c_str(), &st) == 0) { std::cout << "File name: " << filepath.substr(filepath.find_last_of("/\\") + 1) << std::endl; std::cout << "File size (in bytes): " << st.st_size << std::endl; } std::cout << "Number of messages: " << messages.size() << std::endl; bool hasCRLF = content.find("\r\n") != std::string::npos; std::cout << "Detected line ending type: " << (hasCRLF ? "CRLF" : "LF") << std::endl; bool startsWithFrom = content.rfind("From ", 0) == 0; std::cout << "Starts with \"From \": " << (startsWithFrom ? "Yes" : "No") << std::endl; std::string variant = "mboxo"; if (content.find(">From ") != std::string::npos) { variant = "mboxrd"; } else if (content.find("Content-Length:") != std::string::npos) { variant = "mboxcl or mboxcl2"; } std::cout << "Detected variant: " << variant << std::endl; } void write(const std::string& newFilepath) { std::ofstream out(newFilepath); if (out) { out << content; } } }; // Example usage: // int main() { // MboxHandler handler("path/to/file.mbox"); // handler.printProperties(); // handler.write("path/to/new_file.mbox"); // return 0; // } // ===== end task-377 .MBOX ===== // ===== task-378 .MCADDON [C] ===== #include #include #include #include typedef struct { char* filename; // Use a simple array for properties (key-value) char keys[100][50]; char values[100][50]; int count; } MCAddonHandler; void init_MCAddonHandler(MCAddonHandler* handler, char* filename) { handler->filename = filename; handler->count = 0; } void read_and_decode(MCAddonHandler* handler) { FILE *f = fopen(handler->filename, "rb"); if (!f) return; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); long offset = size - 22; while (offset >= 0) { uint32_t sig = *(uint32_t*)(data + offset); if (sig == 0x06054b50) { sprintf(handler->keys[handler->count], "End of central directory signature"); sprintf(handler->values[handler->count++], "0x%08x", sig); uint16_t num_disk = *(uint16_t*)(data + offset + 4); sprintf(handler->keys[handler->count], "Number of this disk"); sprintf(handler->values[handler->count++], "%u", num_disk); // Add similar for other fields uint32_t cd_offset = *(uint32_t*)(data + offset + 16); uint32_t cd_sig = *(uint32_t*)(data + cd_offset); if (cd_sig == 0x02014b50) { sprintf(handler->keys[handler->count], "Central file header signature"); sprintf(handler->values[handler->count++], "0x%08x", cd_sig); // Add more fields similarly } break; } offset--; } free(data); } void print_properties(MCAddonHandler* handler) { for (int i = 0; i < handler->count; i++) { printf("%s: %s\n", handler->keys[i], handler->values[i]); } } void write(MCAddonHandler* handler, char* new_filename) { FILE *src = fopen(handler->filename, "rb"); FILE *dst = fopen(new_filename, "wb"); char buf[1024]; size_t len; while ((len = fread(buf, 1, sizeof(buf), src)) > 0) { fwrite(buf, 1, len, dst); } fclose(src); fclose(dst); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s file.mcaddon\n", argv[0]); return 1; } MCAddonHandler handler; init_MCAddonHandler(&handler, argv[1]); read_and_decode(&handler); print_properties(&handler); write(&handler, "modified.mcaddon"); return 0; } // ===== end task-378 .MCADDON ===== // ===== task-379 .MCF [C++] ===== #include #include #include #include #include #include class MCFParser { private: std::string filename; std::vector> entries; public: MCFParser(const std::string& fn) : filename(fn) { read(); } void read() { entries.clear(); std::ifstream file(filename); if (!file.is_open()) { std::cerr << "Error opening file: " << filename << std::endl; return; } std::string line; while (std::getline(file, line)) { line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); if (!line.empty() && line[0] != '#') { std::istringstream iss(line); std::vector fields; std::string field; while (iss >> field) { fields.push_back(field); } if (fields.size() >= 5) { std::map entry; entry["Equipment Identifier"] = fields[0]; entry["Equipment Number"] = fields[1]; entry["Equipment Type"] = fields[2]; entry["Family Set"] = fields[3]; entry["Device State"] = fields[4]; std::string additional = "-"; if (fields.size() > 5) { additional = ""; for (size_t i = 5; i < fields.size(); ++i) { additional += fields[i] + " "; } additional.pop_back(); // Remove trailing space } entry["Additional Parameters"] = additional; entries.push_back(entry); } } } file.close(); } void printProperties() const { for (const auto& entry : entries) { for (const auto& kv : entry) { std::cout << kv.first << ": " << kv.second << std::endl; } std::cout << "---" << std::endl; } } void write(const std::string& newFilename) const { std::ofstream file(newFilename); if (!file.is_open()) { std::cerr << "Error opening file for writing: " << newFilename << std::endl; return; } file << "# Equipment Identifier Equipment Number Equipment Type Family Set Device State Additional Parameters" << std::endl; for (const auto& entry : entries) { file << entry.at("Equipment Identifier") << " " << entry.at("Equipment Number") << " " << entry.at("Equipment Type") << " " << entry.at("Family Set") << " " << entry.at("Device State") << " " << entry.at("Additional Parameters") << std::endl; } file.close(); } }; // Example usage: // int main() { // MCFParser parser("example.mcf"); // parser.printProperties(); // parser.write("new.mcf"); // return 0; // } // ===== end task-379 .MCF ===== // ===== task-380 .MCMETA [C++] ===== #include #include #include #include using json = nlohmann::json; class McMetaHandler { private: std::string filepath; json data; public: McMetaHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath); if (!file.is_open()) { throw std::runtime_error("File " + filepath + " not found."); } file >> data; file.close(); } void printProperties() { if (data.is_null()) { std::cout << "No data loaded. Call read() first." << std::endl; return; } std::cout << data.dump(4) << std::endl; } void write(const std::string& outputPath = "") { if (data.is_null()) { std::cout << "No data to write. Load or set data first." << std::endl; return; } std::string path = outputPath.empty() ? filepath : outputPath; std::ofstream file(path); file << data.dump(4); file.close(); std::cout << "Written to " << path << std::endl; } }; // Example usage: // int main() { // try { // McMetaHandler handler("example.mcmeta"); // handler.read(); // handler.printProperties(); // handler.data["pack"]["description"] = "Updated"; // handler.write("updated.mcmeta"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-380 .MCMETA ===== // ===== task-381 .MCPACK [C] ===== #include #include #include #include #include "cJSON.h" // Assume cJSON.h and cJSON.c compiled in typedef struct { char* filepath; cJSON* data; // For other files: use a simple map (array of key-value for simplicity) struct OtherFile { char* name; void* content; size_t size; } *other_files; int other_count; } McPack; void mcpack_init(McPack* self, const char* filepath) { self->filepath = strdup(filepath); self->data = NULL; self->other_files = NULL; self->other_count = 0; mcpack_read(self); } void mcpack_read(McPack* self) { zip_t* za = zip_open(self->filepath, ZIP_RDONLY, NULL); if (!za) { fprintf(stderr, "Error opening ZIP\n"); return; } int num_entries = zip_get_num_entries(za, 0); self->other_files = malloc(num_entries * sizeof(struct OtherFile)); for (int i = 0; i < num_entries; i++) { const char* name = zip_get_name(za, i, 0); if (strcmp(name, "manifest.json") == 0) { zip_file_t* zf = zip_fopen_index(za, i, 0); zip_stat_t sb; zip_stat_index(za, i, 0, &sb); char* buffer = malloc(sb.size + 1); zip_fread(zf, buffer, sb.size); buffer[sb.size] = '\0'; self->data = cJSON_Parse(buffer); free(buffer); zip_fclose(zf); } else { zip_file_t* zf = zip_fopen_index(za, i, 0); zip_stat_t sb; zip_stat_index(za, i, 0, &sb); void* buffer = malloc(sb.size); zip_fread(zf, buffer, sb.size); self->other_files[self->other_count].name = strdup(name); self->other_files[self->other_count].content = buffer; self->other_files[self->other_count].size = sb.size; self->other_count++; zip_fclose(zf); } } zip_close(za); } void mcpack_print_properties(McPack* self) { if (self->data) { dump_properties(self->data, ""); } else { printf("No manifest.json found.\n"); } } void dump_properties(cJSON* item, const char* prefix) { if (cJSON_IsObject(item)) { cJSON* child = item->child; while (child) { printf("%s%s: ", prefix, child->string); if (cJSON_IsObject(child) || cJSON_IsArray(child)) { printf("\n"); char new_prefix[1024]; snprintf(new_prefix, sizeof(new_prefix), "%s ", prefix); dump_properties(child, new_prefix); } else if (cJSON_IsString(child)) { printf("%s\n", child->valuestring); } else if (cJSON_IsNumber(child)) { printf("%f\n", child->valuedouble); } else if (cJSON_IsBool(child)) { printf("%s\n", child->valueint ? "true" : "false"); } else if (cJSON_IsNull(child)) { printf("null\n"); } child = child->next; } } else if (cJSON_IsArray(item)) { int i = 0; cJSON* child = item->child; while (child) { printf("%s[%d]: \n", prefix, i++); char new_prefix[1024]; snprintf(new_prefix, sizeof(new_prefix), "%s ", prefix); dump_properties(child, new_prefix); child = child->next; } } } void mcpack_write(McPack* self, const char* new_filepath) { zip_t* za = zip_open(new_filepath, ZIP_CREATE | ZIP_TRUNCATE, NULL); if (!za) { fprintf(stderr, "Error creating ZIP\n"); return; } // Write other files for (int i = 0; i < self->other_count; i++) { zip_source_t* src = zip_source_buffer(za, self->other_files[i].content, self->other_files[i].size, 0); zip_file_add(za, self->other_files[i].name, src, ZIP_FL_OVERWRITE); } // Write manifest char* json_str = cJSON_Print(self->data); zip_source_t* src = zip_source_buffer(za, json_str, strlen(json_str), 0); zip_file_add(za, "manifest.json", src, ZIP_FL_OVERWRITE); zip_close(za); free(json_str); } void mcpack_destroy(McPack* self) { free(self->filepath); cJSON_Delete(self->data); for (int i = 0; i < self->other_count; i++) { free(self->other_files[i].name); free(self->other_files[i].content); } free(self->other_files); } // Example usage: // int main() { // McPack pack; // mcpack_init(&pack, "example.mcpack"); // mcpack_print_properties(&pack); // // Modify: cJSON_ReplaceItemInObject(pack.data->child, "name", cJSON_CreateString("Updated Name")); // mcpack_write(&pack, "updated.mcpack"); // mcpack_destroy(&pack); // return 0; // } // ===== end task-381 .MCPACK ===== // ===== task-382 .MCPROJECT [C++] ===== #include #include #include // Assume an NBT library like libnbt++ class MCProjectHandler { private: std::string filepath; nbt_tag_t* nbtData; // Assume NBT struct from library public: MCProjectHandler(const std::string& fp) : filepath(fp), nbtData(nullptr) {} ~MCProjectHandler() { if (nbtData) nbt_free(nbtData); } void read() { zip_t* zip = zip_open(filepath.c_str(), ZIP_RDONLY, nullptr); if (zip) { zip_file_t* file = zip_fopen(zip, "level.dat", 0); if (file) { // Read buffer zip_stat_t stat; zip_stat(zip, "level.dat", 0, &stat); char* buffer = new char[stat.size]; zip_fread(file, buffer, stat.size); nbtData = nbt_parse(buffer, stat.size); // Use library delete[] buffer; zip_fclose(file); } zip_close(zip); } } void printProperties() { if (!nbtData) read(); // Assume library has a dump function nbt_dump(nbtData, std::cout, 0); // Or implement recursion to print tags } void write(const std::string& newFilepath) { if (!nbtData) return; zip_t* zip = zip_open(newFilepath.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); if (zip) { zip_source_t* source = zip_source_buffer_create(nullptr, 0, 0, nullptr); // Write NBT to buffer using library size_t size; char* buffer = nbt_encode(nbtData, &size); zip_source_buffer(zip, source, buffer, size, 1); zip_add(zip, "level.dat", source); zip_close(zip); free(buffer); } } }; // Example usage: // int main() { // MCProjectHandler handler("example.mcproject"); // handler.read(); // handler.printProperties(); // // Modify nbtData // handler.write("modified.mcproject"); // return 0; // } // ===== end task-382 .MCPROJECT ===== // ===== task-383 .MCSTRUCTURE [C++] ===== #include #include #include #include #include #include // For little-endian, assume or use htole* #include // C++17 for variant types using NBTValue = std::variant, std::vector, std::map, std::vector, std::vector>; class MCStructure { private: std::map properties; public: MCStructure(const std::string& filepath = "") { if (!filepath.empty()) load(filepath); } void load(const std::string& filepath) { std::ifstream f(filepath, std::ios::binary); if (!f) return; std::vector data((std::istreambuf_iterator(f)), std::istreambuf_iterator()); size_t pos = 0; properties = std::get>(parseNBT(data, pos).second); } std::pair parseTag(const std::vector& data, size_t pos, int type) { switch (type) { case 1: return {pos + 1, *reinterpret_cast(&data[pos])}; case 2: { int16_t val = le16toh(*reinterpret_cast(&data[pos])); return {pos + 2, val}; } case 3: { int32_t val = le32toh(*reinterpret_cast(&data[pos])); return {pos + 4, val}; } case 4: { int64_t val = le64toh(*reinterpret_cast(&data[pos])); return {pos + 8, val}; } case 5: { uint32_t raw = le32toh(*reinterpret_cast(&data[pos])); return {pos + 4, *reinterpret_cast(&raw)}; } case 6: { uint64_t raw = le64toh(*reinterpret_cast(&data[pos])); return {pos + 8, *reinterpret_cast(&raw)}; } case 8: { uint16_t len = le16toh(*reinterpret_cast(&data[pos])); pos += 2; std::string str(&data[pos], len); return {pos + len, str}; } case 7: { int32_t len = le32toh(*reinterpret_cast(&data[pos])); pos += 4; std::vector arr(&data[pos], &data[pos + len]); return {pos + len, arr}; } case 9: { int listType = static_cast(data[pos]); pos += 1; int32_t len = le32toh(*reinterpret_cast(&data[pos])); pos += 4; std::vector list; for (int i = 0; i < len; i++) { auto [newPos, val] = parseTag(data, pos, listType); pos = newPos; list.push_back(val); } return {pos, list}; } case 10: { std::map compound; while (true) { auto [newPos, tag] = parseNBT(data, pos); pos = newPos; if (std::holds_alternative(tag)) break; compound.insert(std::get>(tag).begin()); } return {pos, compound}; } case 11: { int32_t len = le32toh(*reinterpret_cast(&data[pos])); pos += 4; std::vector arr; for (int i = 0; i < len; i++) { arr.push_back(le32toh(*reinterpret_cast(&data[pos]))); pos += 4; } return {pos, arr}; } case 12: { int32_t len = le32toh(*reinterpret_cast(&data[pos])); pos += 4; std::vector arr; for (int i = 0; i < len; i++) { arr.push_back(le64toh(*reinterpret_cast(&data[pos]))); pos += 8; } return {pos, arr}; } default: throw std::runtime_error("Unknown NBT type"); } } std::pair parseNBT(const std::vector& data, size_t pos) { int type = static_cast(data[pos]); pos += 1; if (type == 0) return {pos, std::monostate{}}; uint16_t nameLen = le16toh(*reinterpret_cast(&data[pos])); pos += 2; std::string name(&data[pos], nameLen); pos += nameLen; auto [newPos, value] = parseTag(data, pos, type); return {newPos, std::map{{name, value}}}; } void printProperties() { // Implement printing using std::visit or recursive std::cout << "Properties printing not fully implemented for brevity." << std::endl; } void write(const std::string& filepath) { // Implement encode similar to others // Omitted for brevity } }; // Example // int main() { // MCStructure mc("example.mcstructure"); // mc.printProperties(); // mc.write("output.mcstructure"); // return 0; // } // ===== end task-383 .MCSTRUCTURE ===== // ===== task-385 .MCWORLD [C++] ===== #include #include #include #include #include // libzip class MCWorldHandler { private: std::string filename; std::map properties; // Simplified to string values public: MCWorldHandler(const std::string& fn) : filename(fn) {} void open() { zip_t* z = zip_open(filename.c_str(), ZIP_RDONLY, nullptr); if (z) { zip_file_t* f = zip_fopen(z, "level.dat", 0); if (f) { // Read buffer struct zip_stat st; zip_stat_init(&st); zip_stat(z, "level.dat", 0, &st); char* buffer = new char[st.size]; zip_fread(f, buffer, st.size); parseNBT(buffer, st.size); delete[] buffer; zip_fclose(f); } zip_close(z); } } void parseNBT(const char* buffer, size_t size) { // Simplified NBT parser (parse as key-value strings for demo) // Implement full parser here // For example: properties["LevelName"] = "ExampleWorld"; // Placeholder properties["RandomSeed"] = "1234567890"; // Etc. } void printProperties() { for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } void write(const std::string& newFilename, const std::string& modifyKey, const std::string& newValue) { properties[modifyKey] = newValue; zip_t* newZ = zip_open(newFilename.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); if (newZ) { // Add level.dat (simplified) std::string dummyNBT = "Placeholder NBT data"; zip_source_t* src = zip_source_buffer(newZ, dummyNBT.c_str(), dummyNBT.size(), 0); zip_add(newZ, "level.dat", src); // Copy other files from original zip_t* oldZ = zip_open(filename.c_str(), ZIP_RDONLY, nullptr); if (oldZ) { int num = zip_get_num_entries(oldZ, 0); for (int i = 0; i < num; i++) { const char* name = zip_get_name(oldZ, i, 0); if (std::string(name) != "level.dat") { zip_file_t* f = zip_fopen_index(oldZ, i, 0); if (f) { zip_stat_t st; zip_stat_index(oldZ, i, 0, &st); char* buf = new char[st.size]; zip_fread(f, buf, st.size); zip_source_t* s = zip_source_buffer(newZ, buf, st.size, 1); zip_add(newZ, name, s); zip_fclose(f); } } } zip_close(oldZ); } zip_close(newZ); } } }; // Example usage // int main() { // MCWorldHandler handler("example.mcworld"); // handler.open(); // handler.printProperties(); // handler.write("modified.mcworld", "LevelName", "New Name"); // return 0; // } // ===== end task-385 .MCWORLD ===== // ===== task-386 .MD [C++] ===== #include #include #include class MDFile { private: std::string filename; std::string content; public: MDFile(const std::string& fn) : filename(fn), content("") {} void openAndRead() { std::ifstream file(filename); if (file.is_open()) { std::string line; while (std::getline(file, line)) { content += line + "\n"; } file.close(); } else { std::cerr << "Unable to open file" << std::endl; } } std::string getContent() const { return content; } void write(const std::string& cnt) { std::ofstream file(filename); if (file.is_open()) { file << cnt; file.close(); } else { std::cerr << "Unable to open file for writing" << std::endl; } } void printProperties() const { std::cout << "Filename extensions: .md, .markdown" << std::endl; std::cout << "Internet media type: text/markdown" << std::endl; std::cout << "Uniform Type Identifier (UTI): net.daringfireball.markdown" << std::endl; std::cout << "UTI Conformation: public.plain-text" << std::endl; std::cout << "Magic Number: None" << std::endl; std::cout << "Type of format: Open file format" << std::endl; } }; // ===== end task-386 .MD ===== // ===== task-387 .MDB [C++] ===== #include #include #include #include #include #include #include std::vector rc4(const std::vector& key, const std::vector& data) { std::vector s(256); for (int i = 0; i < 256; ++i) s[i] = i; int j = 0; for (int i = 0; i < 256; ++i) { j = (j + s[i] + key[i % key.size()]) % 256; std::swap(s[i], s[j]); } int i = 0; j = 0; std::vector output(data.size()); for (size_t k = 0; k < data.size(); ++k) { i = (i + 1) % 256; j = (j + s[i]) % 256; std::swap(s[i], s[j]); output[k] = data[k] ^ s[(s[i] + s[j]) % 256]; } return output; } class MDBParser { private: std::string filename; std::vector data; std::map properties; public: MDBParser(const std::string& fn) : filename(fn) {} void open() { std::ifstream file(filename, std::ios::binary); if (!file) throw std::runtime_error("Cannot open file"); file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0); data.resize(size); file.read(reinterpret_cast(data.data()), size); if (size < 4096) throw std::runtime_error("File too small"); } void decode() { if (data.empty()) throw std::runtime_error("File not opened"); std::stringstream sigSs; for (int b = 0; b < 4; ++b) sigSs << std::hex << std::setw(2) << std::setfill('0') << (int)data[b] << " "; std::string sig = sigSs.str(); sig.pop_back(); std::string formatId(reinterpret_cast(&data[4]), 20); uint8_t jetVer = data[0x14]; uint8_t fileType = data[0x15]; uint16_t sysCollation = *reinterpret_cast(&data[0x16]); uint16_t codePage = *reinterpret_cast(&data[0x1C]); uint32_t dbKey = *reinterpret_cast(&data[0x1E]); int pageSize = (jetVer == 0) ? 2048 : 4096; std::string encrypted = (dbKey != 0) ? "Yes" : "No"; std::vector key = {0xc7, 0xda, 0x39, 0x6b}; // Little-endian 0x6b39dac7 int encLength = (jetVer == 0) ? 126 : 128; std::vector encData(data.begin() + 0x18, data.begin() + 0x18 + encLength); std::vector decData = rc4(key, encData); int pwdLength = (jetVer == 0) ? 20 : 40; std::stringstream pwdSs; for (int b = 0x42 - 0x18; b < 0x42 - 0x18 + pwdLength; ++b) pwdSs << std::hex << std::setw(2) << std::setfill('0') << (int)decData[b] << " "; std::string password = pwdSs.str(); password.pop_back(); uint16_t defaultSort = *reinterpret_cast(&decData[0x66 - 0x18]); uint64_t creationRaw = *reinterpret_cast(&decData[0x72 - 0x18]); time_t epoch = (creationRaw / 10000000) - 11644473600LL; char dateBuf[32]; std::strftime(dateBuf, sizeof(dateBuf), "%Y-%m-%dT%H:%M:%S", std::gmtime(&epoch)); uint32_t numPages = *reinterpret_cast(&data[0x08]); properties["Signature"] = sig; properties["Format ID"] = formatId; properties["Jet Version"] = std::to_string(jetVer); properties["File Type"] = std::to_string(fileType); properties["System Collation"] = std::to_string(sysCollation); properties["Code Page"] = std::to_string(codePage); properties["Database Key"] = std::to_string(dbKey); properties["Encrypted"] = encrypted; properties["Page Size"] = std::to_string(pageSize); properties["Database Password (hex)"] = password; properties["Default Sort Order"] = std::to_string(defaultSort); properties["Creation Date"] = dateBuf; properties["Number of Pages"] = std::to_string(numPages); } void printProperties() { for (const auto& [key, value] : properties) { std::cout << key << ": " << value << std::endl; } } void write(const std::string& newFilename = "", std::map modify = {}) { if (data.empty()) throw std::runtime_error("File not opened"); std::vector newData = data; if (modify.count("creation_date")) { struct tm tm = {}; strptime(modify["creation_date"].c_str(), "%Y-%m-%dT%H:%M:%S", &tm); uint64_t newTime = (static_cast(mktime(&tm)) + 11644473600LL) * 10000000; uint8_t jetVer = newData[0x14]; int encLength = (jetVer == 0) ? 126 : 128; std::vector encData(newData.begin() + 0x18, newData.begin() + 0x18 + encLength); std::vector key = {0xc7, 0xda, 0x39, 0x6b}; std::vector decData = rc4(key, encData); *reinterpret_cast(&decData[0x72 - 0x18]) = newTime; std::vector newEnc = rc4(key, decData); std::copy(newEnc.begin(), newEnc.end(), newData.begin() + 0x18); } std::string outFile = newFilename.empty() ? filename + ".modified" : newFilename; std::ofstream out(outFile, std::ios::binary); out.write(reinterpret_cast(newData.data()), newData.size()); std::cout << "Written to " << outFile << std::endl; } }; int main(int argc, char** argv) { if (argc < 2) return 1; try { MDBParser parser(argv[1]); parser.open(); parser.decode(); parser.printProperties(); // Example: std::map modify; modify["creation_date"] = "2025-09-29T12:00:00"; parser.write("", modify); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } return 0; } // ===== end task-387 .MDB ===== // ===== task-388 .MDF [C] ===== #include #include #include #include typedef struct { char* filepath; char file_id[9]; char format_id[9]; char program_id[9]; uint16_t byte_order; uint16_t fp_format; uint16_t ver_major; uint16_t ver_minor; uint16_t code_page; uint16_t standard_flags; uint16_t custom_flags; uint64_t timestamp; int16_t utc_offset; uint16_t time_quality; char timer_id[33]; char* author; char* org; char* project; char* subject; char* file_comment; int num_data_groups; int num_attachments; int num_file_history; } MDFHandler; MDFHandler* mdf_create(const char* filepath) { MDFHandler* handler = malloc(sizeof(MDFHandler)); handler->filepath = strdup(filepath); handler->author = NULL; handler->org = NULL; handler->project = NULL; handler->subject = NULL; handler->file_comment = NULL; return handler; } void mdf_read(MDFHandler* handler) { FILE* f = fopen(handler->filepath, "rb"); if (!f) return; // IDBLOCK char id_data[64]; fread(id_data, 64, 1, f); strncpy(handler->file_id, id_data, 8); handler->file_id[8] = '\0'; strncpy(handler->format_id, id_data + 8, 8); handler->format_id[8] = '\0'; strncpy(handler->program_id, id_data + 16, 8); handler->program_id[8] = '\0'; memcpy(&handler->byte_order, id_data + 24, 2); memcpy(&handler->fp_format, id_data + 26, 2); memcpy(&handler->ver_major, id_data + 28, 2); memcpy(&handler->ver_minor, id_data + 30, 2); memcpy(&handler->code_page, id_data + 32, 2); memcpy(&handler->standard_flags, id_data + 60, 2); memcpy(&handler->custom_flags, id_data + 62, 2); // HDBLOCK fseek(f, 64, SEEK_SET); char hd_data[184]; fread(hd_data, 184, 1, f); char hd_id[5]; strncpy(hd_id, hd_data, 4); hd_id[4] = '\0'; if (strcmp(hd_id, "##HD") != 0) { fclose(f); return; } uint64_t block_len, links_nr, first_dg_addr, file_comment_addr, author_addr, org_addr, project_addr, subject_addr; memcpy(&block_len, hd_data + 8, 8); memcpy(&links_nr, hd_data + 16, 8); memcpy(&first_dg_addr, hd_data + 24, 8); memcpy(&file_comment_addr, hd_data + 32, 8); memcpy(&author_addr, hd_data + 40, 8); memcpy(&org_addr, hd_data + 48, 8); memcpy(&project_addr, hd_data + 56, 8); memcpy(&subject_addr, hd_data + 64, 8); memcpy(&handler->timestamp, hd_data + 72, 8); memcpy(&handler->utc_offset, hd_data + 80, 2); memcpy(&handler->time_quality, hd_data + 82, 2); strncpy(handler->timer_id, hd_data + 84, 32); handler->timer_id[32] = '\0'; // Read TX handler->file_comment = read_tx(f, file_comment_addr); handler->author = read_tx(f, author_addr); handler->org = read_tx(f, org_addr); handler->project = read_tx(f, project_addr); handler->subject = read_tx(f, subject_addr); // Counts handler->num_data_groups = count_dg(f, first_dg_addr); handler->num_attachments = links_nr - 5; // Approximate handler->num_file_history = 0; // Simplified fclose(f); } char* read_tx(FILE* f, uint64_t addr) { if (addr == 0) return strdup(""); fseek(f, addr, SEEK_SET); char data[32]; fread(data, 32, 1, f); char id[5]; strncpy(id, data, 4); id[4] = '\0'; if (strcmp(id, "##TX") != 0) return strdup("Invalid TXBLOCK"); uint64_t text_len; memcpy(&text_len, data + 24, 8); char* text = malloc(text_len + 1); fseek(f, addr + 32, SEEK_SET); fread(text, text_len, 1, f); text[text_len] = '\0'; return text; } int count_dg(FILE* f, uint64_t addr) { int count = 0; while (addr != 0) { count++; fseek(f, addr + 8, SEEK_SET); fread(&addr, 8, 1, f); } return count; } void mdf_print_properties(MDFHandler* handler) { printf("File Identifier: %s\n", handler->file_id); printf("Format Identifier: %s\n", handler->format_id); printf("Program Identifier: %s\n", handler->program_id); printf("Default Byte Order: %u\n", handler->byte_order); printf("Default Floating Point Format: %u\n", handler->fp_format); printf("Version Major: %u\n", handler->ver_major); printf("Version Minor: %u\n", handler->ver_minor); printf("Code Page Number: %u\n", handler->code_page); printf("Standard Flags: %u\n", handler->standard_flags); printf("Custom Unfinalized Flags: %u\n", handler->custom_flags); printf("Start Timestamp: %llu\n", handler->timestamp); printf("UTC Offset: %d\n", handler->utc_offset); printf("Time Quality: %u\n", handler->time_quality); printf("Timer Identification: %s\n", handler->timer_id); printf("Author: %s\n", handler->author); printf("Organization: %s\n", handler->org); printf("Project: %s\n", handler->project); printf("Subject: %s\n", handler->subject); printf("File Comment: %s\n", handler->file_comment); printf("Number of Data Groups: %d\n", handler->num_data_groups); printf("Number of Attachments: %d\n", handler->num_attachments); printf("Number of File History Entries: %d\n", handler->num_file_history); } void mdf_write(MDFHandler* handler, const char* new_filepath) { FILE* src = fopen(handler->filepath, "rb"); FILE* dst = fopen(new_filepath, "wb"); char buffer[1024]; size_t bytes; while ((bytes = fread(buffer, 1, sizeof(buffer), src)) > 0) { fwrite(buffer, 1, bytes, dst); } fclose(src); fclose(dst); // For full write, update bytes in place } void mdf_destroy(MDFHandler* handler) { free(handler->filepath); free(handler->author); free(handler->org); free(handler->project); free(handler->subject); free(handler->file_comment); free(handler); } // Example usage // int main() { // MDFHandler* handler = mdf_create("example.mdf"); // mdf_read(handler); // mdf_print_properties(handler); // mdf_write(handler, "modified.mdf"); // mdf_destroy(handler); // return 0; // } // ===== end task-388 .MDF ===== // ===== task-390 .MDI [C] ===== #include #include #include typedef struct { char *filepath; int is_valid; } MDIHandler; const char *properties[] = { "File extension: .mdi", "Magic number (header signature): 45 50 2A 00 (ASCII 'EP*\\0')", "MIME type: image/vnd.ms-modi", "PRONOM identifier: fmt/881", "Proprietary: Yes (Microsoft-specific)", "Base format: Tagged Image File Format (TIFF) with custom header and additional compression schemes", "Compression codes: 34718 (Binary Level Codec - BLC), 34719 (MODI_VECTOR), 34720 (Progressive Transform Codec - PTC)", "Supported image types: Monochrome (compressed in MODI BW), Grayscale or Color (compressed in MODI Color)", "Maximum resolution: Images over 900 DPI are downsampled to 900 DPI", "OCR support: Can store optical character recognition (OCR) text alongside images", "File size advantage: Reduced disk space compared to equivalent TIFF files", "Image fidelity: Improved quality compared to TIFF with lossless compression (e.g., LZW)", "Multi-page support: Yes (page layout structure like TIFF)", "Compatibility: Can only be opened/edited in Microsoft Office Document Imaging (MODI); TIFF is recommended for sharing", NULL // Sentinel }; MDIHandler* mdi_create(const char *filepath) { MDIHandler *handler = malloc(sizeof(MDIHandler)); handler->filepath = strdup(filepath); handler->is_valid = 0; return handler; } int mdi_read(MDIHandler *handler) { FILE *f = fopen(handler->filepath, "rb"); if (!f) { printf("Cannot open file.\n"); return 0; } unsigned char header[4]; fread(header, 1, 4, f); fclose(f); if (header[0] == 0x45 && header[1] == 0x50 && header[2] == 0x2A && header[3] == 0x00) { handler->is_valid = 1; } else { printf("Invalid .MDI file: Magic number does not match.\n"); return 0; } return 1; } void mdi_decode_and_print_properties(MDIHandler *handler) { if (mdi_read(handler)) { printf("Valid .MDI file detected. Properties:\n"); for (int i = 0; properties[i] != NULL; i++) { printf("- %s\n", properties[i]); } } } void mdi_write(MDIHandler *handler, const char *output_path) { if (!handler->is_valid) { printf("Cannot write: No valid .MDI file loaded.\n"); return; } FILE *f_in = fopen(handler->filepath, "rb"); FILE *f_out = fopen(output_path, "wb"); if (!f_in || !f_out) { printf("File operation failed.\n"); if (f_in) fclose(f_in); if (f_out) fclose(f_out); return; } char buffer[1024]; size_t length; while ((length = fread(buffer, 1, sizeof(buffer), f_in)) > 0) { fwrite(buffer, 1, length, f_out); } fclose(f_in); fclose(f_out); printf(" .MDI file written to %s\n", output_path); } void mdi_destroy(MDIHandler *handler) { free(handler->filepath); free(handler); } // Example usage // int main() { // MDIHandler *mdi = mdi_create("sample.mdi"); // mdi_decode_and_print_properties(mdi); // mdi_write(mdi, "output.mdi"); // mdi_destroy(mdi); // return 0; // } // ===== end task-390 .MDI ===== // ===== task-391 .MDL [C] ===== #include #include #include typedef struct { int ident; int version; float scale[3]; float translate[3]; float boundingradius; float eyeposition[3]; int num_skins; int skinwidth; int skinheight; int num_verts; int num_tris; int num_frames; int synctype; int flags; float size; } mdl_header_t; typedef struct { int type; void* data; // For type 0: unsigned char* pixels; For type 1: struct {int num_group; float* times; unsigned char** pixels_list;} } mdl_skin_t; typedef struct { int onseam; int s; int t; } mdl_texcoord_t; typedef struct { int facesfront; int vertices[3]; } mdl_triangle_t; typedef struct { unsigned char v[3]; unsigned char lightnormalindex; } mdl_trivertx_t; typedef struct { int type; void* data; // For type 0: struct {mdl_trivertx_t bboxmin; mdl_trivertx_t bboxmax; char name[16]; mdl_trivertx_t* verts;} // For type 1: struct {int num_group; float* min_times; void* subframes;} where subframes are array of type 0 data } mdl_frame_t; typedef struct { char* filename; FILE* file; mdl_header_t header; mdl_skin_t* skins; mdl_texcoord_t* texcoords; mdl_triangle_t* triangles; mdl_frame_t* frames; } MDLFile; // Helper structs for groups typedef struct { int num_group; float* times; unsigned char** pixels_list; } mdl_skin_group_t; typedef struct { mdl_trivertx_t bboxmin; mdl_trivertx_t bboxmax; char name[16]; mdl_trivertx_t* verts; } mdl_simpleframe_t; typedef struct { int num_group; float* min_times; mdl_simpleframe_t* subframes; } mdl_frame_group_t; MDLFile* mdl_create(const char* filename) { MDLFile* mdl = (MDLFile*)malloc(sizeof(MDLFile)); mdl->filename = strdup(filename); mdl->file = NULL; mdl->skins = NULL; mdl->texcoords = NULL; mdl->triangles = NULL; mdl->frames = NULL; return mdl; } void mdl_destroy(MDLFile* mdl) { // Free allocated memory (omitted for brevity, need to free arrays, subarrays, etc.) free(mdl->filename); free(mdl); } int mdl_read(MDLFile* mdl) { mdl->file = fopen(mdl->filename, "rb"); if (!mdl->file) return -1; fread(&mdl->header, sizeof(mdl_header_t), 1, mdl->file); // Allocate mdl->skins = (mdl_skin_t*)malloc(mdl->header.num_skins * sizeof(mdl_skin_t)); mdl->texcoords = (mdl_texcoord_t*)malloc(mdl->header.num_verts * sizeof(mdl_texcoord_t)); mdl->triangles = (mdl_triangle_t*)malloc(mdl->header.num_tris * sizeof(mdl_triangle_t)); mdl->frames = (mdl_frame_t*)malloc(mdl->header.num_frames * sizeof(mdl_frame_t)); // Read skins for (int i = 0; i < mdl->header.num_skins; i++) { fread(&mdl->skins[i].type, sizeof(int), 1, mdl->file); if (mdl->skins[i].type == 0) { unsigned char* pixels = (unsigned char*)malloc(mdl->header.skinwidth * mdl->header.skinheight); fread(pixels, 1, mdl->header.skinwidth * mdl->header.skinheight, mdl->file); mdl->skins[i].data = pixels; } else { mdl_skin_group_t* group = (mdl_skin_group_t*)malloc(sizeof(mdl_skin_group_t)); fread(&group->num_group, sizeof(int), 1, mdl->file); group->times = (float*)malloc(group->num_group * sizeof(float)); fread(group->times, sizeof(float), group->num_group, mdl->file); group->pixels_list = (unsigned char**)malloc(group->num_group * sizeof(unsigned char*)); for (int j = 0; j < group->num_group; j++) { group->pixels_list[j] = (unsigned char*)malloc(mdl->header.skinwidth * mdl->header.skinheight); fread(group->pixels_list[j], 1, mdl->header.skinwidth * mdl->header.skinheight, mdl->file); } mdl->skins[i].data = group; } } // Read texcoords fread(mdl->texcoords, sizeof(mdl_texcoord_t), mdl->header.num_verts, mdl->file); // Read triangles fread(mdl->triangles, sizeof(mdl_triangle_t), mdl->header.num_tris, mdl->file); // Read frames for (int i = 0; i < mdl->header.num_frames; i++) { fread(&mdl->frames[i].type, sizeof(int), 1, mdl->file); if (mdl->frames[i].type == 0) { mdl_simpleframe_t* simple = (mdl_simpleframe_t*)malloc(sizeof(mdl_simpleframe_t)); fread(&simple->bboxmin, sizeof(mdl_trivertx_t), 1, mdl->file); fread(&simple->bboxmax, sizeof(mdl_trivertx_t), 1, mdl->file); fread(simple->name, 1, 16, mdl->file); simple->verts = (mdl_trivertx_t*)malloc(mdl->header.num_verts * sizeof(mdl_trivertx_t)); fread(simple->verts, sizeof(mdl_trivertx_t), mdl->header.num_verts, mdl->file); mdl->frames[i].data = simple; } else { mdl_frame_group_t* group = (mdl_frame_group_t*)malloc(sizeof(mdl_frame_group_t)); fread(&group->num_group, sizeof(int), 1, mdl->file); group->min_times = (float*)malloc(group->num_group * sizeof(float)); fread(group->min_times, sizeof(float), group->num_group, mdl->file); group->subframes = (mdl_simpleframe_t*)malloc(group->num_group * sizeof(mdl_simpleframe_t)); for (int j = 0; j < group->num_group; j++) { fread(&group->subframes[j].bboxmin, sizeof(mdl_trivertx_t), 1, mdl->file); fread(&group->subframes[j].bboxmax, sizeof(mdl_trivertx_t), 1, mdl->file); fread(group->subframes[j].name, 1, 16, mdl->file); group->subframes[j].verts = (mdl_trivertx_t*)malloc(mdl->header.num_verts * sizeof(mdl_trivertx_t)); fread(group->subframes[j].verts, sizeof(mdl_trivertx_t), mdl->header.num_verts, mdl->file); } mdl->frames[i].data = group; } } fclose(mdl->file); return 0; } void mdl_print_properties(MDLFile* mdl) { printf("Header:\n"); printf(" ident: %d\n", mdl->header.ident); printf(" version: %d\n", mdl->header.version); printf(" scale: [%f, %f, %f]\n", mdl->header.scale[0], mdl->header.scale[1], mdl->header.scale[2]); // ... (print all header fields similarly) // For brevity, printing all would follow similar pattern for skins, texcoords, etc. // Implement full printing as needed. } int mdl_write(MDLFile* mdl, const char* output_filename) { FILE* out = fopen(output_filename, "wb"); if (!out) return -1; fwrite(&mdl->header, sizeof(mdl_header_t), 1, out); // Write skins for (int i = 0; i < mdl->header.num_skins; i++) { fwrite(&mdl->skins[i].type, sizeof(int), 1, out); if (mdl->skins[i].type == 0) { fwrite(mdl->skins[i].data, 1, mdl->header.skinwidth * mdl->header.skinheight, out); } else { mdl_skin_group_t* group = (mdl_skin_group_t*)mdl->skins[i].data; fwrite(&group->num_group, sizeof(int), 1, out); fwrite(group->times, sizeof(float), group->num_group, out); for (int j = 0; j < group->num_group; j++) { fwrite(group->pixels_list[j], 1, mdl->header.skinwidth * mdl->header.skinheight, out); } } } // Write texcoords fwrite(mdl->texcoords, sizeof(mdl_texcoord_t), mdl->header.num_verts, out); // Write triangles fwrite(mdl->triangles, sizeof(mdl_triangle_t), mdl->header.num_tris, out); // Write frames for (int i = 0; i < mdl->header.num_frames; i++) { fwrite(&mdl->frames[i].type, sizeof(int), 1, out); if (mdl->frames[i].type == 0) { mdl_simpleframe_t* simple = (mdl_simpleframe_t*)mdl->frames[i].data; fwrite(&simple->bboxmin, sizeof(mdl_trivertx_t), 1, out); fwrite(&simple->bboxmax, sizeof(mdl_trivertx_t), 1, out); fwrite(simple->name, 1, 16, out); fwrite(simple->verts, sizeof(mdl_trivertx_t), mdl->header.num_verts, out); } else { mdl_frame_group_t* group = (mdl_frame_group_t*)mdl->frames[i].data; fwrite(&group->num_group, sizeof(int), 1, out); fwrite(group->min_times, sizeof(float), group->num_group, out); for (int j = 0; j < group->num_group; j++) { fwrite(&group->subframes[j].bboxmin, sizeof(mdl_trivertx_t), 1, out); fwrite(&group->subframes[j].bboxmax, sizeof(mdl_trivertx_t), 1, out); fwrite(group->subframes[j].name, 1, 16, out); fwrite(group->subframes[j].verts, sizeof(mdl_trivertx_t), mdl->header.num_verts, out); } } } fclose(out); return 0; } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s input.mdl [output.mdl]\n", argv[0]); return 1; } MDLFile* mdl = mdl_create(argv[1]); if (mdl_read(mdl) != 0) { printf("Error reading file\n"); return 1; } mdl_print_properties(mdl); if (argc > 2) { mdl_write(mdl, argv[2]); } mdl_destroy(mdl); return 0; } // ===== end task-391 .MDL ===== // ===== task-392 .MDMP [C] ===== #include #include #include #include #include typedef struct { char signature[5]; // Null-terminated uint8_t implVer1; uint8_t implVer2; uint16_t version; uint32_t numberOfStreams; uint32_t streamDirectoryRva; uint32_t checkSum; uint32_t timeDateStamp; uint64_t flags; } MdmpProperties; typedef struct { const char* filepath; MdmpProperties props; int loaded; } MdmpHandler; void initMdmpHandler(MdmpHandler* handler, const char* filepath) { handler->filepath = filepath; handler->loaded = 0; memset(&handler->props, 0, sizeof(MdmpProperties)); } int readAndDecode(MdmpHandler* handler) { FILE* f = fopen(handler->filepath, "rb"); if (!f) return -1; uint8_t header[32]; if (fread(header, 1, 32, f) != 32) { fclose(f); return -2; } fclose(f); memcpy(handler->props.signature, header, 4); handler->props.signature[4] = '\0'; handler->props.implVer1 = header[4]; handler->props.implVer2 = header[5]; handler->props.version = *(uint16_t*)(header + 6); handler->props.numberOfStreams = *(uint32_t*)(header + 8); handler->props.streamDirectoryRva = *(uint32_t*)(header + 12); handler->props.checkSum = *(uint32_t*)(header + 16); handler->props.timeDateStamp = *(uint32_t*)(header + 20); handler->props.flags = *(uint64_t*)(header + 24); handler->loaded = 1; return 0; } void printProperties(MdmpHandler* handler) { if (!handler->loaded) { printf("No properties loaded.\n"); return; } printf("Signature: %s\n", handler->props.signature); printf("ImplementationVersion: 0x%02x 0x%02x\n", handler->props.implVer1, handler->props.implVer2); printf("Version: %u\n", handler->props.version); printf("NumberOfStreams: %u\n", handler->props.numberOfStreams); printf("StreamDirectoryRva: %u\n", handler->props.streamDirectoryRva); printf("CheckSum: %u\n", handler->props.checkSum); time_t ts = (time_t)handler->props.timeDateStamp; printf("TimeDateStamp: %u (Date: %s)\n", handler->props.timeDateStamp, ctime(&ts)); printf("Flags: %llu\n", handler->props.flags); } int write(MdmpHandler* handler, const char* newFilepath) { if (!handler->loaded) return -1; FILE* f_in = fopen(handler->filepath, "rb"); if (!f_in) return -2; fseek(f_in, 0, SEEK_END); long size = ftell(f_in); fseek(f_in, 0, SEEK_SET); uint8_t* data = malloc(size); if (fread(data, 1, size, f_in) != size) { free(data); fclose(f_in); return -3; } fclose(f_in); // Update header memcpy(data, handler->props.signature, 4); data[4] = handler->props.implVer1; data[5] = handler->props.implVer2; *(uint16_t*)(data + 6) = handler->props.version; *(uint32_t*)(data + 8) = handler->props.numberOfStreams; *(uint32_t*)(data + 12) = handler->props.streamDirectoryRva; *(uint32_t*)(data + 16) = handler->props.checkSum; *(uint32_t*)(data + 20) = handler->props.timeDateStamp; *(uint64_t*)(data + 24) = handler->props.flags; char* outputPath = newFilepath ? (char*)newFilepath : strcat(strdup(handler->filepath), ".modified"); FILE* f_out = fopen(outputPath, "wb"); if (!f_out) { free(data); if (!newFilepath) free(outputPath); return -4; } fwrite(data, 1, size, f_out); fclose(f_out); free(data); if (!newFilepath) free(outputPath); printf("Written to %s\n", outputPath ? outputPath : newFilepath); return 0; } // Example usage: // int main() { // MdmpHandler handler; // initMdmpHandler(&handler, "example.mdmp"); // readAndDecode(&handler); // printProperties(&handler); // handler.props.checkSum = 0; // Modify // write(&handler, NULL); // return 0; // } // ===== end task-392 .MDMP ===== // ===== task-393 .MDS [C] ===== #include #include #include #include typedef struct { char file_id[17]; uint8_t version[2]; uint16_t media_type; uint16_t num_sessions; uint32_t unknown; uint16_t bca_length; uint32_t bca_offset; uint32_t disc_structures_offset; uint32_t offset_first_session; uint32_t offset_read_errors; } Header; typedef struct { int32_t start_sector; int32_t end_sector; uint16_t session_num; uint8_t num_data_any; uint8_t num_data_a0; uint16_t first_track; uint16_t last_track; uint32_t offset_first_data; } SessionBlock; typedef struct { uint8_t track_mode; uint8_t num_subchannels; uint8_t adr_control; uint8_t track_no; uint8_t point; uint8_t minute; uint8_t second; uint8_t frame; uint32_t offset_index; uint16_t sector_size; uint8_t unknown; uint32_t track_start_plba; uint64_t track_start_offset; uint32_t num_filenames; uint32_t offset_filename; } DataBlock; typedef struct { uint32_t sectors_index0; uint32_t sectors_index1; } IndexBlock; typedef struct { uint32_t offset_string; char* filename; } FilenameBlock; typedef struct { Header header; SessionBlock* sessions; int num_sessions; DataBlock* data_blocks; int num_data_blocks; IndexBlock* index_blocks; int num_index_blocks; FilenameBlock* filename_blocks; int num_filename_blocks; char* read_errors; uint8_t* data; long data_size; } MDS; MDS* mds_open(const char* filepath) { FILE* f = fopen(filepath, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); MDS* mds = malloc(sizeof(MDS)); mds->data = data; mds->data_size = size; if (strncmp((char*)data, "MEDIA DESCRIPTOR", 16) != 0) { free(mds); free(data); return NULL; } // Parse Header memcpy(mds->header.file_id, data, 16); mds->header.file_id[16] = '\0'; mds->header.version[0] = data[16]; mds->header.version[1] = data[17]; memcpy(&mds->header.media_type, data + 18, 2); memcpy(&mds->header.num_sessions, data + 20, 2); memcpy(&mds->header.unknown, data + 22, 4); memcpy(&mds->header.bca_length, data + 26, 2); memcpy(&mds->header.bca_offset, data + 36, 4); memcpy(&mds->header.disc_structures_offset, data + 64, 4); memcpy(&mds->header.offset_first_session, data + 80, 4); memcpy(&mds->header.offset_read_errors, data + 84, 4); // Parse Session Blocks mds->num_sessions = mds->header.num_sessions; mds->sessions = malloc(mds->num_sessions * sizeof(SessionBlock)); uint32_t offset = mds->header.offset_first_session; for (int i = 0; i < mds->num_sessions; i++) { memcpy(&mds->sessions[i].start_sector, data + offset, 4); memcpy(&mds->sessions[i].end_sector, data + offset + 4, 4); memcpy(&mds->sessions[i].session_num, data + offset + 8, 2); mds->sessions[i].num_data_any = data[offset + 10]; mds->sessions[i].num_data_a0 = data[offset + 11]; memcpy(&mds->sessions[i].first_track, data + offset + 12, 2); memcpy(&mds->sessions[i].last_track, data + offset + 14, 2); memcpy(&mds->sessions[i].offset_first_data, data + offset + 20, 4); offset += 24; } // Parse Data Blocks uint32_t data_offset = mds->sessions[mds->num_sessions - 1].offset_first_data; mds->num_data_blocks = mds->sessions[mds->num_sessions - 1].num_data_any; mds->data_blocks = malloc(mds->num_data_blocks * sizeof(DataBlock)); for (int i = 0; i < mds->num_data_blocks; i++) { mds->data_blocks[i].track_mode = data[data_offset]; mds->data_blocks[i].num_subchannels = data[data_offset + 1]; mds->data_blocks[i].adr_control = data[data_offset + 2]; mds->data_blocks[i].track_no = data[data_offset + 3]; mds->data_blocks[i].point = data[data_offset + 4]; mds->data_blocks[i].minute = data[data_offset + 9]; mds->data_blocks[i].second = data[data_offset + 10]; mds->data_blocks[i].frame = data[data_offset + 11]; memcpy(&mds->data_blocks[i].offset_index, data + data_offset + 12, 4); memcpy(&mds->data_blocks[i].sector_size, data + data_offset + 16, 2); mds->data_blocks[i].unknown = data[data_offset + 18]; memcpy(&mds->data_blocks[i].track_start_plba, data + data_offset + 36, 4); memcpy(&mds->data_blocks[i].track_start_offset, data + data_offset + 40, 8); memcpy(&mds->data_blocks[i].num_filenames, data + data_offset + 48, 4); memcpy(&mds->data_blocks[i].offset_filename, data + data_offset + 52, 4); data_offset += 80; } // Parse Index Blocks (assume starting from first track after A0-A2) uint32_t index_offset = mds->data_blocks[3].offset_index; mds->num_index_blocks = mds->num_data_blocks - mds->sessions[mds->num_sessions - 1].num_data_a0; mds->index_blocks = malloc(mds->num_index_blocks * sizeof(IndexBlock)); for (int i = 0; i < mds->num_index_blocks; i++) { memcpy(&mds->index_blocks[i].sectors_index0, data + index_offset, 4); memcpy(&mds->index_blocks[i].sectors_index1, data + index_offset + 4, 4); index_offset += 8; } // Parse Filename Blocks (assume from first track) uint32_t filename_offset = mds->data_blocks[3].offset_filename; mds->num_filename_blocks = mds->data_blocks[3].num_filenames; mds->filename_blocks = malloc(mds->num_filename_blocks * sizeof(FilenameBlock)); for (int i = 0; i < mds->num_filename_blocks; i++) { memcpy(&mds->filename_blocks[i].offset_string, data + filename_offset, 4); uint32_t str_offset = mds->filename_blocks[i].offset_string; int len = 0; while (data[str_offset + len] != 0) len++; mds->filename_blocks[i].filename = malloc(len + 1); memcpy(mds->filename_blocks[i].filename, data + str_offset, len); mds->filename_blocks[i].filename[len] = '\0'; filename_offset += 16; } // Read Errors mds->read_errors = (mds->header.offset_read_errors == 0) ? "None" : "Present"; return mds; } void mds_print(MDS* mds) { printf("Header:\n"); printf("- File ID: %s\n", mds->header.file_id); printf("- Version: %02x,%02x\n", mds->header.version[0], mds->header.version[1]); printf("- Media Type: %u\n", mds->header.media_type); printf("- Number of sessions: %u\n", mds->header.num_sessions); printf("- Unknown: %u\n", mds->header.unknown); printf("- BCA Length: %u\n", mds->header.bca_length); printf("- BCA Offset: %u\n", mds->header.bca_offset); printf("- Disc Structures Offset: %u\n", mds->header.disc_structures_offset); printf("- Offset to First Session Block: %u\n", mds->header.offset_first_session); printf("- Offset to Read Errors: %u\n", mds->header.offset_read_errors); printf("\nSession Blocks:\n"); for (int i = 0; i < mds->num_sessions; i++) { printf(" Session %d:\n", i); printf(" - Start Sector: %d\n", mds->sessions[i].start_sector); printf(" - End Sector: %d\n", mds->sessions[i].end_sector); printf(" - Session Number: %u\n", mds->sessions[i].session_num); printf(" - Num Data Blocks (Any Point): %u\n", mds->sessions[i].num_data_any); printf(" - Num Data Blocks (Point >= A0h): %u\n", mds->sessions[i].num_data_a0); printf(" - First Track Number: %u\n", mds->sessions[i].first_track); printf(" - Last Track Number: %u\n", mds->sessions[i].last_track); printf(" - Offset to First Data Block: %u\n", mds->sessions[i].offset_first_data); } printf("\nData Blocks:\n"); for (int i = 0; i < mds->num_data_blocks; i++) { printf(" Data Block %d:\n", i); printf(" - Track Mode: %02x\n", mds->data_blocks[i].track_mode); printf(" - Number of Subchannels: %u\n", mds->data_blocks[i].num_subchannels); printf(" - ADR/Control: %02x\n", mds->data_blocks[i].adr_control); printf(" - TrackNo: %u\n", mds->data_blocks[i].track_no); printf(" - Point: %02x\n", mds->data_blocks[i].point); printf(" - Minute: %u\n", mds->data_blocks[i].minute); printf(" - Second: %u\n", mds->data_blocks[i].second); printf(" - Frame: %u\n", mds->data_blocks[i].frame); printf(" - Offset to Index Block: %u\n", mds->data_blocks[i].offset_index); printf(" - Sector Size: %u\n", mds->data_blocks[i].sector_size); printf(" - Unknown: %u\n", mds->data_blocks[i].unknown); printf(" - Track Start Sector (PLBA): %u\n", mds->data_blocks[i].track_start_plba); printf(" - Track Start Offset: %llu\n", mds->data_blocks[i].track_start_offset); printf(" - Number of Filenames: %u\n", mds->data_blocks[i].num_filenames); printf(" - Offset to Filename Block: %u\n", mds->data_blocks[i].offset_filename); } printf("\nIndex Blocks:\n"); for (int i = 0; i < mds->num_index_blocks; i++) { printf(" Index Block %d:\n", i); printf(" - Sectors Index 0: %u\n", mds->index_blocks[i].sectors_index0); printf(" - Sectors Index 1: %u\n", mds->index_blocks[i].sectors_index1); } printf("\nFilename Blocks:\n"); for (int i = 0; i < mds->num_filename_blocks; i++) { printf(" Filename Block %d:\n", i); printf(" - Offset to Filename String: %u\n", mds->filename_blocks[i].offset_string); printf(" - Filename: %s\n", mds->filename_blocks[i].filename); } printf("\nRead Errors: %s\n", mds->read_errors); } void mds_write(MDS* mds, const char* filepath) { FILE* f = fopen(filepath, "wb"); if (f) { fwrite(mds->data, 1, mds->data_size, f); fclose(f); printf("File written to %s\n", filepath); } } void mds_free(MDS* mds) { free(mds->sessions); free(mds->data_blocks); free(mds->index_blocks); for (int i = 0; i < mds->num_filename_blocks; i++) { free(mds->filename_blocks[i].filename); } free(mds->filename_blocks); free(mds->data); free(mds); } // Example usage int main() { MDS* mds = mds_open("example.mds"); if (mds) { mds_print(mds); mds_write(mds, "new.mds"); mds_free(mds); } return 0; } // ===== end task-393 .MDS ===== // ===== task-394 .MEX [C] ===== #include #include #include #define MAX_LINE 256 #define MAX_DATA 100000 // Arbitrary max for data entries typedef struct { char object[10]; char format[20]; char field[10]; char symmetry[10]; int rows; int cols; int entries; int (*data)[3]; // array of [row, col, value] int data_count; } MexFile; void mex_init(MexFile *mex) { strcpy(mex->object, "matrix"); strcpy(mex->format, "coordinate"); strcpy(mex->field, "integer"); strcpy(mex->symmetry, "general"); mex->rows = 0; mex->cols = 0; mex->entries = 0; mex->data = NULL; mex->data_count = 0; } void mex_read(MexFile *mex, const char *filename) { FILE *fp = fopen(filename, "r"); if (!fp) { perror("Failed to open file"); exit(1); } char line[MAX_LINE]; char header[MAX_LINE] = ""; char size_line[MAX_LINE] = ""; int data_capacity = 1000; mex->data = malloc(data_capacity * sizeof(int[3])); mex->data_count = 0; while (fgets(line, MAX_LINE, fp)) { line[strcspn(line, "\n")] = 0; // Trim newline if (strstr(line, "%%MatrixMarket")) { strcpy(header, line); } else if (line[0] == '%') { continue; } else if (strlen(size_line) == 0) { strcpy(size_line, line); } else { if (mex->data_count >= data_capacity) { data_capacity *= 2; mex->data = realloc(mex->data, data_capacity * sizeof(int[3])); } sscanf(line, "%d %d %d", &mex->data[mex->data_count][0], &mex->data[mex->data_count][1], &mex->data[mex->data_count][2]); mex->data_count++; } } fclose(fp); sscanf(header, "%%MatrixMarket %s %s %s %s", mex->object, mex->format, mex->field, mex->symmetry); sscanf(size_line, "%d %d %d", &mex->rows, &mex->cols, &mex->entries); } void mex_print_properties(const MexFile *mex) { printf("Object type: %s\n", mex->object); printf("Storage format: %s\n", mex->format); printf("Data field: %s\n", mex->field); printf("Symmetry type: %s\n", mex->symmetry); printf("Number of rows: %d\n", mex->rows); printf("Number of columns: %d\n", mex->cols); printf("Number of non-zero entries: %d\n", mex->entries); printf("Sparse data entries:\n"); int limit = mex->data_count > 10 ? 10 : mex->data_count; for (int i = 0; i < limit; i++) { printf("(%d, %d, %d)\n", mex->data[i][0], mex->data[i][1], mex->data[i][2]); } if (mex->data_count > 10) { printf("... (truncated)\n"); } } void mex_write(const MexFile *mex, const char *filename) { FILE *fp = fopen(filename, "w"); if (!fp) { perror("Failed to open file"); exit(1); } fprintf(fp, "%%MatrixMarket %s %s %s %s\n", mex->object, mex->format, mex->field, mex->symmetry); fprintf(fp, "%% Generated MEX file\n"); fprintf(fp, "%d %d %d\n", mex->rows, mex->cols, mex->entries); for (int i = 0; i < mex->data_count; i++) { fprintf(fp, "%d %d %d\n", mex->data[i][0], mex->data[i][1], mex->data[i][2]); } fclose(fp); } void mex_free(MexFile *mex) { free(mex->data); } // Example usage: // int main() { // MexFile mex; // mex_init(&mex); // mex_read(&mex, "example.mex"); // mex_print_properties(&mex); // mex_write(&mex, "output.mex"); // mex_free(&mex); // return 0; // } // ===== end task-394 .MEX ===== // ===== task-395 .MGF [C++] ===== #include #include #include #include #include #include #include std::string trim(const std::string& str) { size_t first = str.find_first_not_of(" \t"); if (first == std::string::npos) return ""; size_t last = str.find_last_not_of(" \t"); return str.substr(first, (last - first + 1)); } class MGFHandler { private: std::map globalProps; std::vector> spectra; bool isPeakLine(const std::string& line) { std::string temp = trim(line); size_t spacePos = temp.find(' '); if (spacePos != std::string::npos) { std::string mz = temp.substr(0, spacePos); std::string intensity = trim(temp.substr(spacePos + 1)); bool isNum1 = !mz.empty() && (std::isdigit(mz[0]) || mz[0] == '.' || mz[0] == '-'); bool isNum2 = !intensity.empty() && (std::isdigit(intensity[0]) || intensity[0] == '.' || intensity[0] == '-'); return isNum1 && isNum2; } return false; } public: void read(const std::string& filename) { std::ifstream ifs(filename); if (!ifs) return; std::string line; std::map currentSpectrum; while (std::getline(ifs, line)) { line = trim(line); if (line == "BEGIN IONS") { currentSpectrum.clear(); } else if (line == "END IONS") { spectra.push_back(currentSpectrum); } else if (line.find('=') != std::string::npos && line[0] != '#' && line[0] != ';' && line[0] != '!' && line[0] != '/' && !isPeakLine(line)) { size_t pos = line.find('='); std::string key = trim(line.substr(0, pos)); std::string value = trim(line.substr(pos + 1)); if (currentSpectrum.empty()) { globalProps[key] = value; } else { currentSpectrum[key] = value; } } } } void printProperties() { std::cout << "Global properties:" << std::endl; for (const auto& p : globalProps) { std::cout << p.first << ": " << p.second << std::endl; } for (size_t i = 0; i < spectra.size(); ++i) { std::cout << "\nSpectrum " << (i + 1) << " properties:" << std::endl; for (const auto& p : spectra[i]) { std::cout << p.first << ": " << p.second << std::endl; } } } void write(const std::string& filename) { std::ofstream ofs(filename); for (const auto& p : globalProps) { ofs << p.first << "=" << p.second << std::endl; } for (const auto& spec : spectra) { ofs << "BEGIN IONS" << std::endl; for (const auto& p : spec) { ofs << p.first << "=" << p.second << std::endl; } ofs << "END IONS" << std::endl; } } }; // Example usage: // int main() { // MGFHandler handler; // handler.read("example.mgf"); // handler.printProperties(); // handler.write("new.mgf"); // return 0; // } // ===== end task-395 .MGF ===== // ===== task-396 .MHT [C++] ===== #include #include #include #include #include #include #include class MHTHandler { private: std::map headers; std::string boundary; std::vector> parts; void parse(const std::string& text) { std::istringstream iss(text); std::string line; std::string currentHeader; bool inHeaders = true; while (std::getline(iss, line)) { if (inHeaders) { if (line.empty()) { inHeaders = false; continue; } if (line[0] == ' ' || line[0] == '\t') { headers[currentHeader] += " " + line.substr(1); } else { size_t colon = line.find(':'); if (colon != std::string::npos) { currentHeader = line.substr(0, colon); headers[currentHeader] = line.substr(colon + 1); } } } else { if (boundary.empty() && headers.find("Content-Type") != headers.end()) { std::regex boundaryRegex(R"(boundary="([^"]+)")"); std::smatch match; if (std::regex_search(headers["Content-Type"], match, boundaryRegex)) { boundary = match[1]; } } if (!boundary.empty() && line.find("--" + boundary) != std::string::npos) { if (!parts.empty() && !parts.back().empty()) { // Already pushed } parts.push_back({}); inHeaders = true; currentHeader = ""; } else if (inHeaders && !parts.empty()) { if (line.empty()) { inHeaders = false; } else if (line[0] == ' ' || line[0] == '\t') { parts.back()[currentHeader] += " " + line.substr(1); } else { size_t colon = line.find(':'); if (colon != std::string::npos) { currentHeader = line.substr(0, colon); parts.back()[currentHeader] = line.substr(colon + 1); } } } } } } public: MHTHandler(const std::string& filepath = "") { if (!filepath.empty()) read(filepath); } void read(const std::string& filepath) { std::ifstream file(filepath); if (!file) { std::cerr << "Failed to open file." << std::endl; return; } std::stringstream buffer; buffer << file.rdbuf(); parse(buffer.str()); } void printProperties() { if (headers.empty()) { std::cout << "No file loaded." << std::endl; return; } std::cout << "From: " << headers["From"] << std::endl; std::cout << "Date: " << headers["Date"] << std::endl; std::cout << "Subject: " << headers["Subject"] << std::endl; std::cout << "MIME-Version: " << headers["MIME-Version"] << std::endl; std::cout << "Content-Type (top-level): " << headers["Content-Type"] << std::endl; std::cout << "Boundary: " << (boundary.empty() ? "N/A" : boundary) << std::endl; std::cout << "Content-Base: " << headers["Content-Base"] << std::endl; std::cout << "Snapshot-Content-Location: " << headers["Snapshot-Content-Location"] << std::endl; std::cout << "Number of parts: " << parts.size() << std::endl; for (size_t i = 0; i < parts.size(); ++i) { auto& part = parts[i]; std::cout << "\nPart " << (i + 1) << ":" << std::endl; std::cout << " Content-Type: " << part["Content-Type"] << std::endl; std::string charset = "N/A"; std::regex charsetRegex(R"(charset=([^;]+))"); std::smatch match; if (std::regex_search(part["Content-Type"], match, charsetRegex)) { charset = match[1]; } std::cout << " Charset: " << charset << std::endl; std::cout << " Content-Transfer-Encoding: " << part["Content-Transfer-Encoding"] << std::endl; std::cout << " Content-Location: " << part["Content-Location"] << std::endl; std::cout << " Content-ID: " << part["Content-ID"] << std::endl; } } void write(const std::string& filepath, const std::string& rootHtml = "Test") { std::string boundaryStr = "----boundary_test"; std::ofstream file(filepath); if (!file) { std::cerr << "Failed to write file." << std::endl; return; } file << "From: \n"; file << "Date: Mon, 30 Sep 2025 00:00:00 -0000\n"; file << "Subject: Test MHT\n"; file << "MIME-Version: 1.0\n"; file << "Content-Type: multipart/related; type=\"text/html\"; boundary=\"" << boundaryStr << "\"\n"; file << "Content-Base: http://example.com\n"; file << "Snapshot-Content-Location: http://example.com/test\n\n"; file << "This is a multi-part message in MIME format.\n\n"; file << "--" << boundaryStr << "\n"; file << "Content-Type: text/html; charset=\"UTF-8\"\n"; file << "Content-Transfer-Encoding: quoted-printable\n"; file << "Content-Location: /\n\n"; file << rootHtml << "\n"; file << "--" << boundaryStr << "--\n"; } }; int main(int argc, char* argv[]) { if (argc > 1) { MHTHandler handler(argv[1]); handler.printProperties(); } else { MHTHandler handler; handler.write("test.mht"); std::cout << "Wrote test.mht" << std::endl; } return 0; } // ===== end task-396 .MHT ===== // ===== task-397 .MIDI [C++] ===== #include #include #include #include #include #include class MidiParser { private: std::vector data; size_t offset = 0; std::map properties; // Simplified to string for print uint32_t readUint32() { uint32_t val = (data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]; offset += 4; return val; } uint16_t readUint16() { uint16_t val = (data[offset] << 8) | data[offset+1]; offset += 2; return val; } uint32_t readVarLen() { uint32_t val = 0; while (true) { uint8_t byte = data[offset++]; val = (val << 7) | (byte & 0x7F); if (!(byte & 0x80)) break; } return val; } std::string readString(size_t len) { std::string str(data.begin() + offset, data.begin() + offset + len); offset += len; return str; } std::vector readBytes(size_t len) { std::vector bytes(data.begin() + offset, data.begin() + offset + len); offset += len; return bytes; } void extractProperties() { if (readString(4) != "MThd") return; readUint32(); // header len 6 properties["formatType"] = std::to_string(readUint16()); properties["numTracks"] = std::to_string(readUint16()); properties["division"] = std::to_string(readUint16()); // Similar parsing loop as JS, but add to properties map // For tempos, etc., append as strings like "tempos: 120, 140" // Implement full loop here (analogous to JS) } public: MidiParser(const std::string& filepath) { std::ifstream file(filepath, std::ios::binary); if (file) { data = std::vector(std::istreambuf_iterator(file), {}); extractProperties(); } } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& outputPath, bool modifyExample = false) { std::ofstream out(outputPath, std::ios::binary); if (out) { out.write(reinterpret_cast(data.data()), data.size()); if (modifyExample) { // Example: Append a simple meta (complex in practice) } } } }; // Example usage: // int main() { // MidiParser parser("example.mid"); // parser.printProperties(); // parser.write("modified.mid", true); // return 0; // } // ===== end task-397 .MIDI ===== // ===== task-399 .MKV [C++] ===== #include #include #include #include #include #include #include struct ElementInfo { std::string name; std::string type; }; struct Node { std::vector id; std::string type; std::vector data; }; class MKVParser { private: std::string filepath; std::map, ElementInfo> elementMap; std::vector data; std::vector tree; std::pair readVint(const std::vector& buf, size_t pos) { unsigned char leadByte = buf[pos]; int length = 1; unsigned char mask = 0x80; while (length <= 8 && !(leadByte & mask)) { length++; mask >>= 1; } long long value = leadByte & (mask - 1); pos++; for (int i = 1; i < length; i++) { value = (value << 8) | buf[pos++]; } return {value, pos}; } void parseEBML(const std::vector& buf, size_t start, size_t end, int level) { size_t pos = start; while (pos < end) { auto idRes = readVint(buf, pos); pos = idRes.second; auto sizeRes = readVint(buf, pos); pos = sizeRes.second; long long idVal = idRes.first; std::vector idBytes; long long temp = idVal; while (temp > 0) { idBytes.insert(idBytes.begin(), temp & 0xFF); temp >>= 8; } if (idBytes.empty()) idBytes = {0}; auto it = elementMap.find(idBytes); ElementInfo elem = (it != elementMap.end()) ? it->second : ElementInfo{"Unknown (0x" + std::to_string(idVal) + ")", "unknown"}; for (int i = 0; i < level; i++) std::cout << " "; std::cout << elem.name << " (ID: 0x" << std::hex << idVal << std::dec << ", Size: " << sizeRes.first << "): "; size_t dataStart = pos; size_t dataEnd = pos + sizeRes.first; Node node; node.id = idBytes; node.type = elem.type; node.data = std::vector(buf.begin() + dataStart, buf.begin() + dataEnd); tree.push_back(node); if (elem.type == "master") { std::cout << std::endl; parseEBML(buf, dataStart, dataEnd, level + 1); } else if (elem.type == "uinteger") { long long val = 0; for (auto b : node.data) val = (val << 8) | b; std::cout << val << std::endl; } else if (elem.type == "float") { if (sizeRes.first == 4) { float val; memcpy(&val, node.data.data(), 4); std::cout << val << std::endl; } else if (sizeRes.first == 8) { double val; memcpy(&val, node.data.data(), 8); std::cout << val << std::endl; } else { std::cout << "Invalid float size" << std::endl; } } else if (elem.type == "utf-8" || elem.type == "string") { std::string str(node.data.begin(), node.data.end()); std::cout << str << std::endl; } else if (elem.type == "binary") { std::cout << "[Binary data, length " << sizeRes.first << "]" << std::endl; } else if (elem.type == "date") { long long ns = 0; for (auto b : node.data) ns = (ns << 8) | b; time_t seconds = 978307200 + ns / 1000000000; char timeBuf[64]; strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%dT%H:%M:%SZ", gmtime(&seconds)); std::cout << timeBuf << std::endl; } else { std::cout << "[Unknown type data]" << std::endl; } pos = dataEnd; } } public: MKVParser(const std::string& fp) : filepath(fp) { elementMap[{{0x42, 0xF2}}] = {"EBMLMaxIDLength", "uinteger"}; elementMap[{{0x42, 0xF3}}] = {"EBMLMaxSizeLength", "uinteger"}; elementMap[{{0x18, 0x53, 0x80, 0x67}}] = {"Segment", "master"}; elementMap[{{0x11, 0x4D, 0x9B, 0x74}}] = {"SeekHead", "master"}; elementMap[{{0x4D, 0xBB}}] = {"Seek", "master"}; elementMap[{{0x53, 0xAB}}] = {"SeekID", "binary"}; elementMap[{{0x53, 0xAC}}] = {"SeekPosition", "uinteger"}; elementMap[{{0x15, 0x49, 0xA9, 0x66}}] = {"Info", "master"}; elementMap[{{0x73, 0xA4}}] = {"SegmentUUID", "binary"}; elementMap[{{0x73, 0x84}}] = {"SegmentFilename", "utf-8"}; elementMap[{{0x3C, 0xB9, 0x23}}] = {"PrevUUID", "binary"}; elementMap[{{0x3C, 0x83, 0xAB}}] = {"PrevFilename", "utf-8"}; elementMap[{{0x3E, 0xB9, 0x23}}] = {"NextUUID", "binary"}; elementMap[{{0x3E, 0x83, 0xBB}}] = {"NextFilename", "utf-8"}; elementMap[{{0x44, 0x44}}] = {"SegmentFamily", "binary"}; elementMap[{{0x69, 0x24}}] = {"ChapterTranslate", "master"}; elementMap[{{0x69, 0xA5}}] = {"ChapterTranslateID", "binary"}; elementMap[{{0x69, 0xFC}}] = {"ChapterTranslateCodec", "uinteger"}; elementMap[{{0x69, 0xBF}}] = {"ChapterTranslateEditionUID", "uinteger"}; elementMap[{{0x2A, 0xD7, 0xB1}}] = {"TimestampScale", "uinteger"}; elementMap[{{0x44, 0x89}}] = {"Duration", "float"}; elementMap[{{0x44, 0x61}}] = {"DateUTC", "date"}; elementMap[{{0x7B, 0xA9}}] = {"Title", "utf-8"}; elementMap[{{0x4D, 0x80}}] = {"MuxingApp", "utf-8"}; elementMap[{{0x57, 0x41}}] = {"WritingApp", "utf-8"}; // Add more } void readAndPrint() { std::ifstream file(filepath, std::ios::binary); data = std::vector((std::istreambuf_iterator(file)), std::istreambuf_iterator()); parseEBML(data, 0, data.size(), 0); } void write(const std::string& outputPath) { std::ofstream out(outputPath, std::ios::binary); for (const auto& node : tree) { // Write ID VINT (simplified) long long idInt = 0; for (auto b : node.id) idInt = (idInt << 8) | b; int idLen = node.id.size(); unsigned char mask = 1 << (8 - idLen); long long idVint = (1LL << (8 * idLen - idLen)) | idInt; for (int i = idLen - 1; i >= 0; i--) { out.put(static_cast(idVint >> (i * 8))); } // Write size VINT long long size = node.data.size(); int sizeLen = (63 - __builtin_clzll(size | 1)) / 7 + 1; long long sizeVint = (1LL << (8 * sizeLen - sizeLen)) | size; for (int i = sizeLen - 1; i >= 0; i--) { out.put(static_cast(sizeVint >> (i * 8))); } // Write data out.write(reinterpret_cast(node.data.data()), node.data.size()); } } }; // Usage: // MKVParser parser("example.mkv"); // parser.readAndPrint(); // parser.write("output.mkv"); // ===== end task-399 .MKV ===== // ===== task-400 .MLX [C++] ===== #include #include #include #include // Requires libzip or similar; install via package manager class MLXHandler { private: std::string filename; zip_t* zipf; public: MLXHandler(const std::string& fn) : filename(fn), zipf(nullptr) {} ~MLXHandler() { close(); } bool open() { int err = 0; zipf = zip_open(filename.c_str(), ZIP_RDONLY, &err); return zipf != nullptr; } void readAndPrintProperties() { if (!zipf && !open()) { std::cerr << "Failed to open file." << std::endl; return; } zip_int64_t num_entries = zip_get_num_entries(zipf, 0); for (zip_int64_t i = 0; i < num_entries; ++i) { zip_stat_t sb; if (zip_stat_index(zipf, i, 0, &sb) == 0) { std::cout << "File name: " << sb.name << std::endl; std::cout << "Compression method: " << sb.comp_method << std::endl; std::cout << "Last modification time: " << sb.mtime << std::endl; std::cout << "CRC-32: " << sb.crc << std::endl; std::cout << "Compressed size: " << sb.comp_size << std::endl; std::cout << "Uncompressed size: " << sb.size << std::endl; std::cout << "External attributes: " << sb.external_attr << std::endl; std::cout << "\n"; } } } void writeNewMlx(const std::string& newFilename, const std::vector& filesToAdd) { zip_t* newZip = zip_open(newFilename.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); if (!newZip) { std::cerr << "Failed to create new file." << std::endl; return; } for (const auto& filePath : filesToAdd) { zip_source_t* src = zip_source_file(newZip, filePath.c_str(), 0, 0); if (src) { zip_file_add(newZip, filePath.c_str(), src, ZIP_FL_ENC_UTF_8); } } zip_close(newZip); std::cout << "New .MLX file written: " << newFilename << std::endl; } void close() { if (zipf) { zip_close(zipf); zipf = nullptr; } } }; // Example usage: // int main() { // MLXHandler handler("example.mlx"); // handler.readAndPrintProperties(); // handler.writeNewMlx("new.mlx", {"file1.txt", "file2.xml"}); // return 0; // } // ===== end task-400 .MLX ===== // ===== task-401 .MM [C] ===== #include #include #include #include typedef struct { xmlDocPtr doc; } MMFile; MMFile* mmfile_open(const char* filename) { MMFile* mm = malloc(sizeof(MMFile)); mm->doc = xmlReadFile(filename, NULL, 0); if (mm->doc == NULL) { fprintf(stderr, "Failed to parse %s\n", filename); free(mm); return NULL; } return mm; } void mmfile_print_properties(MMFile* mm) { if (mm == NULL || mm->doc == NULL) return; printf("Dumping .MM File Properties:\n\n"); xmlNode* root = xmlDocGetRootElement(mm->doc); if (root && xmlStrcmp(root->name, (const xmlChar*)"map") == 0) { xmlChar* version = xmlGetProp(root, (const xmlChar*)"version"); printf("Map version: %s\n\n", version ? (char*)version : "N/A"); xmlFree(version); } void traverse_node(xmlNode* node, int depth) { if (node == NULL) return; char indent[256] = {0}; memset(indent, ' ', depth * 2); indent[depth * 2] = '\0'; printf("%sNode:\n", indent); xmlChar* id = xmlGetProp(node, (const xmlChar*)"ID"); printf("%s id: %s\n", indent, id ? (char*)id : "N/A"); xmlFree(id); xmlChar* text = xmlGetProp(node, (const xmlChar*)"TEXT"); printf("%s text: %s\n", indent, text ? (char*)text : "N/A"); xmlFree(text); xmlChar* link = xmlGetProp(node, (const xmlChar*)"LINK"); printf("%s link: %s\n", indent, link ? (char*)link : "N/A"); xmlFree(link); xmlChar* folded = xmlGetProp(node, (const xmlChar*)"FOLDED"); printf("%s folded: %s\n", indent, folded ? (char*)folded : "N/A"); xmlFree(folded); xmlChar* color = xmlGetProp(node, (const xmlChar*)"COLOR"); printf("%s color: %s\n", indent, color ? (char*)color : "N/A"); xmlFree(color); xmlChar* position = xmlGetProp(node, (const xmlChar*)"POSITION"); printf("%s position: %s\n", indent, position ? (char*)position : "N/A"); xmlFree(position); xmlNode* child = node->children; while (child) { if (xmlStrcmp(child->name, (const xmlChar*)"edge") == 0) { xmlChar* style = xmlGetProp(child, (const xmlChar*)"STYLE"); printf("%s Edge style: %s\n", indent, style ? (char*)style : "N/A"); xmlFree(style); xmlChar* ecolor = xmlGetProp(child, (const xmlChar*)"COLOR"); printf("%s Edge color: %s\n", indent, ecolor ? (char*)ecolor : "N/A"); xmlFree(ecolor); xmlChar* width = xmlGetProp(child, (const xmlChar*)"WIDTH"); printf("%s Edge width: %s\n", indent, width ? (char*)width : "N/A"); xmlFree(width); } else if (xmlStrcmp(child->name, (const xmlChar*)"font") == 0) { xmlChar* name = xmlGetProp(child, (const xmlChar*)"NAME"); printf("%s Font name: %s\n", indent, name ? (char*)name : "N/A"); xmlFree(name); xmlChar* size = xmlGetProp(child, (const xmlChar*)"SIZE"); printf("%s Font size: %s\n", indent, size ? (char*)size : "N/A"); xmlFree(size); xmlChar* bold = xmlGetProp(child, (const xmlChar*)"BOLD"); printf("%s Font bold: %s\n", indent, bold ? (char*)bold : "N/A"); xmlFree(bold); xmlChar* italic = xmlGetProp(child, (const xmlChar*)"ITALIC"); printf("%s Font italic: %s\n", indent, italic ? (char*)italic : "N/A"); xmlFree(italic); } else if (xmlStrcmp(child->name, (const xmlChar*)"icon") == 0) { xmlChar* builtin = xmlGetProp(child, (const xmlChar*)"BUILTIN"); printf("%s Icon builtin: %s\n", indent, builtin ? (char*)builtin : "N/A"); xmlFree(builtin); } else if (xmlStrcmp(child->name, (const xmlChar*)"cloud") == 0) { xmlChar* ccolor = xmlGetProp(child, (const xmlChar*)"COLOR"); printf("%s Cloud color: %s\n", indent, ccolor ? (char*)ccolor : "N/A"); xmlFree(ccolor); } else if (xmlStrcmp(child->name, (const xmlChar*)"arrowlink") == 0) { xmlChar* acolor = xmlGetProp(child, (const xmlChar*)"COLOR"); printf("%s Arrowlink color: %s\n", indent, acolor ? (char*)acolor : "N/A"); xmlFree(acolor); xmlChar* dest = xmlGetProp(child, (const xmlChar*)"DESTINATION"); printf("%s Arrowlink destination: %s\n", indent, dest ? (char*)dest : "N/A"); xmlFree(dest); xmlChar* startarrow = xmlGetProp(child, (const xmlChar*)"STARTARROW"); printf("%s Arrowlink startarrow: %s\n", indent, startarrow ? (char*)startarrow : "N/A"); xmlFree(startarrow); xmlChar* endarrow = xmlGetProp(child, (const xmlChar*)"ENDARROW"); printf("%s Arrowlink endarrow: %s\n", indent, endarrow ? (char*)endarrow : "N/A"); xmlFree(endarrow); xmlChar* startincl = xmlGetProp(child, (const xmlChar*)"STARTINCLINATION"); printf("%s Arrowlink startinclination: %s\n", indent, startincl ? (char*)startincl : "N/A"); xmlFree(startincl); xmlChar* endincl = xmlGetProp(child, (const xmlChar*)"ENDINCLINATION"); printf("%s Arrowlink endinclination: %s\n", indent, endincl ? (char*)endincl : "N/A"); xmlFree(endincl); } else if (xmlStrcmp(child->name, (const xmlChar*)"node") == 0) { traverse_node(child, depth + 1); } child = child->next; } } xmlNode* root_node = root->children; while (root_node) { if (xmlStrcmp(root_node->name, (const xmlChar*)"node") == 0) { traverse_node(root_node, 0); break; } root_node = root_node->next; } } void mmfile_write(MMFile* mm, const char* filename) { if (mm == NULL || mm->doc == NULL) return; xmlSaveFormatFileEnc(filename, mm->doc, "UTF-8", 0); // No declaration } void mmfile_close(MMFile* mm) { if (mm) { xmlFreeDoc(mm->doc); free(mm); } } // Example usage: // int main() { // MMFile* mm = mmfile_open("example.mm"); // if (mm) { // mmfile_print_properties(mm); // mmfile_write(mm, "output.mm"); // mmfile_close(mm); // } // return 0; // } // ===== end task-401 .MM ===== // ===== task-402 .MML [C++] ===== #include #include #include #include // Requires nlohmann/json (single-header JSON library); assumes JSON format for simplicity (YAML parsing requires additional lib like yaml-cpp) using json = nlohmann::json; class MMLHandler { private: std::string filepath; json data; public: MMLHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Failed to open file." << std::endl; return; } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); try { data = json::parse(content); // Assumes JSON; for YAML, use yaml-cpp library } catch (json::parse_error& e) { std::cerr << "Invalid .MML file: " << e.what() << std::endl; } } void printProperties() { if (data.empty()) { std::cout << "No data loaded. Call read() first." << std::endl; return; } dump(data, ""); } private: void dump(const json& node, const std::string& prefix) { if (node.is_object()) { for (auto& el : node.items()) { std::cout << prefix << el.key() << ": " << (el.value().is_structured() ? "" : el.value().dump()) << std::endl; if (el.value().is_structured()) { dump(el.value(), prefix + " "); } } } else if (node.is_array()) { for (size_t i = 0; i < node.size(); ++i) { std::cout << prefix << "[" << i << "]: " << std::endl; dump(node[i], prefix + " "); } } } public: void write(const std::string& newFilepath = "") { if (data.empty()) { std::cout << "No data to write. Call read() first." << std::endl; return; } std::ofstream out(newFilepath.empty() ? filepath : newFilepath); out << data.dump(2); // Pretty-print with indent 2 } }; // Example usage: // int main() { // MMLHandler handler("example.mml"); // handler.read(); // handler.printProperties(); // handler.write("output.mml"); // return 0; // } // ===== end task-402 .MML ===== // ===== task-403 .MNT [C] ===== #include #include #include #include #include // For big-endian conversions, assume available or use custom typedef struct { uint32_t type; uint32_t length; uint8_t *data; } MemoBlock; typedef struct { char *filename; uint32_t next_free_block; uint16_t unused; uint16_t block_size; uint8_t reserved[504]; MemoBlock *memo_blocks; size_t num_memo_blocks; } MNTFile; MNTFile *mnt_create(const char *filename) { MNTFile *mnt = malloc(sizeof(MNTFile)); mnt->filename = strdup(filename); mnt->next_free_block = 0; mnt->unused = 0; mnt->block_size = 0; memset(mnt->reserved, 0, 504); mnt->memo_blocks = NULL; mnt->num_memo_blocks = 0; return mnt; } void mnt_destroy(MNTFile *mnt) { for (size_t i = 0; i < mnt->num_memo_blocks; i++) { free(mnt->memo_blocks[i].data); } free(mnt->memo_blocks); free(mnt->filename); free(mnt); } int mnt_read(MNTFile *mnt) { FILE *f = fopen(mnt->filename, "rb"); if (!f) return 1; fseek(f, 0, SEEK_END); long file_size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(file_size); fread(data, 1, file_size, f); fclose(f); if (file_size < 512) { free(data); return 1; } mnt->next_free_block = be32toh(*(uint32_t*)(data + 0)); mnt->unused = be16toh(*(uint16_t*)(data + 4)); mnt->block_size = be16toh(*(uint16_t*)(data + 6)); memcpy(mnt->reserved, data + 8, 504); long offset = 512; size_t block_number = 1; while (offset + mnt->block_size <= file_size) { uint32_t type = be32toh(*(uint32_t*)(data + offset)); uint32_t length = be32toh(*(uint32_t*)(data + offset + 4)); if (length > 0 && (type == 0 || type == 1)) { uint8_t *memo_data = malloc(length); memcpy(memo_data, data + offset + 8, length); mnt->memo_blocks = realloc(mnt->memo_blocks, sizeof(MemoBlock) * (mnt->num_memo_blocks + 1)); mnt->memo_blocks[mnt->num_memo_blocks].type = type; mnt->memo_blocks[mnt->num_memo_blocks].length = length; mnt->memo_blocks[mnt->num_memo_blocks].data = memo_data; mnt->num_memo_blocks++; } offset += mnt->block_size; block_number++; } free(data); return 0; } void mnt_print_properties(const MNTFile *mnt) { printf("Next Free Block Number: %u\n", mnt->next_free_block); printf("Unused: %hu\n", mnt->unused); printf("Block Size: %hu\n", mnt->block_size); printf("Reserved Area (first 100 bytes hex): "); for (int i = 0; i < 100 && i < 504; i++) { printf("%02x ", mnt->reserved[i]); } printf("...\n"); for (size_t i = 0; i < mnt->num_memo_blocks; i++) { MemoBlock block = mnt->memo_blocks[i]; printf("Memo Block %zu:\n", i + 1); printf(" Type: %u\n", block.type); printf(" Length: %u\n", block.length); printf(" Data (first 100 bytes as string): "); for (int j = 0; j < 100 && j < block.length; j++) { putchar(block.data[j]); } printf("...\n"); } } int mnt_write(const MNTFile *mnt, const char *new_filename) { if (!new_filename) new_filename = mnt->filename; FILE *f = fopen(new_filename, "wb"); if (!f) return 1; uint8_t header[512] = {0}; *(uint32_t*)(header + 0) = htobe32(mnt->next_free_block); *(uint16_t*)(header + 4) = htobe16(mnt->unused); *(uint16_t*)(header + 6) = htobe16(mnt->block_size); memcpy(header + 8, mnt->reserved, 504); fwrite(header, 1, 512, f); for (size_t i = 0; i < mnt->num_memo_blocks; i++) { MemoBlock block = mnt->memo_blocks[i]; uint8_t *block_buf = calloc(1, mnt->block_size); *(uint32_t*)(block_buf + 0) = htobe32(block.type); *(uint32_t*)(block_buf + 4) = htobe32(block.length); memcpy(block_buf + 8, block.data, block.length); fwrite(block_buf, 1, mnt->block_size, f); free(block_buf); } fclose(f); return 0; } // Example usage: // MNTFile *mnt = mnt_create("example.mnt"); // mnt_read(mnt); // mnt_print_properties(mnt); // mnt_write(mnt, "modified.mnt"); // mnt_destroy(mnt); // ===== end task-403 .MNT ===== // ===== task-404 .MO [C] ===== #include #include #include #include #include // For byte order typedef struct { uint32_t magic; uint32_t revision; uint32_t num_strings; uint32_t orig_offset; uint32_t trans_offset; uint32_t hash_size; uint32_t hash_offset; struct { uint32_t length; uint32_t offset; } *orig_table; struct { uint32_t length; uint32_t offset; } *trans_table; uint32_t *hash_table; char **orig_strings; char **trans_strings; int is_little_endian; char *data; // Raw data buffer size_t data_size; } MOFile; MOFile* mo_open(const char *filepath) { FILE *f = fopen(filepath, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); char *data = malloc(size); fread(data, 1, size, f); fclose(f); MOFile *mo = calloc(1, sizeof(MOFile)); mo->data = data; mo->data_size = size; mo->is_little_endian = 1; uint32_t magic_le = *(uint32_t*)(data + 0); uint32_t magic_be = be32toh(magic_le); if (magic_be == 0x950412de) mo->is_little_endian = 0; else if (magic_le != 0x950412de) { free(mo); free(data); return NULL; // Invalid } mo->magic = magic_le; #define GET_UINT32(offset) (mo->is_little_endian ? le32toh(*(uint32_t*)(data + offset)) : be32toh(*(uint32_t*)(data + offset))) mo->revision = GET_UINT32(4); mo->num_strings = GET_UINT32(8); mo->orig_offset = GET_UINT32(12); mo->trans_offset = GET_UINT32(16); mo->hash_size = GET_UINT32(20); mo->hash_offset = GET_UINT32(24); mo->orig_table = malloc(mo->num_strings * sizeof(*mo->orig_table)); mo->trans_table = malloc(mo->num_strings * sizeof(*mo->trans_table)); mo->orig_strings = malloc(mo->num_strings * sizeof(char*)); mo->trans_strings = malloc(mo->num_strings * sizeof(char*)); for (uint32_t i = 0; i < mo->num_strings; i++) { uint32_t base = mo->orig_offset + i * 8; mo->orig_table[i].length = GET_UINT32(base); mo->orig_table[i].offset = GET_UINT32(base + 4); mo->orig_strings[i] = strndup(data + mo->orig_table[i].offset, mo->orig_table[i].length); base = mo->trans_offset + i * 8; mo->trans_table[i].length = GET_UINT32(base); mo->trans_table[i].offset = GET_UINT32(base + 4); mo->trans_strings[i] = strndup(data + mo->trans_table[i].offset, mo->trans_table[i].length); } if (mo->hash_size > 0) { mo->hash_table = malloc(mo->hash_size * sizeof(uint32_t)); for (uint32_t i = 0; i < mo->hash_size; i++) { mo->hash_table[i] = GET_UINT32(mo->hash_offset + i * 4); } } return mo; } void mo_print_properties(MOFile *mo) { printf("Magic Number: 0x%08x\n", mo->magic); printf("Revision: %u.%u\n", mo->revision >> 16, mo->revision & 0xffff); printf("Number of Strings: %u\n", mo->num_strings); printf("Original Table Offset: %u\n", mo->orig_offset); printf("Translation Table Offset: %u\n", mo->trans_offset); printf("Hash Table Size: %u\n", mo->hash_size); printf("Hash Table Offset: %u\n", mo->hash_offset); printf("\nOriginal Table:\n"); for (uint32_t i = 0; i < mo->num_strings; i++) { printf(" [%u] Length: %u, Offset: %u\n", i, mo->orig_table[i].length, mo->orig_table[i].offset); } printf("\nTranslation Table:\n"); for (uint32_t i = 0; i < mo->num_strings; i++) { printf(" [%u] Length: %u, Offset: %u\n", i, mo->trans_table[i].length, mo->trans_table[i].offset); } if (mo->hash_table) { printf("\nHash Table:\n"); for (uint32_t i = 0; i < mo->hash_size; i++) { printf(" [%u] Index: %u\n", i, mo->hash_table[i]); } } printf("\nStrings:\n"); for (uint32_t i = 0; i < mo->num_strings; i++) { printf(" [%u] Original: %s\n Translation: %s\n", i, mo->orig_strings[i], mo->trans_strings[i]); } } void mo_write(MOFile *mo, const char *filepath) { FILE *f = fopen(filepath, "wb"); if (!f) return; // Reconstruct header uint32_t header[7] = {mo->magic, mo->revision, mo->num_strings, mo->orig_offset, mo->trans_offset, mo->hash_size, mo->hash_offset}; for (int i = 0; i < 7; i++) { uint32_t val = mo->is_little_endian ? htole32(header[i]) : htobe32(header[i]); fwrite(&val, 4, 1, f); } // Write tables, hash, strings - omitted for brevity, pack similarly using fwrite. fclose(f); } void mo_close(MOFile *mo) { free(mo->data); free(mo->orig_table); free(mo->trans_table); free(mo->hash_table); for (uint32_t i = 0; i < mo->num_strings; i++) { free(mo->orig_strings[i]); free(mo->trans_strings[i]); } free(mo->orig_strings); free(mo->trans_strings); free(mo); } // Example usage: // int main(int argc, char **argv) { // MOFile *mo = mo_open("example.mo"); // mo_print_properties(mo); // mo_write(mo, "output.mo"); // mo_close(mo); // return 0; // } // ===== end task-404 .MO ===== // ===== task-405 .MOBI [C++] ===== #include #include #include #include #include #include #include class MobiHandler { private: std::string filepath; std::vector data; size_t offset = 0; std::map properties; // Simplified to string for print public: MobiHandler(const std::string& fp) : filepath(fp) { std::ifstream file(fp, std::ios::binary | std::ios::ate); auto size = file.tellg(); data.resize(size); file.seekg(0); file.read(data.data(), size); parse(); } uint8_t readUint8() { return static_cast(data[offset++]); } uint16_t readUint16() { uint16_t val = (static_cast(data[offset]) << 8) | static_cast(data[offset + 1]); offset += 2; return val; } uint32_t readUint32() { uint32_t val = (static_cast(data[offset]) << 24) | (static_cast(data[offset + 1]) << 16) | (static_cast(data[offset + 2]) << 8) | static_cast(data[offset + 3]); offset += 4; return val; } std::string readString(size_t length) { std::string str(data.data() + offset, length); auto nullPos = str.find('\0'); if (nullPos != std::string::npos) str.resize(nullPos); offset += length; return str; } std::vector readBytes(size_t length) { std::vector bytes(data.begin() + offset, data.begin() + offset + length); offset += length; return bytes; } void parsePdbHeader() { properties["Database Name"] = readString(32); properties["Attributes"] = std::to_string(readUint16()); properties["Version"] = std::to_string(readUint16()); properties["Creation Date"] = std::to_string(readUint32()); properties["Modification Date"] = std::to_string(readUint32()); properties["Last Backup Date"] = std::to_string(readUint32()); properties["Modification Number"] = std::to_string(readUint32()); properties["App Info ID"] = std::to_string(readUint32()); properties["Sort Info ID"] = std::to_string(readUint32()); properties["Type"] = readString(4); properties["Creator"] = readString(4); properties["Unique ID Seed"] = std::to_string(readUint32()); properties["Next Record List ID"] = std::to_string(readUint32()); properties["Number of Records"] = std::to_string(readUint16()); } void parseRecordInfoList() { uint16_t numRecords = std::stoi(properties["Number of Records"]); std::string recordInfos = "["; for (uint16_t i = 0; i < numRecords; ++i) { recordInfos += "{Offset: " + std::to_string(readUint32()) + ", Attr: " + std::to_string(readUint8()) + ", ID: " + std::to_string((readUint8() << 16) | (readUint8() << 8) | readUint8()) + "},"; } if (!recordInfos.empty()) recordInfos.pop_back(); recordInfos += "]"; properties["Record Infos"] = recordInfos; } void parsePalmDocHeader() { uint32_t record0Offset = std::stoul(properties["Record Infos"].substr(9, 10)); // Simplified parse, adjust as needed offset = record0Offset; properties["Compression"] = std::to_string(readUint16()); properties["Unused"] = std::to_string(readUint16()); properties["Text Length"] = std::to_string(readUint32()); properties["Record Count"] = std::to_string(readUint16()); properties["Record Size"] = std::to_string(readUint16()); properties["Encryption Type"] = std::to_string(readUint16()); properties["Unknown (PalmDOC)"] = std::to_string(readUint16()); } void parseMobiHeader() { properties["Identifier (MOBI)"] = readString(4); uint32_t headerLength = readUint32(); properties["Header Length (MOBI)"] = std::to_string(headerLength); size_t headerEnd = offset + headerLength - 8; properties["Mobi Type"] = std::to_string(readUint32()); properties["Text Encoding"] = std::to_string(readUint32()); properties["Unique ID"] = std::to_string(readUint32()); properties["File Version"] = std::to_string(readUint32()); properties["Ortographic Index"] = std::to_string(readUint32()); properties["Inflection Index"] = std::to_string(readUint32()); properties["Index Names"] = std::to_string(readUint32()); properties["Index Keys"] = std::to_string(readUint32()); properties["Extra Index 0"] = std::to_string(readUint32()); properties["Extra Index 1"] = std::to_string(readUint32()); properties["Extra Index 2"] = std::to_string(readUint32()); properties["Extra Index 3"] = std::to_string(readUint32()); properties["Extra Index 4"] = std::to_string(readUint32()); properties["Extra Index 5"] = std::to_string(readUint32()); properties["First Non-Book Index"] = std::to_string(readUint32()); properties["Full Name Offset"] = std::to_string(readUint32()); properties["Full Name Length"] = std::to_string(readUint32()); properties["Locale"] = std::to_string(readUint32()); properties["Input Language"] = std::to_string(readUint32()); properties["Output Language"] = std::to_string(readUint32()); properties["Min Version"] = std::to_string(readUint32()); properties["First Image Index"] = std::to_string(readUint32()); properties["Huffman Record Offset"] = std::to_string(readUint32()); properties["Huffman Record Count"] = std::to_string(readUint32()); properties["Huffman Table Offset"] = std::to_string(readUint32()); properties["Huffman Table Length"] = std::to_string(readUint32()); properties["EXTH Flags"] = std::to_string(readUint32()); auto unknown84 = readBytes(32); properties["Unknown (0x84)"] = std::string(unknown84.begin(), unknown84.end()); properties["Unknown (0xA4)"] = std::to_string(readUint32()); properties["DRM Offset"] = std::to_string(readUint32()); properties["DRM Count"] = std::to_string(readUint32()); properties["DRM Size"] = std::to_string(readUint32()); properties["DRM Flags"] = std::to_string(readUint32()); auto unknownB8 = readBytes(8); properties["Unknown (0xB8)"] = std::string(unknownB8.begin(), unknownB8.end()); properties["First Content Record Number"] = std::to_string(readUint16()); properties["Last Content Record Number"] = std::to_string(readUint16()); properties["Unknown (0xC4)"] = std::to_string(readUint32()); properties["FCIS Record Number"] = std::to_string(readUint32()); properties["Unknown (0xCC)"] = std::to_string(readUint32()); properties["FLIS Record Number"] = std::to_string(readUint32()); properties["Unknown (0xD4)"] = std::to_string(readUint32()); auto unknownD8 = readBytes(8); properties["Unknown (0xD8)"] = std::string(unknownD8.begin(), unknownD8.end()); properties["Unknown (0xE0)"] = std::to_string(readUint32()); properties["First Compilation Data Section Count"] = std::to_string(readUint32()); properties["Number of Compilation Data Sections"] = std::to_string(readUint32()); properties["Unknown (0xEC)"] = std::to_string(readUint32()); properties["Extra Record Data Flags"] = std::to_string(readUint32()); properties["INDX Record Offset"] = std::to_string(readUint32()); offset = headerEnd; } void parseExthHeader() { uint32_t exthFlags = std::stoul(properties["EXTH Flags"]); if ((exthFlags & 0x40) == 0) return; properties["Identifier (EXTH)"] = readString(4); properties["Header Length (EXTH)"] = std::to_string(readUint32()); uint32_t recordCount = readUint32(); properties["Record Count (EXTH)"] = std::to_string(recordCount); std::string exthRecords = "["; for (uint32_t i = 0; i < recordCount; ++i) { uint32_t type = readUint32(); uint32_t len = readUint32(); auto dataBytes = readBytes(len - 8); std::string data(dataBytes.begin(), dataBytes.end()); exthRecords += "{type: " + std::to_string(type) + ", data: " + data + "},"; } if (!exthRecords.empty()) exthRecords.pop_back(); exthRecords += "]"; properties["EXTH Records"] = exthRecords; } void parse() { parsePdbHeader(); parseRecordInfoList(); parsePalmDocHeader(); parseMobiHeader(); parseExthHeader(); } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& newFilepath, const std::map& modifyProp) { std::vector writeData = data; for (const auto& mod : modifyProp) { if (mod.first == "Database Name") { std::string newName = mod.second; newName.resize(31, '\0'); newName += '\0'; std::memcpy(writeData.data(), newName.data(), 32); } // Add more } std::ofstream out(newFilepath, std::ios::binary); out.write(writeData.data(), writeData.size()); } }; int main() { MobiHandler handler("example.mobi"); handler.printProperties(); std::map mods = {{"Database Name", "Modified Title"}}; handler.write("modified.mobi", mods); return 0; } // ===== end task-405 .MOBI ===== // ===== task-406 .MOD [C] ===== #include #include #include #include typedef struct { char name[23]; uint32_t length; int8_t finetune; uint8_t volume; uint32_t loop_start; uint32_t loop_length; } Sample; typedef struct { char song_title[21]; Sample samples[31]; uint8_t song_length; uint8_t restart_byte; uint8_t pattern_sequence[128]; char signature[5]; uint8_t num_patterns; uint8_t num_channels; // Default 4 uint8_t* data; // For writing back size_t data_size; } ModFile; void modfile_init(ModFile* mod) { memset(mod, 0, sizeof(ModFile)); mod->num_channels = 4; } int modfile_read(ModFile* mod, const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) return -1; fseek(f, 0, SEEK_END); mod->data_size = ftell(f); fseek(f, 0, SEEK_SET); mod->data = malloc(mod->data_size); if (!mod->data) { fclose(f); return -1; } fread(mod->data, 1, mod->data_size, f); fclose(f); // Song Title (0-19) strncpy(mod->song_title, (char*)mod->data, 20); mod->song_title[20] = '\0'; // Samples (20-949) for (int i = 0; i < 31; i++) { uint8_t* offset = mod->data + 20 + i * 30; strncpy(mod->samples[i].name, (char*)offset, 22); mod->samples[i].name[22] = '\0'; uint16_t len = (offset[22] << 8) | offset[23]; mod->samples[i].length = len * 2; uint8_t ft = offset[24] & 0x0F; mod->samples[i].finetune = (ft > 7) ? ft - 16 : ft; mod->samples[i].volume = offset[25]; uint16_t ls = (offset[26] << 8) | offset[27]; mod->samples[i].loop_start = ls * 2; uint16_t ll = (offset[28] << 8) | offset[29]; mod->samples[i].loop_length = ll * 2; } // Song Length (950) mod->song_length = mod->data[950]; // Restart Byte (951) mod->restart_byte = mod->data[951]; // Pattern Sequence (952-1079) mod->num_patterns = 0; memcpy(mod->pattern_sequence, mod->data + 952, 128); for (int i = 0; i < 128; i++) { if (mod->pattern_sequence[i] > mod->num_patterns) mod->num_patterns = mod->pattern_sequence[i]; } mod->num_patterns++; // Signature (1080-1083) strncpy(mod->signature, (char*)(mod->data + 1080), 4); mod->signature[4] = '\0'; // Channels if (strcmp(mod->signature, "6CHN") == 0) mod->num_channels = 6; else if (strcmp(mod->signature, "8CHN") == 0 || strcmp(mod->signature, "FLT8") == 0) mod->num_channels = 8; return 0; } void modfile_print_properties(const ModFile* mod) { printf("Song Title: %s\n", mod->song_title); for (int i = 0; i < 31; i++) { printf("Sample %d:\n", i + 1); printf(" Name: %s\n", mod->samples[i].name); printf(" Length: %u\n", mod->samples[i].length); printf(" Finetune: %d\n", mod->samples[i].finetune); printf(" Volume: %u\n", mod->samples[i].volume); printf(" Loop Start: %u\n", mod->samples[i].loop_start); printf(" Loop Length: %u\n", mod->samples[i].loop_length); } printf("Song Length: %u\n", mod->song_length); printf("Restart Byte: %u\n", mod->restart_byte); printf("Pattern Sequence: "); for (int i = 0; i < 128; i++) { printf("%u%s", mod->pattern_sequence[i], (i < 127 ? ", " : "\n")); } printf("Signature: %s\n", mod->signature); printf("Number of Patterns: %u\n", mod->num_patterns); printf("Number of Channels: %u\n", mod->num_channels); } int modfile_write(const ModFile* mod, const char* filename) { if (!mod->data) return -1; FILE* f = fopen(filename, "wb"); if (!f) return -1; fwrite(mod->data, 1, mod->data_size, f); fclose(f); return 0; } void modfile_free(ModFile* mod) { free(mod->data); mod->data = NULL; } // Example usage: // int main() { // ModFile mod; // modfile_init(&mod); // if (modfile_read(&mod, "example.mod") == 0) { // modfile_print_properties(&mod); // modfile_write(&mod, "output.mod"); // } // modfile_free(&mod); // return 0; // } // ===== end task-406 .MOD ===== // ===== task-407 .MODULES [C] ===== #include #include #include #include #include #include #include struct ModulesFileHandler { char *filepath; }; struct ModulesFileHandler* create_handler(const char *filepath) { if (strstr(filepath, ".modules") == NULL && strstr(filepath, ".MODULES") == NULL) { fprintf(stderr, "File must have .MODULES extension\n"); exit(1); } struct ModulesFileHandler *handler = malloc(sizeof(struct ModulesFileHandler)); handler->filepath = strdup(filepath); return handler; } void destroy_handler(struct ModulesFileHandler *handler) { free(handler->filepath); free(handler); } void read_and_print_properties(struct ModulesFileHandler *handler) { struct stat st; if (stat(handler->filepath, &st) != 0) { perror("stat"); return; } printf("Device ID: %ld\n", (long)st.st_dev); printf("Inode number: %ld\n", (long)st.st_ino); printf("File mode: %o\n", st.st_mode); printf("Number of hard links: %ld\n", (long)st.st_nlink); printf("User ID of owner: %d\n", st.st_uid); printf("Group ID of owner: %d\n", st.st_gid); printf("Device ID for special files: %ld\n", (long)st.st_rdev); printf("File size: %ld\n", (long)st.st_size); printf("Block size: %ld\n", (long)st.st_blksize); printf("Number of blocks: %ld\n", (long)st.st_blocks); printf("Last access time: %s", ctime(&st.st_atime)); printf("Last modification time: %s", ctime(&st.st_mtime)); printf("Last status change time: %s", ctime(&st.st_ctime)); // Read content (decode as text) FILE *f = fopen(handler->filepath, "r"); if (f) { printf("\nFile Content:\n"); char buf[1024]; while (fgets(buf, sizeof(buf), f)) { printf("%s", buf); } fclose(f); } } void write_example_file(struct ModulesFileHandler *handler, const char *module_name) { FILE *f = fopen(handler->filepath, "w"); if (!f) { perror("fopen"); return; } fprintf(f, "#!/bin/sh\nif [ ! -c /dev/%s ] ; then\n exec /sbin/modprobe %s >/dev/null 2>&1\nfi\n", module_name, module_name); fclose(f); chmod(handler->filepath, 0755); printf("Written example .MODULES file to %s\n", handler->filepath); } // Example usage: // int main() { // struct ModulesFileHandler *handler = create_handler("example.modules"); // write_example_file(handler, "uinput"); // read_and_print_properties(handler); // destroy_handler(handler); // return 0; // } // ===== end task-407 .MODULES ===== // ===== task-409 .MOL [C] ===== #include #include #include #include #define MAX_LINES 10000 #define LINE_LEN 81 typedef struct { char molecule_name[81]; char user_initials[3]; char program_name[9]; char date_time[11]; char dimensional_codes[3]; int scaling_factors; double coordinate_scaling; double energy; int registry_number; char comment[81]; } Header; typedef struct { int num_atoms; int num_bonds; int num_atom_lists; int chiral_flag; int num_properties; char version[6]; } Counts; typedef struct { double x, y, z; char symbol[4]; int mass_diff; int charge; int stereo_parity; int h_count; int stereo_care; int valence; int h0; int inversion; int exact_change; } Atom; typedef struct { int atom1, atom2; int type; int stereo; int topology; int reacting_center; } Bond; typedef struct { int attached_atom; char list_type[2]; int num_entries; char entries[5][5]; } AtomList; typedef struct { Header header; Counts counts; Atom *atoms; Bond *bonds; AtomList *atom_lists; char **properties_block; int properties_block_count; } MolProperties; void init_properties(MolProperties *props) { memset(&props->header, 0, sizeof(Header)); memset(&props->counts, 0, sizeof(Counts)); props->atoms = NULL; props->bonds = NULL; props->atom_lists = NULL; props->properties_block = NULL; props->properties_block_count = 0; } void free_properties(MolProperties *props) { free(props->atoms); free(props->bonds); free(props->atom_lists); for (int i = 0; i < props->properties_block_count; i++) { free(props->properties_block[i]); } free(props->properties_block); } int read_mol(const char *filepath, MolProperties *props) { FILE *fp = fopen(filepath, "r"); if (!fp) return -1; char lines[MAX_LINES][LINE_LEN]; int line_count = 0; while (fgets(lines[line_count], LINE_LEN, fp) && line_count < MAX_LINES) { line_count++; } fclose(fp); init_properties(props); // Header if (line_count >= 4) { strncpy(props->header.molecule_name, lines[0], 80); props->header.molecule_name[80] = '\0'; char line2[81]; strncpy(line2, lines[1], 80); line2[80] = '\0'; strncpy(props->header.user_initials, line2, 2); props->header.user_initials[2] = '\0'; strncpy(props->header.program_name, line2 + 2, 8); props->header.program_name[8] = '\0'; strncpy(props->header.date_time, line2 + 10, 10); props->header.date_time[10] = '\0'; strncpy(props->header.dimensional_codes, line2 + 20, 2); props->header.dimensional_codes[2] = '\0'; props->header.scaling_factors = atoi(line2 + 22); props->header.coordinate_scaling = atof(line2 + 24); props->header.energy = atof(line2 + 34); props->header.registry_number = atoi(line2 + 46); strncpy(props->header.comment, lines[2], 80); props->header.comment[80] = '\0'; } // Counts char counts_line[81]; if (line_count > 3) { strncpy(counts_line, lines[3], 80); counts_line[80] = '\0'; if (strstr(counts_line, "V2000")) { char temp[4]; strncpy(temp, counts_line, 3); temp[3] = '\0'; props->counts.num_atoms = atoi(temp); strncpy(temp, counts_line + 3, 3); temp[3] = '\0'; props->counts.num_bonds = atoi(temp); strncpy(temp, counts_line + 6, 3); temp[3] = '\0'; props->counts.num_atom_lists = atoi(temp); strncpy(temp, counts_line + 12, 3); temp[3] = '\0'; props->counts.chiral_flag = atoi(temp); strncpy(temp, counts_line + 30, 3); temp[3] = '\0'; props->counts.num_properties = atoi(temp); strncpy(props->counts.version, counts_line + 34, 5); props->counts.version[5] = '\0'; } } // Atoms props->atoms = malloc(props->counts.num_atoms * sizeof(Atom)); int atom_start = 4; for (int i = 0; i < props->counts.num_atoms; i++) { char line[81]; if (atom_start + i >= line_count) break; strncpy(line, lines[atom_start + i], 80); line[80] = '\0'; props->atoms[i].x = atof(line); props->atoms[i].y = atof(line + 10); props->atoms[i].z = atof(line + 20); strncpy(props->atoms[i].symbol, line + 31, 3); props->atoms[i].symbol[3] = '\0'; props->atoms[i].mass_diff = atoi(line + 34); props->atoms[i].charge = atoi(line + 36); props->atoms[i].stereo_parity = atoi(line + 39); props->atoms[i].h_count = atoi(line + 42); props->atoms[i].stereo_care = atoi(line + 45); props->atoms[i].valence = atoi(line + 48); props->atoms[i].h0 = atoi(line + 51); props->atoms[i].inversion = atoi(line + 60); props->atoms[i].exact_change = atoi(line + 63); } // Bonds props->bonds = malloc(props->counts.num_bonds * sizeof(Bond)); int bond_start = atom_start + props->counts.num_atoms; for (int i = 0; i < props->counts.num_bonds; i++) { char line[81]; if (bond_start + i >= line_count) break; strncpy(line, lines[bond_start + i], 80); line[80] = '\0'; props->bonds[i].atom1 = atoi(line); props->bonds[i].atom2 = atoi(line + 3); props->bonds[i].type = atoi(line + 6); props->bonds[i].stereo = atoi(line + 9); props->bonds[i].topology = atoi(line + 15); props->bonds[i].reacting_center = atoi(line + 18); } // Atom Lists props->atom_lists = malloc(props->counts.num_atom_lists * sizeof(AtomList)); int list_start = bond_start + props->counts.num_bonds; for (int i = 0; i < props->counts.num_atom_lists; i++) { char line[81]; if (list_start + i >= line_count) break; strncpy(line, lines[list_start + i], 80); line[80] = '\0'; props->atom_lists[i].attached_atom = atoi(line); strncpy(props->atom_lists[i].list_type, line + 3, 1); props->atom_lists[i].list_type[1] = '\0'; props->atom_lists[i].num_entries = atoi(line + 8); for (int j = 0; j < 5; j++) { strncpy(props->atom_lists[i].entries[j], line + 10 + j*5, 4); props->atom_lists[i].entries[j][4] = '\0'; } } // Properties Block int prop_start = list_start + props->counts.num_atom_lists; props->properties_block = malloc((line_count - prop_start) * sizeof(char*)); for (int i = prop_start; i < line_count; i++) { if (strstr(lines[i], "M END")) break; if (strlen(lines[i]) > 0) { props->properties_block[props->properties_block_count] = strdup(lines[i]); props->properties_block_count++; } } return 0; } void print_properties(const MolProperties *props) { printf("{\n"); printf(" \"header\": {\n"); printf(" \"molecule_name\": \"%s\",\n", props->header.molecule_name); printf(" \"user_initials\": \"%s\",\n", props->header.user_initials); printf(" \"program_name\": \"%s\",\n", props->header.program_name); printf(" \"date_time\": \"%s\",\n", props->header.date_time); printf(" \"dimensional_codes\": \"%s\",\n", props->header.dimensional_codes); printf(" \"scaling_factors\": %d,\n", props->header.scaling_factors); printf(" \"coordinate_scaling\": %.5f,\n", props->header.coordinate_scaling); printf(" \"energy\": %.5f,\n", props->header.energy); printf(" \"registry_number\": %d,\n", props->header.registry_number); printf(" \"comment\": \"%s\"\n", props->header.comment); printf(" },\n"); printf(" \"counts\": {\n"); printf(" \"num_atoms\": %d,\n", props->counts.num_atoms); printf(" \"num_bonds\": %d,\n", props->counts.num_bonds); printf(" \"num_atom_lists\": %d,\n", props->counts.num_atom_lists); printf(" \"chiral_flag\": %d,\n", props->counts.chiral_flag); printf(" \"num_properties\": %d,\n", props->counts.num_properties); printf(" \"version\": \"%s\"\n", props->counts.version); printf(" },\n"); printf(" \"atoms\": [\n"); for (int i = 0; i < props->counts.num_atoms; i++) { printf(" {\n"); printf(" \"x\": %.4f,\n", props->atoms[i].x); printf(" \"y\": %.4f,\n", props->atoms[i].y); printf(" \"z\": %.4f,\n", props->atoms[i].z); printf(" \"symbol\": \"%s\",\n", props->atoms[i].symbol); printf(" \"mass_diff\": %d,\n", props->atoms[i].mass_diff); printf(" \"charge\": %d,\n", props->atoms[i].charge); printf(" \"stereo_parity\": %d,\n", props->atoms[i].stereo_parity); printf(" \"h_count\": %d,\n", props->atoms[i].h_count); printf(" \"stereo_care\": %d,\n", props->atoms[i].stereo_care); printf(" \"valence\": %d,\n", props->atoms[i].valence); printf(" \"h0\": %d,\n", props->atoms[i].h0); printf(" \"inversion\": %d,\n", props->atoms[i].inversion); printf(" \"exact_change\": %d\n", props->atoms[i].exact_change); printf(" }%s\n", i < props->counts.num_atoms - 1 ? "," : ""); } printf(" ],\n"); printf(" \"bonds\": [\n"); for (int i = 0; i < props->counts.num_bonds; i++) { printf(" {\n"); printf(" \"atom1\": %d,\n", props->bonds[i].atom1); printf(" \"atom2\": %d,\n", props->bonds[i].atom2); printf(" \"type\": %d,\n", props->bonds[i].type); printf(" \"stereo\": %d,\n", props->bonds[i].stereo); printf(" \"topology\": %d,\n", props->bonds[i].topology); printf(" \"reacting_center\": %d\n", props->bonds[i].reacting_center); printf(" }%s\n", i < props->counts.num_bonds - 1 ? "," : ""); } printf(" ],\n"); printf(" \"atom_lists\": [\n"); for (int i = 0; i < props->counts.num_atom_lists; i++) { printf(" {\n"); printf(" \"attached_atom\": %d,\n", props->atom_lists[i].attached_atom); printf(" \"list_type\": \"%s\",\n", props->atom_lists[i].list_type); printf(" \"num_entries\": %d,\n", props->atom_lists[i].num_entries); printf(" \"entries\": ["); for (int j = 0; j < 5; j++) { if (strlen(props->atom_lists[i].entries[j]) > 0) { printf("\"%s\"%s", props->atom_lists[i].entries[j], j < 4 ? ", " : ""); } } printf("]\n"); printf(" }%s\n", i < props->counts.num_atom_lists - 1 ? "," : ""); } printf(" ],\n"); printf(" \"properties_block\": [\n"); for (int i = 0; i < props->properties_block_count; i++) { printf(" \"%s\"%s\n", props->properties_block[i], i < props->properties_block_count - 1 ? "," : ""); } printf(" ]\n"); printf("}\n"); } int write_mol(const char *filepath, const MolProperties *props) { FILE *fp = fopen(filepath, "w"); if (!fp) return -1; fprintf(fp, "%-80s\n", props->header.molecule_name); char line2[81]; snprintf(line2, 81, "%2s%8s%10s%2s%2d%10.5f%12.5f%6d", props->header.user_initials, props->header.program_name, props->header.date_time, props->header.dimensional_codes, props->header.scaling_factors, props->header.coordinate_scaling, props->header.energy, props->header.registry_number); fprintf(fp, "%-80s\n", line2); fprintf(fp, "%-80s\n", props->header.comment); char counts_line[81]; snprintf(counts_line, 81, "%3d%3d%3d %3d %3d V2000", props->counts.num_atoms, props->counts.num_bonds, props->counts.num_atom_lists, props->counts.chiral_flag, props->counts.num_properties); fprintf(fp, "%-80s\n", counts_line); for (int i = 0; i < props->counts.num_atoms; i++) { char line[81]; snprintf(line, 81, "%10.4f%10.4f%10.4f %-3s%2d%3d%3d%3d%3d%3d%3d %3d%3d", props->atoms[i].x, props->atoms[i].y, props->atoms[i].z, props->atoms[i].symbol, props->atoms[i].mass_diff, props->atoms[i].charge, props->atoms[i].stereo_parity, props->atoms[i].h_count, props->atoms[i].stereo_care, props->atoms[i].valence, props->atoms[i].h0, props->atoms[i].inversion, props->atoms[i].exact_change); fprintf(fp, "%-80s\n", line); } for (int i = 0; i < props->counts.num_bonds; i++) { char line[81]; snprintf(line, 81, "%3d%3d%3d%3d %3d%3d", props->bonds[i].atom1, props->bonds[i].atom2, props->bonds[i].type, props->bonds[i].stereo, props->bonds[i].topology, props->bonds[i].reacting_center); fprintf(fp, "%-80s\n", line); } for (int i = 0; i < props->counts.num_atom_lists; i++) { char entries_str[26] = ""; for (int j = 0; j < 5; j++) { char temp[6]; snprintf(temp, 6, "%4s ", props->atom_lists[i].entries[j]); strcat(entries_str, temp); } char line[81]; snprintf(line, 81, "%3d%s %1d %s", props->atom_lists[i].attached_atom, props->atom_lists[i].list_type, props->atom_lists[i].num_entries, entries_str); fprintf(fp, "%-80s\n", line); } for (int i = 0; i < props->properties_block_count; i++) { fprintf(fp, "%-80s\n", props->properties_block[i]); } fprintf(fp, "M END\n"); fclose(fp); return 0; } int main(int argc, char *argv[]) { if (argc < 2) return 1; MolProperties props; if (read_mol(argv[1], &props) == 0) { print_properties(&props); write_mol("output.mol", &props); free_properties(&props); } return 0; } // ===== end task-409 .MOL ===== // ===== task-410 .MOL2 [C++] ===== #include #include #include #include #include #include #include class Mol2Handler { private: std::map molecule; std::vector> atoms; std::vector> bonds; std::vector> substructures; public: void read(const std::string& filename) { std::ifstream file(filename); if (!file.is_open()) { std::cerr << "Error opening file: " << filename << std::endl; return; } std::string line, current_section; while (std::getline(file, line)) { std::istringstream iss(line); std::string token; iss >> token; if (token.substr(0, 9) == "@") { current_section = token.substr(9); continue; } if (token[0] == '#' || line.empty()) continue; if (current_section == "MOLECULE") { if (molecule.find("mol_name") == molecule.end()) { molecule["mol_name"] = line; } else if (molecule.find("num_atoms") == molecule.end()) { std::istringstream count_iss(line); std::string num; count_iss >> num; molecule["num_atoms"] = num; count_iss >> num; molecule["num_bonds"] = num.empty() ? "0" : num; count_iss >> num; molecule["num_subst"] = num.empty() ? "0" : num; count_iss >> num; molecule["num_feat"] = num.empty() ? "0" : num; count_iss >> num; molecule["num_sets"] = num.empty() ? "0" : num; } else if (molecule.find("mol_type") == molecule.end()) { molecule["mol_type"] = line; } else if (molecule.find("charge_type") == molecule.end()) { molecule["charge_type"] = line; } else if (molecule.find("status_bits") == molecule.end()) { molecule["status_bits"] = line; } else { molecule["mol_comment"] = line; } } else if (current_section == "ATOM") { std::map atom; std::istringstream atom_iss(line); atom_iss >> atom["atom_id"] >> atom["atom_name"] >> atom["x"] >> atom["y"] >> atom["z"] >> atom["atom_type"]; std::string temp; atom_iss >> temp; if (!temp.empty()) atom["subst_id"] = temp; atom_iss >> temp; if (!temp.empty()) atom["subst_name"] = temp; atom_iss >> temp; if (!temp.empty()) atom["charge"] = temp; atom_iss >> temp; if (!temp.empty()) atom["status_bit"] = temp; atoms.push_back(atom); } else if (current_section == "BOND") { std::map bond; std::istringstream bond_iss(line); bond_iss >> bond["bond_id"] >> bond["origin_atom_id"] >> bond["target_atom_id"] >> bond["bond_type"]; std::string temp; bond_iss >> temp; if (!temp.empty()) bond["status_bits"] = temp; bonds.push_back(bond); } else if (current_section == "SUBSTRUCTURE") { std::map sub; std::istringstream sub_iss(line); sub_iss >> sub["subst_id"] >> sub["subst_name"] >> sub["root_atom"]; std::string temp; sub_iss >> temp; if (!temp.empty()) sub["subst_type"] = temp; sub_iss >> temp; if (!temp.empty()) sub["dict_type"] = temp; sub_iss >> temp; if (!temp.empty()) sub["chain"] = temp; sub_iss >> temp; if (!temp.empty()) sub["sub_type"] = temp; sub_iss >> temp; if (!temp.empty()) sub["inter_bonds"] = temp; sub_iss >> temp; if (!temp.empty()) sub["status"] = temp; sub_iss >> temp; if (!temp.empty()) sub["comment"] = temp; substructures.push_back(sub); } } file.close(); } void print_properties() { std::cout << "Molecule Properties:" << std::endl; for (const auto& kv : molecule) { std::cout << kv.first << ": " << kv.second << std::endl; } std::cout << "\nAtoms:" << std::endl; for (const auto& atom : atoms) { for (const auto& kv : atom) { std::cout << kv.first << ": " << kv.second << " "; } std::cout << std::endl; } std::cout << "\nBonds:" << std::endl; for (const auto& bond : bonds) { for (const auto& kv : bond) { std::cout << kv.first << ": " << kv.second << " "; } std::cout << std::endl; } std::cout << "\nSubstructures:" << std::endl; for (const auto& sub : substructures) { for (const auto& kv : sub) { std::cout << kv.first << ": " << kv.second << " "; } std::cout << std::endl; } } void write(const std::string& filename) { std::ofstream file(filename); if (!file.is_open()) { std::cerr << "Error opening file for writing: " << filename << std::endl; return; } file << "@MOLECULE" << std::endl; file << molecule["mol_name"] << std::endl; std::string counts = molecule["num_atoms"] + " " + molecule["num_bonds"] + " " + molecule["num_subst"] + " 0 0"; file << counts << std::endl; file << (molecule.find("mol_type") != molecule.end() ? molecule["mol_type"] : "SMALL") << std::endl; file << (molecule.find("charge_type") != molecule.end() ? molecule["charge_type"] : "NO_CHARGES") << std::endl; if (molecule.find("status_bits") != molecule.end()) file << molecule["status_bits"] << std::endl; if (molecule.find("mol_comment") != molecule.end()) file << molecule["mol_comment"] << std::endl; file << std::endl << "@ATOM" << std::endl; for (const auto& atom : atoms) { file << std::setw(5) << atom.at("atom_id") << " " << std::left << std::setw(5) << atom.at("atom_name") << " " << std::fixed << std::setprecision(4) << std::stof(atom.at("x")) << " " << std::stof(atom.at("y")) << " " << std::stof(atom.at("z")) << " " << atom.at("atom_type"); if (atom.find("subst_id") != atom.end()) file << " " << atom.at("subst_id"); if (atom.find("subst_name") != atom.end()) file << " " << atom.at("subst_name"); if (atom.find("charge") != atom.end()) file << " " << std::setprecision(3) << std::stof(atom.at("charge")); if (atom.find("status_bit") != atom.end()) file << " " << atom.at("status_bit"); file << std::endl; } file << "@BOND" << std::endl; for (const auto& bond : bonds) { file << std::setw(5) << bond.at("bond_id") << " " << std::setw(5) << bond.at("origin_atom_id") << " " << std::setw(5) << bond.at("target_atom_id") << " " << bond.at("bond_type"); if (bond.find("status_bits") != bond.end()) file << " " << bond.at("status_bits"); file << std::endl; } if (!substructures.empty()) { file << "@SUBSTRUCTURE" << std::endl; for (const auto& sub : substructures) { file << std::setw(5) << sub.at("subst_id") << " " << std::left << std::setw(10) << sub.at("subst_name") << " " << std::setw(5) << sub.at("root_atom"); if (sub.find("subst_type") != sub.end()) file << " " << sub.at("subst_type"); if (sub.find("dict_type") != sub.end()) file << " " << sub.at("dict_type"); if (sub.find("chain") != sub.end()) file << " " << sub.at("chain"); if (sub.find("sub_type") != sub.end()) file << " " << sub.at("sub_type"); if (sub.find("inter_bonds") != sub.end()) file << " " << sub.at("inter_bonds"); if (sub.find("status") != sub.end()) file << " " << sub.at("status"); if (sub.find("comment") != sub.end()) file << " " << sub.at("comment"); file << std::endl; } } file.close(); } }; // Example usage: // int main() { // Mol2Handler handler; // handler.read("input.mol2"); // handler.print_properties(); // handler.write("output.mol2"); // return 0; // } // ===== end task-410 .MOL2 ===== // ===== task-411 .MOP [C++] ===== #include #include #include #include #include #include #include class MopFile { private: std::vector keywords; std::string title; std::string comment; std::vector> atoms; // Use double for all numeric, cast ints bool isCartesian; bool startsWith(const std::string& str, const std::string& prefix) { return str.compare(0, prefix.length(), prefix) == 0; } public: MopFile(const std::string& filename = "") { keywords.clear(); title = ""; comment = ""; atoms.clear(); isCartesian = false; if (!filename.empty()) read(filename); } void read(const std::string& filename) { std::ifstream file(filename); if (!file.is_open()) throw std::runtime_error("Cannot open file"); std::vector lines; std::string line; while (std::getline(file, line)) { if (!line.empty()) { std::stringstream ss(line); std::string trimmed; ss >> std::ws; std::getline(ss, trimmed); if (!trimmed.empty()) lines.push_back(trimmed); } } file.close(); if (lines.empty()) throw std::runtime_error("Empty file"); std::stringstream ss0(lines[0]); std::string kw; while (ss0 >> kw) keywords.push_back(kw); title = lines.size() > 1 ? lines[1] : ""; comment = lines.size() > 2 ? lines[2] : ""; isCartesian = false; for (const auto& k : keywords) { if (startsWith(std::string(1, std::toupper(k[0])) + k.substr(1), "XYZ")) { isCartesian = true; break; } } atoms.clear(); for (size_t i = 3; i < lines.size(); ++i) { std::stringstream ss(lines[i]); std::string symbol; ss >> symbol; if (symbol.empty()) continue; std::map atom; atom["symbol_str"] = 0; // Placeholder for string // Store symbol as string somehow; for simplicity, print separately double v1, o1, v2, o2, v3, o3, c1, c2, c3; if (isCartesian) { ss >> v1 >> o1 >> v2 >> o2 >> v3 >> o3; atom["x"] = v1; atom["opt_x"] = o1; atom["y"] = v2; atom["opt_y"] = o2; atom["z"] = v3; atom["opt_z"] = o3; } else { ss >> v1 >> o1 >> v2 >> o2 >> v3 >> o3 >> c1 >> c2; atom["dist"] = v1; atom["opt_d"] = o1; atom["angle"] = v2; atom["opt_a"] = o2; atom["dihed"] = v3; atom["opt_di"] = o3; atom["conn1"] = c1; atom["conn2"] = c2; ss >> c3; atom["conn3"] = ss.fail() ? 0 : c3; } atoms.push_back(atom); } } void write(const std::string& filename) { std::ofstream file(filename); if (!file.is_open()) throw std::runtime_error("Cannot write file"); for (const auto& kw : keywords) file << kw << " "; file << "\n" << title << "\n" << comment << "\n"; for (const auto& atom : atoms) { // Symbol not stored; assume we need to add it separately or modify class // For this impl, skip symbol print or assume it's stored elsewhere // To fix, use struct instead of map for atoms if (isCartesian) { file << std::fixed << std::setprecision(8) << atom.at("x") << " " << (int)atom.at("opt_x") << " " << std::setprecision(8) << atom.at("y") << " " << (int)atom.at("opt_y") << " " << std::setprecision(8) << atom.at("z") << " " << (int)atom.at("opt_z") << "\n"; } else { file << std::fixed << std::setprecision(8) << atom.at("dist") << " " << (int)atom.at("opt_d") << " " << std::setprecision(7) << atom.at("angle") << " " << (int)atom.at("opt_a") << " " << std::setprecision(7) << atom.at("dihed") << " " << (int)atom.at("opt_di") << " " << (int)atom.at("conn1") << " " << (int)atom.at("conn2") << " " << (int)atom.at("conn3") << "\n"; } } file.close(); } void printProperties() { std::cout << "Keywords:"; for (const auto& kw : keywords) std::cout << " " << kw; std::cout << "\nTitle: " << title << "\nComment: " << comment << "\n"; std::cout << "Geometry Type: " << (isCartesian ? "Cartesian" : "Internal") << "\nAtoms:\n"; for (const auto& atom : atoms) { if (isCartesian) { std::cout << "x: " << atom.at("x") << ", opt_x: " << (int)atom.at("opt_x") << ", y: " << atom.at("y") << ", opt_y: " << (int)atom.at("opt_y") << ", z: " << atom.at("z") << ", opt_z: " << (int)atom.at("opt_z") << "\n"; } else { std::cout << "dist: " << atom.at("dist") << ", opt_d: " << (int)atom.at("opt_d") << ", angle: " << atom.at("angle") << ", opt_a: " << (int)atom.at("opt_a") << ", dihed: " << atom.at("dihed") << ", opt_di: " << (int)atom.at("opt_di") << ", conn1: " << (int)atom.at("conn1") << ", conn2: " << (int)atom.at("conn2") << ", conn3: " << (int)atom.at("conn3") << "\n"; } } } }; // ===== end task-411 .MOP ===== // ===== task-412 .MOV [C] ===== #include #include #include #include typedef struct { uint8_t *data; size_t length; size_t pos; // Use arrays or structs for properties (simplified with printf instead of storing all) } MovParser; uint32_t read_uint32(MovParser *parser) { uint32_t val = (parser->data[parser->pos] << 24) | (parser->data[parser->pos+1] << 16) | (parser->data[parser->pos+2] << 8) | parser->data[parser->pos+3]; parser->pos += 4; return val; } uint16_t read_uint16(MovParser *parser) { uint16_t val = (parser->data[parser->pos] << 8) | parser->data[parser->pos+1]; parser->pos += 2; return val; } double read_fixed1616(MovParser *parser) { return (double)read_uint32(parser) / 65536.0; } double read_fixed88(MovParser *parser) { return (double)read_uint16(parser) / 256.0; } char* read_string(MovParser *parser, int length) { char* str = malloc(length + 1); memcpy(str, &parser->data[parser->pos], length); str[length] = '\0'; parser->pos += length; return str; } void parse_atom(MovParser *parser) { size_t start_pos = parser->pos; uint32_t size = read_uint32(parser); char* type = read_string(parser, 4); if (strcmp(type, "ftyp") == 0) { char* major = read_string(parser, 4); uint32_t minor = read_uint32(parser); printf("Major Brand: %s\n", major); printf("Minor Version: %u\n", minor); printf("Compatible Brands: "); while (parser->pos < start_pos + size) { char* brand = read_string(parser, 4); printf("%s ", brand); free(brand); } printf("\n"); free(major); } else if (strcmp(type, "mvhd") == 0) { parser->pos += 1; // version parser->pos += 3; // flags printf("Movie Creation Time: %u\n", read_uint32(parser)); printf("Movie Modification Time: %u\n", read_uint32(parser)); printf("Time Scale: %u\n", read_uint32(parser)); printf("Movie Duration: %u\n", read_uint32(parser)); printf("Preferred Rate: %f\n", read_fixed1616(parser)); printf("Preferred Volume: %f\n", read_fixed88(parser)); parser->pos += 10; // reserved parser->pos += 36; // matrix printf("Preview Time: %u\n", read_uint32(parser)); printf("Preview Duration: %u\n", read_uint32(parser)); printf("Poster Time: %u\n", read_uint32(parser)); printf("Selection Time: %u\n", read_uint32(parser)); printf("Selection Duration: %u\n", read_uint32(parser)); printf("Current Time: %u\n", read_uint32(parser)); printf("Next Track ID: %u\n", read_uint32(parser)); } else if (strcmp(type, "tkhd") == 0) { parser->pos += 1; // version parser->pos += 3; // flags printf("Track Creation Time: %u\n", read_uint32(parser)); printf("Track Modification Time: %u\n", read_uint32(parser)); printf("Track ID: %u\n", read_uint32(parser)); parser->pos += 4; // reserved printf("Track Duration: %u\n", read_uint32(parser)); parser->pos += 8; // reserved int16_t layer = (int16_t)read_uint16(parser); printf("Track Layer: %d\n", layer); int16_t alt_group = (int16_t)read_uint16(parser); printf("Alternate Group: %d\n", alt_group); printf("Track Volume: %f\n", read_fixed88(parser)); parser->pos += 2; // reserved parser->pos += 36; // matrix printf("Track Width: %f\n", read_fixed1616(parser)); printf("Track Height: %f\n", read_fixed1616(parser)); } else if (strcmp(type, "hdlr") == 0) { parser->pos += 8; // version, flags, component type char* htype = read_string(parser, 4); printf("Handler Type: %s\n", htype); free(htype); } free(type); parser->pos = start_pos + size; } void parse(MovParser *parser) { while (parser->pos < parser->length) { parse_atom(parser); } } MovParser* mov_parser_init(const char* filename) { FILE *f = fopen(filename, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); size_t len = ftell(f); fseek(f, 0, SEEK_SET); MovParser* parser = malloc(sizeof(MovParser)); parser->data = malloc(len); fread(parser->data, 1, len, f); fclose(f); parser->length = len; parser->pos = 0; return parser; } void print_properties(MovParser *parser) { parser->pos = 0; // Reset to print again parse(parser); } void write_file(MovParser *parser, const char* output_filename) { FILE *f = fopen(output_filename, "wb"); if (f) { fwrite(parser->data, 1, parser->length, f); fclose(f); printf("File written to %s\n", output_filename); } } void mov_parser_free(MovParser *parser) { free(parser->data); free(parser); } // Example usage: // int main() { // MovParser* parser = mov_parser_init("example.mov"); // if (parser) { // print_properties(parser); // write_file(parser, "output.mov"); // mov_parser_free(parser); // } // return 0; // } // ===== end task-412 .MOV ===== // ===== task-413 .MP2 [C] ===== #include #include #include #include typedef struct { char *version; char *crc; int bitrate; int sampling_rate; char *padding; char *private_bit; char *channels; char *mode_ext; char *copyright; char *original; char *emphasis; } MP2Properties; typedef struct { char *filename; MP2Properties *properties; uint8_t **frames; int frame_count; size_t *frame_sizes; } MP2File; MP2File* mp2_open(const char *filename) { MP2File *mp2 = malloc(sizeof(MP2File)); mp2->filename = strdup(filename); mp2->properties = NULL; mp2->frames = NULL; mp2->frame_count = 0; mp2->frame_sizes = NULL; FILE *f = fopen(filename, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); long len = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(len); fread(data, 1, len, f); fclose(f); int offset = 0; while (offset < len - 4) { uint16_t sync = (data[offset] << 8) | data[offset + 1]; if (sync != 0xFFFC && sync != 0xFFFD) { offset++; continue; } uint32_t header = (data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]; uint32_t version_bits = (header >> 19) & 0x03; char *version = version_bits == 0b11 ? "MPEG-1" : version_bits == 0b10 ? "MPEG-2" : version_bits == 0b00 ? "MPEG-2.5" : "Reserved"; uint32_t layer_bits = (header >> 17) & 0x03; if (layer_bits != 0b10) break; char *crc = ((header >> 16) & 0x01) == 0 ? "Protected" : "Not protected"; uint32_t bitrate_idx = (header >> 12) & 0x0F; int bitrates_v1[16] = {0,32,48,56,64,80,96,112,128,160,192,224,256,320,384,0}; int bitrates_v2[16] = {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0}; int bitrate = strcmp(version, "MPEG-1") == 0 ? bitrates_v1[bitrate_idx] : bitrates_v2[bitrate_idx]; uint32_t sr_idx = (header >> 10) & 0x03; int sr_v1[4] = {44100,48000,32000,0}; int sr_v2[4] = {22050,24000,16000,0}; int sr_v25[4] = {11025,12000,8000,0}; int sr = strcmp(version, "MPEG-1") == 0 ? sr_v1[sr_idx] : strcmp(version, "MPEG-2") == 0 ? sr_v2[sr_idx] : sr_v25[sr_idx]; char *padding = ((header >> 9) & 0x01) ? "Yes" : "No"; char *private_bit = ((header >> 8) & 0x01) ? "Set" : "Not set"; uint32_t channel_bits = (header >> 6) & 0x03; char *channels = channel_bits == 0b00 ? "Stereo" : channel_bits == 0b01 ? "Joint stereo" : channel_bits == 0b10 ? "Dual channel" : "Mono"; uint32_t mode_ext_idx = (header >> 4) & 0x03; char *mode_ext_arr[4] = {"Bands 4-31", "Bands 8-31", "Bands 12-31", "Bands 16-31"}; char *mode_ext = mode_ext_arr[mode_ext_idx]; char *copyright = ((header >> 3) & 0x01) ? "Yes" : "No"; char *original = ((header >> 2) & 0x01) ? "Yes" : "No"; uint32_t emphasis_bits = header & 0x03; char *emphasis = emphasis_bits == 0b00 ? "None" : emphasis_bits == 0b01 ? "50/15 us" : emphasis_bits == 0b11 ? "CCITT J.17" : "Reserved"; mp2->properties = realloc(mp2->properties, sizeof(MP2Properties) * (mp2->frame_count + 1)); MP2Properties *props = &mp2->properties[mp2->frame_count]; props->version = strdup(version); props->crc = strdup(crc); props->bitrate = bitrate; props->sampling_rate = sr; props->padding = strdup(padding); props->private_bit = strdup(private_bit); props->channels = strdup(channels); props->mode_ext = strdup(mode_ext); props->copyright = strdup(copyright); props->original = strdup(original); props->emphasis = strdup(emphasis); int frame_size = (bitrate * 144000 / sr) + ((header >> 9) & 0x01); mp2->frames = realloc(mp2->frames, sizeof(uint8_t*) * (mp2->frame_count + 1)); mp2->frames[mp2->frame_count] = malloc(frame_size); memcpy(mp2->frames[mp2->frame_count], data + offset, frame_size); mp2->frame_sizes = realloc(mp2->frame_sizes, sizeof(size_t) * (mp2->frame_count + 1)); mp2->frame_sizes[mp2->frame_count] = frame_size; offset += frame_size; mp2->frame_count++; } free(data); return mp2; } void mp2_print_properties(MP2File *mp2) { for (int i = 0; i < mp2->frame_count; i++) { MP2Properties *p = &mp2->properties[i]; printf("Frame %d:\n", i + 1); printf(" Version: %s\n", p->version); printf(" CRC: %s\n", p->crc); printf(" Bitrate: %d\n", p->bitrate); printf(" Sampling Rate: %d\n", p->sampling_rate); printf(" Padding: %s\n", p->padding); printf(" Private: %s\n", p->private_bit); printf(" Channels: %s\n", p->channels); printf(" Mode Ext: %s\n", p->mode_ext); printf(" Copyright: %s\n", p->copyright); printf(" Original: %s\n", p->original); printf(" Emphasis: %s\n", p->emphasis); } printf("Total Frames: %d\n", mp2->frame_count); if (mp2->frame_count > 0) { long total_samples = (long)mp2->frame_count * 1152; int avg_sr = mp2->properties[0].sampling_rate; double duration = avg_sr ? (double)total_samples / avg_sr : 0; printf("Estimated Duration: %.2f seconds\n", duration); } } void mp2_write(MP2File *mp2, const char *output_filename) { FILE *f = fopen(output_filename, "wb"); if (!f) return; for (int i = 0; i < mp2->frame_count; i++) { fwrite(mp2->frames[i], 1, mp2->frame_sizes[i], f); } fclose(f); printf("File written to %s\n", output_filename); } void mp2_close(MP2File *mp2) { for (int i = 0; i < mp2->frame_count; i++) { free(mp2->properties[i].version); free(mp2->properties[i].crc); free(mp2->properties[i].padding); free(mp2->properties[i].private_bit); free(mp2->properties[i].channels); free(mp2->properties[i].mode_ext); free(mp2->properties[i].copyright); free(mp2->properties[i].original); free(mp2->properties[i].emphasis); free(mp2->frames[i]); } free(mp2->properties); free(mp2->frames); free(mp2->frame_sizes); free(mp2->filename); free(mp2); } // Example usage: // int main() { // MP2File *mp2 = mp2_open("sample.mp2"); // if (mp2) { // mp2_print_properties(mp2); // mp2_write(mp2, "output.mp2"); // mp2_close(mp2); // } // return 0; // } // ===== end task-413 .MP2 ===== // ===== task-414 .MP3 [C++] ===== #include #include #include #include #include #include #include class MP3Parser { private: std::vector buffer; std::map props; // Simplified to string for print public: MP3Parser(const std::string& filepath) { std::ifstream file(filepath, std::ios::binary | std::ios::ate); auto size = file.tellg(); buffer.resize(size); file.seekg(0); file.read(buffer.data(), size); parse(); } void parse() { // ID3v2 (simplified) if (std::strncmp(buffer.data(), "ID3", 3) == 0) { int tag_size = ((buffer[6] & 0x7F) << 21) | ((buffer[7] & 0x7F) << 14) | ((buffer[8] & 0x7F) << 7) | (buffer[9] & 0x7F); int offset = 10; while (offset < tag_size + 10) { char frame_id[5] = {0}; std::strncpy(frame_id, buffer.data() + offset, 4); if (!std::isalnum(frame_id[0]) || !std::isalnum(frame_id[1]) || !std::isalnum(frame_id[2]) || !std::isalnum(frame_id[3])) break; int frame_size = (buffer[offset + 4] << 24) | (buffer[offset + 5] << 16) | (buffer[offset + 6] << 8) | buffer[offset + 7]; std::string frame_data(buffer.begin() + offset + 10, buffer.begin() + offset + 10 + frame_size); frame_data.erase(std::remove(frame_data.begin(), frame_data.end(), '\0'), frame_data.end()); props["id3v2_" + std::string(frame_id)] = frame_data; offset += 10 + frame_size; } } // ID3v1 size_t end = buffer.size(); if (std::strncmp(buffer.data() + end - 128, "TAG", 3) == 0) { char temp[31] = {0}; std::strncpy(temp, buffer.data() + end - 125, 30); props["id3v1_title"] = std::string(temp); std::strncpy(temp, buffer.data() + end - 95, 30); props["id3v1_artist"] = std::string(temp); std::strncpy(temp, buffer.data() + end - 65, 30); props["id3v1_album"] = std::string(temp); std::strncpy(temp, buffer.data() + end - 35, 4); props["id3v1_year"] = std::string(temp); std::strncpy(temp, buffer.data() + end - 31, 28); props["id3v1_comment"] = std::string(temp); if (buffer[end - 3] == 0) props["id3v1_track"] = std::to_string(static_cast(buffer[end - 2])); props["id3v1_genre"] = std::to_string(static_cast(buffer[end - 1])); } // First frame header size_t header_offset = props.count("id3v2_TIT2") > 0 ? 10 + 1024 : 0; // Approximate for ID3v2 size while (header_offset < end - 4) { if (static_cast(buffer[header_offset]) == 0xFF && (static_cast(buffer[header_offset + 1]) & 0xE0) == 0xE0) break; header_offset++; } if (header_offset < end - 4) { char header[4]; std::memcpy(header, buffer.data() + header_offset, 4); int version_bits = (header[1] >> 3) & 3; props["mpeg_version"] = std::to_string(version_bits == 3 ? 1 : version_bits == 2 ? 2 : 2.5); props["layer"] = std::to_string(4 - ((header[1] >> 1) & 3)); props["protection"] = (header[1] & 1) == 0 ? "yes" : "no"; int bitrate_index = header[2] >> 4; int bitrate_table[16] = {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0}; props["bitrate"] = std::to_string(bitrate_table[bitrate_index]); int sample_index = (header[2] >> 2) & 3; int sample_table[4] = {44100, 48000, 32000, 0}; props["sampling_rate"] = std::to_string(sample_table[sample_index]); props["padding"] = std::to_string((header[2] >> 1) & 1); props["private_bit"] = std::to_string(header[2] & 1); int channel_bits = header[3] >> 6; std::string channels[4] = {"Stereo", "Joint stereo", "Dual channel", "Mono"}; props["channel_mode"] = channels[channel_bits]; props["mode_extension"] = std::to_string((header[3] >> 4) & 3); props["copyright"] = std::to_string((header[3] >> 3) & 1); props["original"] = std::to_string((header[3] >> 2) & 1); props["emphasis"] = std::to_string(header[3] & 3); // VBR Xing size_t xing_offset = header_offset + (std::stod(props["mpeg_version"]) == 1 && props["channel_mode"] != "Mono" ? 36 : 21); char xing[5] = {0}; std::strncpy(xing, buffer.data() + xing_offset, 4); if (std::strcmp(xing, "Xing") == 0 || std::strcmp(xing, "Info") == 0) { props["vbr"] = "true"; int flags = (buffer[xing_offset + 4] << 24) | (buffer[xing_offset + 5] << 16) | (buffer[xing_offset + 6] << 8) | buffer[xing_offset + 7]; props["vbr_flags"] = std::to_string(flags); int num_frames = (buffer[xing_offset + 8] << 24) | (buffer[xing_offset + 9] << 16) | (buffer[xing_offset + 10] << 8) | buffer[xing_offset + 11]; props["num_frames"] = std::to_string(num_frames); } else { props["vbr"] = "false"; } } props["file_size"] = std::to_string(buffer.size()); if (props.count("num_frames") > 0) { double duration = std::stoi(props["num_frames"]) * 1152.0 / std::stoi(props["sampling_rate"]); props["duration"] = std::to_string(duration); } else { props["duration"] = "Unknown (CBR)"; } } void printProperties() { for (const auto& pair : props) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& newFilepath, const std::map& modifications) { std::vector newBuffer = buffer; size_t end = newBuffer.size(); auto it = modifications.find("title"); if (props.count("id3v1_title") > 0 && it != modifications.end()) { std::string newTitle = it->second; newTitle.resize(30, ' '); std::memcpy(newBuffer.data() + end - 125, newTitle.c_str(), 30); } // Add more mods as needed std::ofstream out(newFilepath, std::ios::binary); out.write(newBuffer.data(), newBuffer.size()); std::cout << "Modified file saved to " << newFilepath << std::endl; } }; // Example usage: // int main() { // MP3Parser parser("example.mp3"); // parser.printProperties(); // std::map mods; // mods["title"] = "New Title"; // parser.write("modified.mp3", mods); // return 0; // } // ===== end task-414 .MP3 ===== // ===== task-415 .MP4 [C] ===== #include #include #include #include #include typedef struct { uint8_t *data; size_t size; size_t offset; char *properties[14][256]; // Key-value pairs, fixed size for simplicity char *tracks[10]; // Max 10 tracks int track_count; } MP4Parser; uint32_t read_uint32(MP4Parser *p) { uint32_t val = (p->data[p->offset] << 24) | (p->data[p->offset+1] << 16) | (p->data[p->offset+2] << 8) | p->data[p->offset+3]; p->offset += 4; return val; } uint16_t read_uint16(MP4Parser *p) { uint16_t val = (p->data[p->offset] << 8) | p->data[p->offset+1]; p->offset += 2; return val; } void read_string(MP4Parser *p, int len, char *dest) { memcpy(dest, p->data + p->offset, len); dest[len] = '\0'; p->offset += len; } void read_time(MP4Parser *p, char *dest) { time_t seconds = read_uint32(p) - 2082844800; struct tm *tm = gmtime(&seconds); strftime(dest, 256, "%Y-%m-%dT%H:%M:%SZ", tm); } void parse_box(MP4Parser *p); void parse_container(MP4Parser *p, size_t end) { while (p->offset < end) { parse_box(p); } } void parse_mvhd(MP4Parser *p) { p->offset += 4; // version + flags char ctime[256], mtime[256]; read_time(p, ctime); strcpy(p->properties[3][1], ctime); // Creation Time read_time(p, mtime); strcpy(p->properties[4][1], mtime); // Modification Time uint32_t timescale = read_uint32(p); sprintf(p->properties[5][1], "%u", timescale); // Timescale uint32_t duration = read_uint32(p); char dur_str[256]; sprintf(dur_str, "%.2f seconds", (float)duration / timescale); strcpy(p->properties[6][1], dur_str); // Duration } void parse_tkhd(MP4Parser *p, double *width, double *height) { p->offset += 4; // version + flags p->offset += 8; // creation + modification (skip times) read_uint32(p); // track_id p->offset += 4; // reserved read_uint32(p); // duration p->offset += 8 + 2 + 2 + 2 + 2 + 36; // reserved etc. *width = read_uint32(p) / 65536.0; *height = read_uint32(p) / 65536.0; } void parse_mdhd(MP4Parser *p, uint32_t *timescale) { p->offset += 4; // version + flags p->offset += 8; // creation + modification *timescale = read_uint32(p); p->offset += 4; // duration p->offset += 4; // language + pre_defined } char* parse_hdlr(MP4Parser *p) { p->offset += 4; // version + flags p->offset += 4; // pre_defined char *handler = malloc(5); read_string(p, 4, handler); p->offset += 12; // reserved return handler; } void parse_stsd(MP4Parser *p, char *codec, int *channels, uint32_t *sample_rate, double *width, double *height) { p->offset += 4; // version + flags uint32_t entry_count = read_uint32(p); if (entry_count > 0) { read_uint32(p); // sample_size read_string(p, 4, codec); p->offset += 6; // reserved + data_ref_index if (strcmp(codec, "avc1") == 0 || strcmp(codec, "mp4v") == 0) { p->offset += 8; // pre_defined + reserved *width = read_uint16(p); *height = read_uint16(p); } else if (strcmp(codec, "mp4a") == 0) { p->offset += 8; // reserved + data_ref_index + pre_defined *channels = read_uint16(p); p->offset += 2; // sample size p->offset += 4; // pre_defined + reserved *sample_rate = read_uint32(p) >> 16; } } } void parse_trak(MP4Parser *p) { size_t start = p->offset; double tk_width = 0, tk_height = 0; parse_tkhd(p, &tk_width, &tk_height); char *handler_type = ""; char codec[5] = ""; int channels = 0; uint32_t sample_rate = 0; double st_width = 0, st_height = 0; uint32_t md_timescale = 0; while (p->offset < p->size) { // Approximate loop uint32_t size = read_uint32(p); char type[5]; read_string(p, 4, type); if (strcmp(type, "mdia") == 0) { parse_container(p, p->offset + size - 8); } else if (strcmp(type, "mdhd") == 0) { parse_mdhd(p, &md_timescale); } else if (strcmp(type, "hdlr") == 0) { handler_type = parse_hdlr(p); } else if (strcmp(type, "stbl") == 0) { parse_container(p, p->offset + size - 8); } else if (strcmp(type, "stsd") == 0) { parse_stsd(p, codec, &channels, &sample_rate, &st_width, &st_height); } else { p->offset += size - 8; } if (p->offset >= start + 10000) break; // Safety } if (strcmp(handler_type, "vide") == 0) { strcpy(p->properties[8][1], codec[0] ? codec : "Unknown"); // Video Codec char w_str[256], h_str[256]; sprintf(w_str, "%.0f", tk_width ? tk_width : st_width); strcpy(p->properties[9][1], w_str); // Video Width sprintf(h_str, "%.0f", tk_height ? tk_height : st_height); strcpy(p->properties[10][1], h_str); // Video Height } else if (strcmp(handler_type, "soun") == 0) { strcpy(p->properties[11][1], codec[0] ? codec : "Unknown"); // Audio Codec char ch_str[256], sr_str[256]; sprintf(ch_str, "%d", channels); strcpy(p->properties[12][1], ch_str); // Audio Channels sprintf(sr_str, "%u", md_timescale ? md_timescale : sample_rate); strcpy(p->properties[13][1], sr_str); // Audio Sample Rate } p->tracks[p->track_count++] = handler_type; } void parse_box(MP4Parser *p) { size_t start = p->offset; uint32_t size = read_uint32(p); char type[5]; read_string(p, 4, type); size_t end = start + size; if (strcmp(type, "ftyp") == 0) { char major[5]; read_string(p, 4, major); strcpy(p->properties[0][1], major); // Major Brand uint32_t minor = read_uint32(p); char min_str[256]; sprintf(min_str, "%u", minor); strcpy(p->properties[1][1], min_str); // Minor Version char compat[1024] = ""; while (p->offset < end) { char brand[5]; read_string(p, 4, brand); strcat(compat, brand); strcat(compat, " "); } strcpy(p->properties[2][1], compat); // Compatible Brands } else if (strcmp(type, "moov") == 0) { parse_container(p, end); } else if (strcmp(type, "mvhd") == 0) { parse_mvhd(p); } else if (strcmp(type, "trak") == 0) { parse_trak(p); } p->offset = end; } void init_properties(MP4Parser *p) { const char *keys[] = {"Major Brand", "Minor Version", "Compatible Brands", "Creation Time", "Modification Time", "Timescale", "Duration", "Number of Tracks", "Video Codec", "Video Width", "Video Height", "Audio Codec", "Audio Channels", "Audio Sample Rate"}; for (int i = 0; i < 14; i++) { p->properties[i][0] = malloc(256); strcpy(p->properties[i][0], keys[i]); p->properties[i][1] = malloc(256); strcpy(p->properties[i][1], "Unknown"); } } void parse(MP4Parser *p) { init_properties(p); while (p->offset < p->size) { parse_box(p); } char tc_str[256]; sprintf(tc_str, "%d", p->track_count); strcpy(p->properties[7][1], tc_str); // Number of Tracks } void print_properties(MP4Parser *p) { for (int i = 0; i < 14; i++) { printf("%s: %s\n", p->properties[i][0], p->properties[i][1]); } } void write(MP4Parser *p, const char *output_path) { FILE *f = fopen(output_path, "wb"); if (f) { fwrite(p->data, 1, p->size, f); fclose(f); } } void init_mp4parser(MP4Parser *p, const char *file_path) { FILE *f = fopen(file_path, "rb"); if (f) { fseek(f, 0, SEEK_END); p->size = ftell(f); fseek(f, 0, SEEK_SET); p->data = malloc(p->size); fread(p->data, 1, p->size, f); fclose(f); } p->offset = 0; p->track_count = 0; parse(p); } void free_mp4parser(MP4Parser *p) { free(p->data); for (int i = 0; i < 14; i++) { free(p->properties[i][0]); free(p->properties[i][1]); } for (int i = 0; i < p->track_count; i++) { free(p->tracks[i]); } } // Example usage: // int main() { // MP4Parser parser; // init_mp4parser(&parser, "example.mp4"); // print_properties(&parser); // write(&parser, "output.mp4"); // free_mp4parser(&parser); // return 0; // } // ===== end task-415 .MP4 ===== // ===== task-416 .MPA [C] ===== #include #include #include #include typedef struct { char* filepath; uint8_t* data; size_t size; int properties[12]; } MPAParsing; MPAParsing* mpa_create(const char* filepath) { MPAParsing* parser = malloc(sizeof(MPAParsing)); parser->filepath = strdup(filepath); parser->data = NULL; parser->size = 0; memset(parser->properties, 0, sizeof(parser->properties)); return parser; } void mpa_decode_read(MPAParsing* parser) { FILE* f = fopen(parser->filepath, "rb"); if (!f) return; fseek(f, 0, SEEK_END); parser->size = ftell(f); fseek(f, 0, SEEK_SET); parser->data = malloc(parser->size); fread(parser->data, 1, parser->size, f); fclose(f); size_t offset = 0; while (offset < parser->size - 4) { if (parser->data[offset] == 0xFF && (parser->data[offset + 1] & 0xE0) == 0xE0) { break; } offset++; } if (offset >= parser->size - 4) { printf("No valid MPA frame found.\n"); return; } uint32_t header = (parser->data[offset] << 24) | (parser->data[offset + 1] << 16) | (parser->data[offset + 2] << 8) | parser->data[offset + 3]; parser->properties[0] = (header >> 19) & 3; parser->properties[1] = (header >> 17) & 3; parser->properties[2] = (header >> 16) & 1; parser->properties[3] = (header >> 12) & 15; parser->properties[4] = (header >> 10) & 3; parser->properties[5] = (header >> 9) & 1; parser->properties[6] = (header >> 8) & 1; parser->properties[7] = (header >> 6) & 3; parser->properties[8] = (header >> 4) & 3; parser->properties[9] = (header >> 3) & 1; parser->properties[10] = (header >> 2) & 1; parser->properties[11] = header & 3; } void mpa_print_properties(MPAParsing* parser) { const char* keys[12] = {"Version index", "Layer index", "Protection bit", "Bitrate index", "Sampling rate index", "Padding bit", "Private bit", "Channel mode index", "Mode extension", "Copyright bit", "Original bit", "Emphasis"}; for (int i = 0; i < 12; i++) { printf("%s: %d\n", keys[i], parser->properties[i]); } } void mpa_write(MPAParsing* parser, const char* new_filepath) { if (!parser->data) { // Create dummy uint32_t version = 3; uint32_t layer = 2; uint32_t crc = 1; uint32_t bitrate_index = 10; uint32_t sampling_index = 0; uint32_t padding = 0; uint32_t private_bit = 0; uint32_t channel = 0; uint32_t mode_ext = 0; uint32_t copyright = 0; uint32_t original = 1; uint32_t emphasis = 0; uint32_t header = (0xFFF << 21) | (version << 19) | (layer << 17) | (crc << 16) | (bitrate_index << 12) | (sampling_index << 10) | (padding << 9) | (private_bit << 8) | (channel << 6) | (mode_ext << 4) | (copyright << 3) | (original << 2) | emphasis; uint32_t bitrate = 192000; uint32_t sampling = 44100; uint32_t frame_size = (144 * bitrate / sampling) + padding; parser->data = calloc(frame_size, 1); parser->data[0] = (header >> 24) & 0xFF; parser->data[1] = (header >> 16) & 0xFF; parser->data[2] = (header >> 8) & 0xFF; parser->data[3] = header & 0xFF; parser->size = frame_size; } FILE* f = fopen(new_filepath, "wb"); if (f) { fwrite(parser->data, 1, parser->size, f); fclose(f); } } void mpa_destroy(MPAParsing* parser) { free(parser->filepath); free(parser->data); free(parser); } // Example usage: // int main() { // MPAParsing* parser = mpa_create("example.mpa"); // mpa_decode_read(parser); // mpa_print_properties(parser); // mpa_write(parser, "new.mpa"); // mpa_destroy(parser); // return 0; // } // ===== end task-416 .MPA ===== // ===== task-417 .MPC [C++] ===== #include #include #include #include #include #include using namespace std; class MPCFile { private: string filename; map> properties; vector> packets; pair readVarint(ifstream& file) { long value = 0; int byte; while (true) { file.read((char*)&byte, 1); value = (value << 7) | (byte & 0x7F); if ((byte & 0x80) == 0) break; } return {value, file.tellg()}; } public: MPCFile(const string& fn) : filename(fn) { parse(); } void parse() { ifstream file(filename, ios::binary); char magic[4]; file.read(magic, 4); if (string(magic, 4) != "MPCK") { cerr << "Invalid MPC file" << endl; return; } properties["Magic Number"]["Value"] = "MPCK"; while (!file.eof()) { char keyBuf[2]; file.read(keyBuf, 2); string key(keyBuf, 2); auto sizeRes = readVarint(file); long size = sizeRes.first; streampos pos = file.tellg(); map packetProps; packetProps["Key"] = key; packetProps["Size"] = to_string(size); if (key == "SH") { unsigned int crc; file.read((char*)&crc, 4); char version; file.read(&version, 1); auto sampleCountRes = readVarint(file); file.seekg(sampleCountRes.second); auto beginSilenceRes = readVarint(file); file.seekg(beginSilenceRes.second); char freqBits; file.read(&freqBits, 1); int freq = (freqBits >> 5) & 0x07; int maxBands = freqBits & 0x1F; char chanBits; file.read(&chanBits, 1); int channels = (chanBits >> 4) & 0x0F; int msUsed = (chanBits >> 3) & 0x01; int blockFrames = chanBits & 0x07; packetProps["CRC"] = to_string(crc); packetProps["Stream Version"] = to_string((int)version); packetProps["Sample Count"] = to_string(sampleCountRes.first); packetProps["Beginning Silence"] = to_string(beginSilenceRes.first); packetProps["Sample Frequency"] = to_string(freq); packetProps["Max Used Bands"] = to_string(maxBands); packetProps["Channel Count"] = to_string(channels); packetProps["MS Used"] = to_string(msUsed); packetProps["Audio Block Frames"] = to_string(blockFrames); } // Add for other properties[key] = packetProps; int sizeLength = ceil(log2(size + 1) / 7.0); streampos packetStart = pos - 2 - sizeLength; file.seekg(pos); vector packetData(size); file.read(packetData.data(), size); packets.push_back(packetData); file.seekg(pos + size - 2 - sizeLength + pos - pos); // Adjust long endPos = pos + size - 2 - sizeLength; file.seekg(endPos); } file.close(); } void printProperties() { for (const auto& p : properties) { cout << "Packet " << p.first << ":" << endl; for (const auto& prop : p.second) { cout << " " << prop.first << ": " << prop.second << endl; } } } void write(const string& newFilename) { ofstream out(newFilename, ios::binary); out.write("MPCK", 4); for (const auto& packet : packets) { out.write(packet.data(), packet.size()); } out.close(); } }; int main(int argc, char** argv) { if (argc > 1) { MPCFile mpc(argv[1]); mpc.printProperties(); mpc.write("output.mpc"); } return 0; } // ===== end task-417 .MPC ===== // ===== task-418 .MPD [C++] ===== #include #include #include // Assume TinyXML2 library #include class MPDHandler { private: std::string filepath; tinyxml2::XMLDocument doc; void extractProperties(const tinyxml2::XMLElement* node, std::string indent = "") { if (!node) return; std::cout << indent << "{" << std::endl; std::cout << indent << " \"tag\": \"" << node->Name() << "\"," << std::endl; std::cout << indent << " \"attributes\": {" << std::endl; const tinyxml2::XMLAttribute* attr = node->FirstAttribute(); while (attr) { std::cout << indent << " \"" << attr->Name() << "\": \"" << attr->Value() << "\"," << std::endl; attr = attr->Next(); } std::cout << indent << " }," << std::endl; std::cout << indent << " \"children\": [" << std::endl; const tinyxml2::XMLElement* child = node->FirstChildElement(); while (child) { extractProperties(child, indent + " "); child = child->NextSiblingElement(); } std::cout << indent << " ]" << std::endl; std::cout << indent << "}" << std::endl; } public: MPDHandler(const std::string& fp) : filepath(fp) {} void openAndDecode() { doc.LoadFile(filepath.c_str()); if (doc.Error()) { throw std::runtime_error("Error loading XML."); } } void printProperties() { const tinyxml2::XMLElement* root = doc.RootElement(); if (!root) throw std::runtime_error("No root element."); extractProperties(root); } void write(const std::string& newFilepath = "") { const std::string path = newFilepath.empty() ? filepath : newFilepath; doc.SaveFile(path.c_str()); } // Example modification: update attribute by tag path (simple first-match) void updateProperty(const std::string& tagPath, const std::string& attrName, const std::string& attrValue) { tinyxml2::XMLElement* current = doc.RootElement(); size_t pos = 0, next; std::string token; std::string path = tagPath; if (path.find("MPD/") == 0) path = path.substr(4); // Skip root if starts with MPD/ while ((next = path.find('/', pos)) != std::string::npos) { token = path.substr(pos, next - pos); current = current->FirstChildElement(token.c_str()); if (!current) throw std::runtime_error("Path not found."); pos = next + 1; } token = path.substr(pos); if (!token.empty()) { current = current->FirstChildElement(token.c_str()); if (!current) throw std::runtime_error("Path not found."); } current->SetAttribute(attrName.c_str(), attrValue.c_str()); } }; // Usage example: // int main() { // try { // MPDHandler handler("example.mpd"); // handler.openAndDecode(); // handler.printProperties(); // handler.updateProperty("Period", "id", "newId"); // handler.write("modified.mpd"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-418 .MPD ===== // ===== task-420 .MPG [C++] ===== #include #include #include #include #include #include class MpgHandler { private: std::vector data; std::map properties; public: void read(const std::string& filepath) { std::ifstream file(filepath, std::ios::binary); if (file) { data = std::vector((std::istreambuf_iterator(file)), std::istreambuf_iterator()); decode(); } } void decode() { if (data.empty()) return; size_t pos = 0; // Pack Header uint32_t packStart; memcpy(&packStart, &data[pos], 4); char hexBuf[9]; snprintf(hexBuf, sizeof(hexBuf), "0x%08X", __builtin_bswap32(packStart)); // Big-endian properties["Pack Start Code"] = hexBuf; pos += 4; uint8_t byte = data[pos]; int versionMarker = (byte >> 4) & 0x0F; properties["Version Marker"] = (versionMarker == 2) ? "MPEG-1" : "Unknown"; uint64_t scr = ((byte & 0x0E) >> 1) << 30; pos++; uint16_t shortVal; memcpy(&shortVal, &data[pos], 2); shortVal = __builtin_bswap16(shortVal); scr += ((shortVal & 0xFFFE) >> 1) << 15; pos += 2; memcpy(&shortVal, &data[pos], 2); shortVal = __builtin_bswap16(shortVal); scr += (shortVal & 0xFFFE) >> 1; pos += 2; properties["SCR"] = std::to_string(scr); uint8_t muxHigh = data[pos-1] & 0x01; memcpy(&shortVal, &data[pos], 2); shortVal = __builtin_bswap16(shortVal); uint32_t muxRate = (muxHigh << 22) | (shortVal >> 2); properties["Mux Rate"] = std::to_string(muxRate * 50); pos += 2; int stuffingLength = data[pos] & 0x07; properties["Stuffing Length"] = std::to_string(stuffingLength); pos += 1 + stuffingLength; // System Header uint32_t sysStart; memcpy(&sysStart, &data[pos], 4); if (__builtin_bswap32(sysStart) == 0x000001BB) { properties["System Header Start Code"] = "0x000001BB"; pos += 4; memcpy(&shortVal, &data[pos], 2); shortVal = __builtin_bswap16(shortVal); properties["System Header Length"] = std::to_string(shortVal); int headerLength = shortVal; pos += 2; uint32_t intVal; memcpy(&intVal, &data[pos-1], 4); // Offset for alignment intVal = __builtin_bswap32(intVal); uint32_t rateBound = (intVal >> 9) & 0x3FFFFF; properties["Rate Bound"] = std::to_string(rateBound); pos += 3; int audioBound = data[pos] >> 2; properties["Audio Bound"] = std::to_string(audioBound); int fixedFlag = (data[pos] >> 1) & 1; properties["Fixed Flag"] = std::to_string(fixedFlag); int cspsFlag = data[pos] & 1; properties["CSPS Flag"] = std::to_string(cspsFlag); pos++; int audioLock = data[pos] >> 7 & 1; properties["System Audio Lock Flag"] = std::to_string(audioLock); int videoLock = data[pos] >> 6 & 1; properties["System Video Lock Flag"] = std::to_string(videoLock); int videoBound = data[pos] & 0x1F; properties["Video Bound"] = std::to_string(videoBound); pos++; int packetRateRestriction = data[pos] >> 7 & 1; properties["Packet Rate Restriction Flag"] = std::to_string(packetRateRestriction); pos += headerLength - 6; } // First PES Packet memcpy(&intVal, &data[pos], 4); intVal = __builtin_bswap32(intVal); if ((intVal >> 8) == 0x000001) { uint8_t streamId = data[pos + 3]; snprintf(hexBuf, sizeof(hexBuf), "0x%02X", streamId); properties["PES Stream ID"] = hexBuf; pos += 4; memcpy(&shortVal, &data[pos], 2); shortVal = __builtin_bswap16(shortVal); properties["PES Packet Length"] = std::to_string(shortVal); pos += 2; uint8_t pesFlags = data[pos]; if ((pesFlags >> 6) == 2) { pos++; int ptsDtsIndicator = (data[pos] >> 4) & 3; properties["PTS/DTS Indicator"] = std::to_string(ptsDtsIndicator); // ... (add more) } } } void printProperties() const { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& filepath) const { if (!data.empty()) { std::ofstream file(filepath, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); } } }; // Usage example: // int main() { // MpgHandler handler; // handler.read("example.mpg"); // handler.printProperties(); // handler.write("output.mpg"); // return 0; // } // ===== end task-420 .MPG ===== // ===== task-421 .MPS [C++] ===== #include #include #include #include #include #include #include #include struct Row { std::string name; std::string type; }; struct Coefficient { std::string var; std::string row; double value; }; struct RHS { std::string row; double value; }; struct Bound { std::string type; std::string var; double value; // Use NAN for null }; class MPSHandler { public: std::string name; std::vector rows; std::set variables_set; std::vector variables; std::vector coefficients; std::vector rhs; std::vector bounds; void read(const std::string& filepath) { std::ifstream file(filepath); if (!file.is_open()) { throw std::runtime_error("File not found"); } std::string line; std::string section = ""; std::string current_rhs_name = ""; std::string current_bound_name = ""; while (std::getline(file, line)) { // Trim trailing spaces line.erase(line.find_last_not_of(" \n\r\t") + 1); if (line.empty() || line[0] == '*') continue; if (line == "ENDATA") break; std::istringstream iss(line); std::string first; iss >> first; if (first == "NAME" || first == "ROWS" || first == "COLUMNS" || first == "RHS" || first == "BOUNDS") { section = first; if (section == "NAME") { name = line.substr(14); // Trim name name.erase(0, name.find_first_not_of(" \t")); name.erase(name.find_last_not_of(" \t") + 1); } continue; } if (section == "ROWS") { std::string row_type = line.substr(1, 2); row_type.erase(row_type.find_last_not_of(" \t") + 1); std::string row_name = line.substr(4, 8); row_name.erase(row_name.find_last_not_of(" \t") + 1); if (!row_type.empty() && !row_name.empty()) { rows.push_back({row_name, row_type}); } } else if (section == "COLUMNS") { std::string var_name = line.substr(4, 8); var_name.erase(var_name.find_last_not_of(" \t") + 1); std::string row1 = line.substr(14, 8); row1.erase(row1.find_last_not_of(" \t") + 1); double val1; std::string val1_str = line.substr(24, 12); std::istringstream(val1_str) >> val1; std::string row2 = ""; double val2 = 0.0; if (line.length() >= 49) { row2 = line.substr(39, 8); row2.erase(row2.find_last_not_of(" \t") + 1); std::string val2_str = line.substr(49, 12); std::istringstream(val2_str) >> val2; } if (!var_name.empty()) variables_set.insert(var_name); if (!row1.empty() && !std::isnan(val1)) { coefficients.push_back({var_name, row1, val1}); } if (!row2.empty() && !std::isnan(val2)) { coefficients.push_back({var_name, row2, val2}); } } else if (section == "RHS") { current_rhs_name = line.substr(4, 8); current_rhs_name.erase(current_rhs_name.find_last_not_of(" \t") + 1); std::string row1 = line.substr(14, 8); row1.erase(row1.find_last_not_of(" \t") + 1); double val1; std::string val1_str = line.substr(24, 12); std::istringstream(val1_str) >> val1; std::string row2 = ""; double val2 = 0.0; if (line.length() >= 49) { row2 = line.substr(39, 8); row2.erase(row2.find_last_not_of(" \t") + 1); std::string val2_str = line.substr(49, 12); std::istringstream(val2_str) >> val2; } if (!row1.empty() && !std::isnan(val1)) { rhs.push_back({row1, val1}); } if (!row2.empty() && !std::isnan(val2)) { rhs.push_back({row2, val2}); } } else if (section == "BOUNDS") { std::string bound_type = line.substr(1, 2); bound_type.erase(bound_type.find_last_not_of(" \t") + 1); current_bound_name = line.substr(4, 8); current_bound_name.erase(current_bound_name.find_last_not_of(" \t") + 1); std::string var_name = line.substr(14, 8); var_name.erase(var_name.find_last_not_of(" \t") + 1); double value; std::string value_str = line.substr(24, 12); std::istringstream(value_str) >> value; if (!bound_type.empty() && !var_name.empty()) { bounds.push_back({bound_type, var_name, std::isnan(value) ? NAN : value}); } } } variables.assign(variables_set.begin(), variables_set.end()); file.close(); } void printProperties() { std::cout << "Problem Name: " << name << std::endl; std::cout << "Rows:" << std::endl; for (const auto& r : rows) { std::cout << " " << r.type << " " << r.name << std::endl; } std::cout << "Variables: "; for (size_t i = 0; i < variables.size(); ++i) { std::cout << variables[i]; if (i < variables.size() - 1) std::cout << ", "; } std::cout << std::endl; std::cout << "Coefficients:" << std::endl; for (const auto& c : coefficients) { std::cout << " " << c.var << " in " << c.row << ": " << c.value << std::endl; } std::cout << "RHS:" << std::endl; for (const auto& rh : rhs) { std::cout << " " << rh.row << ": " << rh.value << std::endl; } std::cout << "Bounds:" << std::endl; for (const auto& b : bounds) { std::cout << " " << b.type << " " << b.var << ": "; if (std::isnan(b.value)) std::cout << "null"; else std::cout << b.value; std::cout << std::endl; } } void write(const std::string& filepath) { std::ofstream file(filepath); if (!file.is_open()) { throw std::runtime_error("Cannot open file for writing"); } if (!name.empty()) { file << "NAME " << name << "\n"; } file << "ROWS\n"; for (const auto& r : rows) { file << " " << r.type << " " << std::left << std::setw(8) << r.name << "\n"; } file << "COLUMNS\n"; std::map>> var_coeffs; for (const auto& c : coefficients) { var_coeffs[c.var].emplace_back(c.row, c.value); } for (const auto& [var, coeffs] : var_coeffs) { for (size_t i = 0; i < coeffs.size(); i += 2) { file << " " << std::left << std::setw(8) << var; file << " " << std::left << std::setw(8) << coeffs[i].first << " " << std::scientific << std::setprecision(5) << std::setw(12) << coeffs[i].second; if (i + 1 < coeffs.size()) { file << " " << std::left << std::setw(8) << coeffs[i + 1].first << " " << std::scientific << std::setprecision(5) << std::setw(12) << coeffs[i + 1].second; } file << "\n"; } } file << "RHS\n"; for (size_t i = 0; i < rhs.size(); i += 2) { file << " RHS1 " << std::left << std::setw(8) << rhs[i].row << " " << std::scientific << std::setprecision(5) << std::setw(12) << rhs[i].value; if (i + 1 < rhs.size()) { file << " " << std::left << std::setw(8) << rhs[i + 1].row << " " << std::scientific << std::setprecision(5) << std::setw(12) << rhs[i + 1].value; } file << "\n"; } if (!bounds.empty()) { file << "BOUNDS\n"; for (const auto& b : bounds) { file << " " << b.type << " BND1 " << std::left << std::setw(8) << b.var; if (!std::isnan(b.value)) { file << " " << std::scientific << std::setprecision(5) << std::setw(12) << b.value; } file << "\n"; } } file << "ENDATA\n"; file.close(); } }; // Example usage: // int main() { // MPSHandler handler; // try { // handler.read("example.mps"); // handler.printProperties(); // handler.write("output.mps"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-421 .MPS ===== // ===== task-422 .MR [C] ===== #include #include #include typedef struct { char* chromosome; int start; char* strand; char* sequence; char* quality; char* converted_sequence; int is_null; } MRRead; typedef struct { char* filename; char mode; MRRead* reads; size_t count; } MRFile; MRFile* mr_open(const char* filename, char mode) { MRFile* mr = malloc(sizeof(MRFile)); mr->filename = strdup(filename); mr->mode = mode; mr->reads = NULL; mr->count = 0; if (mode == 'r') { FILE* fp = fopen(filename, "r"); if (fp) { char line[1024]; while (fgets(line, sizeof(line), fp)) { line[strcspn(line, "\n")] = 0; if (strcmp(line, "NULL") == 0) { mr->reads = realloc(mr->reads, sizeof(MRRead) * (mr->count + 1)); mr->reads[mr->count].is_null = 1; mr->count++; } else if (strlen(line) > 0) { char* fields[6]; int fcount = 0; char* token = strtok(line, "\t"); while (token && fcount < 6) { fields[fcount++] = token; token = strtok(NULL, "\t"); } if (fcount == 6) { mr->reads = realloc(mr->reads, sizeof(MRRead) * (mr->count + 1)); MRRead* read = &mr->reads[mr->count]; read->is_null = 0; read->chromosome = strdup(fields[0]); read->start = atoi(fields[1]); read->strand = strdup(fields[2]); read->sequence = strdup(fields[3]); read->quality = strdup(fields[4]); read->converted_sequence = strdup(fields[5]); mr->count++; } else { printf("Invalid line: %s\n", line); } } } fclose(fp); } } return mr; } void mr_print_properties(MRFile* mr) { for (size_t i = 0; i < mr->count; i++) { printf("Read %zu:\n", i + 1); MRRead read = mr->reads[i]; if (read.is_null) { printf("NULL (Invalid Entry)\n"); } else { printf(" Chromosome: %s\n", read.chromosome); printf(" Start Position: %d\n", read.start); printf(" Strand: %s\n", read.strand); printf(" Sequence: %s\n", read.sequence); printf(" Quality Scores: %s\n", read.quality); printf(" Converted Sequence: %s\n", read.converted_sequence); } printf("---\n"); } } void mr_add_read(MRFile* mr, const char* chromosome, int start, const char* strand, const char* sequence, const char* quality, const char* converted_sequence) { if (mr->mode != 'w') { fprintf(stderr, "File not opened in write mode\n"); return; } mr->reads = realloc(mr->reads, sizeof(MRRead) * (mr->count + 1)); MRRead* read = &mr->reads[mr->count]; read->is_null = 0; read->chromosome = strdup(chromosome); read->start = start; read->strand = strdup(strand); read->sequence = strdup(sequence); read->quality = strdup(quality); read->converted_sequence = strdup(converted_sequence); mr->count++; } void mr_write(MRFile* mr) { if (mr->mode != 'w') { fprintf(stderr, "File not opened in write mode\n"); return; } FILE* fp = fopen(mr->filename, "w"); if (fp) { for (size_t i = 0; i < mr->count; i++) { MRRead read = mr->reads[i]; if (read.is_null) { fprintf(fp, "NULL\n"); } else { fprintf(fp, "%s\t%d\t%s\t%s\t%s\t%s\n", read.chromosome, read.start, read.strand, read.sequence, read.quality, read.converted_sequence); } } fclose(fp); } } void mr_close(MRFile* mr) { for (size_t i = 0; i < mr->count; i++) { if (!mr->reads[i].is_null) { free(mr->reads[i].chromosome); free(mr->reads[i].strand); free(mr->reads[i].sequence); free(mr->reads[i].quality); free(mr->reads[i].converted_sequence); } } free(mr->reads); free(mr->filename); free(mr); } // Example usage: // int main() { // MRFile* reader = mr_open("sample.mr", 'r'); // mr_print_properties(reader); // mr_close(reader); // MRFile* writer = mr_open("new.mr", 'w'); // mr_add_read(writer, "chr1", 100, "+", "ATCG", "HHHH", "ATTG"); // mr_write(writer); // mr_close(writer); // return 0; // } // ===== end task-422 .MR ===== // ===== task-424 .MSAV [C] ===== #include #include #include #include #include typedef struct { char *filename; char magic[5]; int16_t version; struct Tag { char *key; char *val; } *tags; size_t tagCount; int16_t width; int16_t height; uint8_t *floorData; size_t floorSize; uint8_t *oreData; size_t oreSize; uint8_t *blockData; size_t blockSize; int32_t entityCount; uint8_t *rawFloor; size_t rawFloorSize; uint8_t *rawOre; size_t rawOreSize; uint8_t *rawBlock; size_t rawBlockSize; uint8_t *rawEntities; size_t rawEntitiesSize; } MSAVHandler; MSAVHandler* msav_create(const char *filename) { MSAVHandler *h = calloc(1, sizeof(MSAVHandler)); h->filename = strdup(filename); return h; } void msav_destroy(MSAVHandler *h) { for (size_t i = 0; i < h->tagCount; i++) { free(h->tags[i].key); free(h->tags[i].val); } free(h->tags); free(h->floorData); free(h->oreData); free(h->blockData); free(h->rawFloor); free(h->rawOre); free(h->rawBlock); free(h->rawEntities); free(h->filename); free(h); } int msav_read(MSAVHandler *h) { FILE *f = fopen(h->filename, "rb"); if (!f) return 1; fseek(f, 0, SEEK_END); size_t fileSize = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(fileSize); fread(data, 1, fileSize, f); fclose(f); size_t offset = 0; memcpy(h->magic, data + offset, 4); h->magic[4] = '\0'; offset += 4; memcpy(&h->version, data + offset, 2); h->version = __builtin_bswap16(h->version); // Assume big-endian offset += 2; int32_t tagCount32; memcpy(&tagCount32, data + offset, 4); tagCount32 = __builtin_bswap32(tagCount32); h->tagCount = tagCount32; offset += 4; h->tags = malloc(h->tagCount * sizeof(struct Tag)); for (size_t i = 0; i < h->tagCount; i++) { uint16_t keyLen; memcpy(&keyLen, data + offset, 2); keyLen = __builtin_bswap16(keyLen); offset += 2; h->tags[i].key = malloc(keyLen + 1); memcpy(h->tags[i].key, data + offset, keyLen); h->tags[i].key[keyLen] = '\0'; offset += keyLen; uint16_t valLen; memcpy(&valLen, data + offset, 2); valLen = __builtin_bswap16(valLen); offset += 2; h->tags[i].val = malloc(valLen + 1); memcpy(h->tags[i].val, data + offset, valLen); h->tags[i].val[valLen] = '\0'; offset += valLen; } memcpy(&h->width, data + offset, 2); h->width = __builtin_bswap16(h->width); offset += 2; memcpy(&h->height, data + offset, 2); h->height = __builtin_bswap16(h->height); offset += 2; int32_t floorLen; memcpy(&floorLen, data + offset, 4); floorLen = __builtin_bswap32(floorLen); offset += 4; h->rawFloor = malloc(floorLen); memcpy(h->rawFloor, data + offset, floorLen); h->rawFloorSize = floorLen; offset += floorLen; uLongf destLen = h->width * h->height; h->floorData = malloc(destLen); if (uncompress(h->floorData, &destLen, h->rawFloor, floorLen) != Z_OK) return 2; h->floorSize = destLen; int32_t oreLen; memcpy(&oreLen, data + offset, 4); oreLen = __builtin_bswap32(oreLen); offset += 4; h->rawOre = malloc(oreLen); memcpy(h->rawOre, data + offset, oreLen); h->rawOreSize = oreLen; offset += oreLen; destLen = h->width * h->height; h->oreData = malloc(destLen); if (uncompress(h->oreData, &destLen, h->rawOre, oreLen) != Z_OK) return 2; h->oreSize = destLen; int32_t blockLen; memcpy(&blockLen, data + offset, 4); blockLen = __builtin_bswap32(blockLen); offset += 4; h->rawBlock = malloc(blockLen); memcpy(h->rawBlock, data + offset, blockLen); h->rawBlockSize = blockLen; offset += blockLen; destLen = fileSize - offset + 4; // Approximate h->blockData = malloc(destLen); if (uncompress(h->blockData, &destLen, h->rawBlock, blockLen) != Z_OK) return 2; h->blockSize = destLen; memcpy(&h->entityCount, data + offset, 4); h->entityCount = __builtin_bswap32(h->entityCount); offset += 4; h->rawEntitiesSize = fileSize - offset; h->rawEntities = malloc(h->rawEntitiesSize); memcpy(h->rawEntities, data + offset, h->rawEntitiesSize); free(data); return 0; } void msav_print_properties(MSAVHandler *h) { printf("Magic: %s\n", h->magic); printf("Version: %d\n", h->version); printf("Tags:\n"); for (size_t i = 0; i < h->tagCount; i++) { printf(" %s: %s\n", h->tags[i].key, h->tags[i].val); } printf("Width: %d\n", h->width); printf("Height: %d\n", h->height); printf("Floor Layer: %zu bytes decompressed\n", h->floorSize); printf("Ore Layer: %zu bytes decompressed\n", h->oreSize); printf("Block Layer: %zu bytes decompressed\n", h->blockSize); printf("Entities: %d\n", h->entityCount); } int msav_write(MSAVHandler *h, const char *newFilename) { if (!newFilename) newFilename = h->filename; FILE *f = fopen(newFilename, "wb"); if (!f) return 1; fwrite(h->magic, 1, 4, f); int16_t ver = __builtin_bswap16(h->version); fwrite(&ver, 2, 1, f); int32_t tc = __builtin_bswap32(h->tagCount); fwrite(&tc, 4, 1, f); for (size_t i = 0; i < h->tagCount; i++) { uint16_t kl = __builtin_bswap16(strlen(h->tags[i].key)); fwrite(&kl, 2, 1, f); fwrite(h->tags[i].key, 1, strlen(h->tags[i].key), f); uint16_t vl = __builtin_bswap16(strlen(h->tags[i].val)); fwrite(&vl, 2, 1, f); fwrite(h->tags[i].val, 1, strlen(h->tags[i].val), f); } int16_t w = __builtin_bswap16(h->width); fwrite(&w, 2, 1, f); int16_t ht = __builtin_bswap16(h->height); fwrite(&ht, 2, 1, f); int32_t fl = __builtin_bswap32(h->rawFloorSize); fwrite(&fl, 4, 1, f); fwrite(h->rawFloor, 1, h->rawFloorSize, f); int32_t ol = __builtin_bswap32(h->rawOreSize); fwrite(&ol, 4, 1, f); fwrite(h->rawOre, 1, h->rawOreSize, f); int32_t bl = __builtin_bswap32(h->rawBlockSize); fwrite(&bl, 4, 1, f); fwrite(h->rawBlock, 1, h->rawBlockSize, f); int32_t ec = __builtin_bswap32(h->entityCount); fwrite(&ec, 4, 1, f); fwrite(h->rawEntities, 1, h->rawEntitiesSize, f); fclose(f); return 0; } // Example usage // int main() { // MSAVHandler *h = msav_create("example.msav"); // if (msav_read(h) == 0) { // msav_print_properties(h); // msav_write(h, "output.msav"); // } // msav_destroy(h); // return 0; // } // ===== end task-424 .MSAV ===== // ===== task-425 .MSC [C++] ===== #include #include #include #include #include #include #include #include // Assume json library for printing, or replace with custom using json = nlohmann::json; class MSCParser { private: std::map globalOptions; std::vector> entities; // Simplified, name in map as "name" std::vector> arcs; // from, type, to as strings in map std::set colors; std::vector comments; public: void read(const std::string& filepath) { std::ifstream file(filepath); std::stringstream content; content << file.rdbuf(); parse(content.str()); } void parse(const std::string& content) { // Global options std::regex optionsRegex("msc\\s*\\{\\s*([^}]*)\\;", std::regex::icase); std::smatch optionsMatch; if (std::regex_search(content, optionsMatch, optionsRegex)) { std::string optionsStr = optionsMatch[1].str(); std::regex optRegex("([^,]+)"); std::sregex_iterator optIter(optionsStr.begin(), optionsStr.end(), optRegex); for (; optIter != std::sregex_iterator(); ++optIter) { std::string opt = optIter->str(); size_t eqPos = opt.find('='); if (eqPos != std::string::npos) { std::string key = opt.substr(0, eqPos); std::string value = opt.substr(eqPos + 1); key.erase(remove(key.begin(), key.end(), '"'), key.end()); key.erase(remove(key.begin(), key.end(), '\''), key.end()); value.erase(remove(value.begin(), value.end(), '"'), value.end()); value.erase(remove(value.begin(), value.end(), '\''), value.end()); key.erase(0, key.find_first_not_of(" \t")); key.erase(key.find_last_not_of(" \t") + 1); value.erase(0, value.find_first_not_of(" \t")); value.erase(value.find_last_not_of(" \t") + 1); globalOptions[key] = value; } } } // Entities std::regex entityRegex("([a-z0-9_\"]+[^;]*);", std::regex::icase); std::sregex_iterator entityIter(content.begin(), content.end(), entityRegex); for (; entityIter != std::sregex_iterator(); ++entityIter) { std::string ent = entityIter->str(1); std::map entityMap; size_t bracketPos = ent.find('['); std::string name = ent.substr(0, bracketPos); name.erase(0, name.find_first_not_of(" \t")); name.erase(name.find_last_not_of(" \t") + 1); entityMap["name"] = name; if (bracketPos != std::string::npos) { std::string attrStr = ent.substr(bracketPos + 1, ent.find(']') - bracketPos - 1); entityMap.update(parseAttributes(attrStr)); extractColors(entityMap); } entities.push_back(entityMap); } // Arcs std::stringstream ss(content); std::string line; while (std::getline(ss, line, ';')) { line.erase(0, line.find_first_not_of(" \t\n\r\f\v")); line.erase(line.find_last_not_of(" \t\n\r\f\v") + 1); if (std::regex_match(line, std::regex(".*[-:=x>|<.*].*"))) { std::regex arcRegex("(.*?)\\s*([-><:=x|.-]+)\\s*(.*)"); std::smatch arcMatch; if (std::regex_match(line, arcMatch, arcRegex)) { std::map arcMap; arcMap["from"] = arcMatch[1].str(); arcMap["type"] = arcMatch[2].str(); std::string toAndAttrs = arcMatch[3].str(); size_t bracketPos = toAndAttrs.find('['); std::string to = toAndAttrs.substr(0, bracketPos); to.erase(0, to.find_first_not_of(" \t")); to.erase(to.find_last_not_of(" \t") + 1); arcMap["to"] = to; if (bracketPos != std::string::npos) { std::string attrStr = toAndAttrs.substr(bracketPos + 1, toAndAttrs.find(']') - bracketPos - 1); auto attrs = parseAttributes(attrStr); for (auto& pair : attrs) { arcMap[pair.first] = pair.second; } extractColors(attrs); } arcs.push_back(arcMap); } } } // Comments std::stringstream ss2(content); while (std::getline(ss2, line)) { line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); if (line.rfind('#', 0) == 0 || line.rfind("//", 0) == 0) { comments.push_back(line); } } } std::map parseAttributes(const std::string& attrStr) { std::map attrs; std::regex attrRegex("([^,]+)"); std::sregex_iterator attrIter(attrStr.begin(), attrStr.end(), attrRegex); for (; attrIter != std::sregex_iterator(); ++attrIter) { std::string attr = attrIter->str(); size_t eqPos = attr.find('='); if (eqPos != std::string::npos) { std::string key = attr.substr(0, eqPos); std::string value = attr.substr(eqPos + 1); key.erase(remove(key.begin(), key.end(), '"'), key.end()); key.erase(remove(key.begin(), key.end(), '\''), key.end()); value.erase(remove(value.begin(), value.end(), '"'), value.end()); value.erase(remove(value.begin(), value.end(), '\''), value.end()); key.erase(0, key.find_first_not_of(" \t")); key.erase(key.find_last_not_of(" \t") + 1); value.erase(0, value.find_first_not_of(" \t")); value.erase(value.find_last_not_of(" \t") + 1); attrs[key] = value; } } return attrs; } void extractColors(const std::map& attrs) { std::vector colorKeys = {"linecolour", "linecolor", "textcolour", "textcolor", "textbgcolour", "textbgcolor", "arclinecolour", "arclinecolor", "arctextcolour", "arctextcolor", "arctextbgcolour", "arctextbgcolor"}; for (const auto& key : colorKeys) { auto it = attrs.find(key); if (it != attrs.end()) { colors.insert(it->second); } } } void printProperties() { json j; j["globalOptions"] = globalOptions; j["entities"] = entities; j["arcs"] = arcs; std::vector colorVec(colors.begin(), colors.end()); j["colors"] = colorVec; j["comments"] = comments; std::cout << j.dump(4) << std::endl; } void write(const std::string& filepath) { std::ofstream file(filepath); file << "msc {" << std::endl; std::string opts; for (const auto& pair : globalOptions) { if (!opts.empty()) opts += ", "; opts += pair.first + "=\"" + pair.second + "\""; } if (!opts.empty()) file << " " << opts << ";" << std::endl; std::string ents; for (const auto& e : entities) { if (!ents.empty()) ents += ", "; ents += e.at("name"); std::string attrStr; for (const auto& pair : e) { if (pair.first != "name") { if (!attrStr.empty()) attrStr += ", "; attrStr += pair.first + "=\"" + pair.second + "\""; } } if (!attrStr.empty()) ents += " [" + attrStr + "]"; } file << " " << ents << ";" << std::endl; for (const auto& a : arcs) { std::string from = a.at("from"); std::string type = a.at("type"); std::string to = a.at("to"); std::string attrStr; for (const auto& pair : a) { if (pair.first != "from" && pair.first != "type" && pair.first != "to") { if (!attrStr.empty()) attrStr += ", "; attrStr += pair.first + "=\"" + pair.second + "\""; } } file << " " << from << " " << type << " " << to; if (!attrStr.empty()) file << " [" << attrStr << "]"; file << ";" << std::endl; } for (const auto& c : comments) { file << c << std::endl; } file << "}" << std::endl; } }; // Example usage // int main() { // MSCParser parser; // parser.read("example.msc"); // parser.printProperties(); // parser.write("output.msc"); // return 0; // } // ===== end task-425 .MSC ===== // ===== task-426 .MSCH [C++] ===== #include #include #include #include #include #include #include class MSCHHandler { public: struct Tile { int16_t x; int16_t y; uint32_t block_id; uint8_t rotation; std::string config_hex; }; std::map tags; std::vector tiles; std::string magic; uint8_t version; uint16_t width; uint16_t height; void read(const std::string& filename) { std::ifstream file(filename, std::ios::binary); if (!file) { std::cerr << "Failed to open file." << std::endl; return; } std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); size_t offset = 0; // Magic magic = std::string(data.data() + offset, 4); offset += 4; // Version version = *reinterpret_cast(data.data() + offset); offset += 1; // Width, Height width = be16toh(*reinterpret_cast(data.data() + offset)); offset += 2; height = be16toh(*reinterpret_cast(data.data() + offset)); offset += 2; // Tags uint32_t tag_count = be32toh(*reinterpret_cast(data.data() + offset)); offset += 4; tags.clear(); for (uint32_t i = 0; i < tag_count; ++i) { uint32_t key_len = be32toh(*reinterpret_cast(data.data() + offset)); offset += 4; std::string key(data.data() + offset, key_len); offset += key_len; uint32_t val_len = be32toh(*reinterpret_cast(data.data() + offset)); offset += 4; std::string val(data.data() + offset, val_len); offset += val_len; tags[key] = val; } // Tiles uint32_t tile_count = be32toh(*reinterpret_cast(data.data() + offset)); offset += 4; tiles.clear(); for (uint32_t i = 0; i < tile_count; ++i) { Tile t; t.x = be16toh(*reinterpret_cast(data.data() + offset)); offset += 2; t.y = be16toh(*reinterpret_cast(data.data() + offset)); offset += 2; t.block_id = be32toh(*reinterpret_cast(data.data() + offset)); offset += 4; t.rotation = *reinterpret_cast(data.data() + offset); offset += 1; uint32_t config_len = be32toh(*reinterpret_cast(data.data() + offset)); offset += 4; std::stringstream ss; for (uint32_t j = 0; j < config_len; ++j) { ss << std::hex << std::setw(2) << std::setfill('0') << (unsigned int)(unsigned char)data[offset + j] << " "; } t.config_hex = ss.str(); if (!t.config_hex.empty()) t.config_hex.pop_back(); // Remove trailing space offset += config_len; tiles.push_back(t); } } void printProperties() { std::cout << "Magic: " << magic << std::endl; std::cout << "Version: " << (int)version << std::endl; std::cout << "Width: " << width << std::endl; std::cout << "Height: " << height << std::endl; std::cout << "Tags:" << std::endl; for (const auto& pair : tags) { std::cout << " " << pair.first << ": " << pair.second << std::endl; } std::cout << "Tiles:" << std::endl; for (const auto& t : tiles) { std::cout << " X: " << t.x << ", Y: " << t.y << ", Block ID: " << t.block_id << ", Rotation: " << (int)t.rotation << ", Config (hex): " << t.config_hex << std::endl; } } void write(const std::string& filename) { std::ofstream file(filename, std::ios::binary); if (!file) { std::cerr << "Failed to open file for writing." << std::endl; return; } // Magic file.write(magic.c_str(), 4); // Version file.put(version); // Width, Height uint16_t be_width = htobe16(width); file.write(reinterpret_cast(&be_width), 2); uint16_t be_height = htobe16(height); file.write(reinterpret_cast(&be_height), 2); // Tags uint32_t be_tag_count = htobe32(tags.size()); file.write(reinterpret_cast(&be_tag_count), 4); for (const auto& pair : tags) { uint32_t be_key_len = htobe32(pair.first.size()); file.write(reinterpret_cast(&be_key_len), 4); file.write(pair.first.c_str(), pair.first.size()); uint32_t be_val_len = htobe32(pair.second.size()); file.write(reinterpret_cast(&be_val_len), 4); file.write(pair.second.c_str(), pair.second.size()); } // Tiles uint32_t be_tile_count = htobe32(tiles.size()); file.write(reinterpret_cast(&be_tile_count), 4); for (const auto& t : tiles) { int16_t be_x = htobe16(t.x); file.write(reinterpret_cast(&be_x), 2); int16_t be_y = htobe16(t.y); file.write(reinterpret_cast(&be_y), 2); uint32_t be_block_id = htobe32(t.block_id); file.write(reinterpret_cast(&be_block_id), 4); file.put(t.rotation); std::vector config_bytes = hexToBytes(t.config_hex); uint32_t be_config_len = htobe32(config_bytes.size()); file.write(reinterpret_cast(&be_config_len), 4); for (uint8_t b : config_bytes) { file.put(b); } } } private: std::vector hexToBytes(const std::string& hex) { std::vector bytes; std::stringstream ss(hex); std::string byte_str; while (ss >> byte_str) { uint8_t b = static_cast(std::stoi(byte_str, nullptr, 16)); bytes.push_back(b); } return bytes; } }; // Example usage: // int main() { // MSCHHandler handler; // handler.read("example.msch"); // handler.printProperties(); // handler.write("new.msch"); // return 0; // } // ===== end task-426 .MSCH ===== // ===== task-427 .MSCZ [C] ===== #include #include #include #include "miniz.h" // For ZIP handling #include "tinyxml2.h" // For XML parsing typedef struct { char* filepath; tinyxml2::XMLDocument* xmlDoc; char* properties[20][2]; // Key-value pairs (limited for simplicity) int propCount; int modified; } MSCZHandler; void initMSCZHandler(MSCZHandler* handler, const char* filepath) { handler->filepath = strdup(filepath); handler->xmlDoc = NULL; handler->propCount = 0; handler->modified = 0; } void readDecode(MSCZHandler* handler) { mz_zip_archive zip_archive = {0}; if (!mz_zip_reader_init_file(&zip_archive, handler->filepath, 0)) { printf("Failed to open ZIP\n"); return; } char* xmlContent = NULL; char structure[1024] = {0}; for (int i = 0; i < (int)mz_zip_reader_get_num_files(&zip_archive); i++) { mz_zip_archive_file_stat file_stat; mz_zip_reader_file_stat(&zip_archive, i, &file_stat); strncat(structure, file_stat.m_filename, sizeof(structure) - strlen(structure) - 1); strncat(structure, ", ", sizeof(structure) - strlen(structure) - 1); if (strstr(file_stat.m_filename, ".mscx")) { xmlContent = (char*)malloc(file_stat.m_uncomp_size + 1); mz_zip_reader_extract_to_mem(&zip_archive, i, xmlContent, file_stat.m_uncomp_size, 0); xmlContent[file_stat.m_uncomp_size] = '\0'; } } mz_zip_reader_end(&zip_archive); if (!xmlContent) { printf("No .mscx found\n"); return; } handler->xmlDoc = new tinyxml2::XMLDocument(); handler->xmlDoc->Parse(xmlContent); free(xmlContent); // Extract properties handler->properties[handler->propCount][0] = strdup("file_extension"); handler->properties[handler->propCount++][1] = strdup(".mscz"); handler->properties[handler->propCount][0] = strdup("mime_type"); handler->properties[handler->propCount++][1] = strdup("application/x-musescore"); handler->properties[handler->propCount][0] = strdup("magic_number"); handler->properties[handler->propCount++][1] = strdup("PK\\003\\004"); handler->properties[handler->propCount][0] = strdup("compression_type"); handler->properties[handler->propCount++][1] = strdup("ZIP (Deflate)"); handler->properties[handler->propCount][0] = strdup("container_structure"); handler->properties[handler->propCount++][1] = strdup(structure); handler->properties[handler->propCount][0] = strdup("internal_data_format"); handler->properties[handler->propCount++][1] = strdup("XML-based (UTF-8)"); tinyxml2::XMLElement* root = handler->xmlDoc->FirstChildElement("museScore"); if (root) { char buf[50]; snprintf(buf, sizeof(buf), "", root->Attribute("version")); handler->properties[handler->propCount][0] = strdup("root_xml_element"); handler->properties[handler->propCount++][1] = strdup(buf); } tinyxml2::XMLElement* score = root ? root->FirstChildElement("Score") : NULL; if (score) { handler->properties[handler->propCount][0] = strdup("programVersion"); handler->properties[handler->propCount++][1] = strdup(score->FirstChildElement("programVersion") ? score->FirstChildElement("programVersion")->GetText() : "N/A"); handler->properties[handler->propCount][0] = strdup("programRevision"); handler->properties[handler->propCount++][1] = strdup(score->FirstChildElement("programRevision") ? score->FirstChildElement("programRevision")->GetText() : "N/A"); } tinyxml2::XMLElement* meta = score ? score->FirstChildElement("metaTag") : NULL; while (meta) { const char* name = meta->Attribute("name"); handler->properties[handler->propCount][0] = strdup(name); handler->properties[handler->propCount++][1] = strdup(meta->GetText() ? meta->GetText() : "N/A"); meta = meta->NextSiblingElement("metaTag"); } handler->properties[handler->propCount][0] = strdup("version_compatibility"); handler->properties[handler->propCount++][1] = strdup("Backward compatible"); handler->properties[handler->propCount][0] = strdup("cross_platform_support"); handler->properties[handler->propCount++][1] = strdup("Yes"); handler->properties[handler->propCount][0] = strdup("developer"); handler->properties[handler->propCount++][1] = strdup("MuseScore"); } void printProperties(MSCZHandler* handler) { for (int i = 0; i < handler->propCount; i++) { printf("%s: %s\n", handler->properties[i][0], handler->properties[i][1]); } } void write(MSCZHandler* handler, const char* newFilepath) { if (!handler->modified) { printf("No changes to write.\n"); return; } const char* outputPath = newFilepath ? newFilepath : handler->filepath; tinyxml2::XMLPrinter printer; handler->xmlDoc->Print(&printer); mz_zip_archive zip_archive = {0}; mz_zip_writer_init_file(&zip_archive, outputPath, 0); mz_zip_writer_add_mem(&zip_archive, "score.mscx", printer.CStr(), printer.CStrSize() - 1, MZ_DEFAULT_COMPRESSION); mz_zip_writer_finalize_archive(&zip_archive); mz_zip_writer_end(&zip_archive); printf("File written to %s\n", outputPath); } void setProperty(MSCZHandler* handler, const char* key, const char* value) { tinyxml2::XMLElement* score = handler->xmlDoc->FirstChildElement("museScore")->FirstChildElement("Score"); if (strcmp(key, "programVersion") == 0 || strcmp(key, "programRevision") == 0) { tinyxml2::XMLElement* elem = score->FirstChildElement(key); if (!elem) { elem = handler->xmlDoc->NewElement(key); score->InsertEndChild(elem); } elem->SetText(value); } else { tinyxml2::XMLElement* meta = score->FirstChildElement("metaTag"); while (meta) { if (strcmp(meta->Attribute("name"), key) == 0) { meta->SetText(value); goto done; } meta = meta->NextSiblingElement("metaTag"); } meta = handler->xmlDoc->NewElement("metaTag"); meta->SetAttribute("name", key); meta->SetText(value); score->InsertEndChild(meta); } done: handler->modified = 1; // Update properties array (simplified, assumes key exists or add) } void freeMSCZHandler(MSCZHandler* handler) { free(handler->filepath); delete handler->xmlDoc; for (int i = 0; i < handler->propCount; i++) { free(handler->properties[i][0]); free(handler->properties[i][1]); } } // Example usage: // int main() { // MSCZHandler handler; // initMSCZHandler(&handler, "example.mscz"); // readDecode(&handler); // printProperties(&handler); // setProperty(&handler, "composer", "New Composer"); // write(&handler, NULL); // freeMSCZHandler(&handler); // return 0; // } // ===== end task-427 .MSCZ ===== // ===== task-428 .MSDL [C++] ===== #include #include #include // Assume tinyxml2.h is included and library linked #include "tinyxml2.h" class MSDLHandler { private: const char* filepath; tinyxml2::XMLDocument doc; public: MSDLHandler(const char* fp) : filepath(fp) {} bool read() { if (doc.LoadFile(filepath) != tinyxml2::XML_SUCCESS) { printf("Failed to load file %s\n", filepath); return false; } return true; } void printProperties() { tinyxml2::XMLElement* root = doc.FirstChildElement(); if (!root) { printf("No file loaded or invalid XML.\n"); return; } printElement(root, ""); } void printElement(tinyxml2::XMLElement* elem, const char* indent) { printf("%s%s: %s\n", indent, elem->Name(), elem->GetText() ? elem->GetText() : ""); for (const tinyxml2::XMLAttribute* attr = elem->FirstAttribute(); attr; attr = attr->Next()) { printf("%s @%s: %s\n", indent, attr->Name(), attr->Value()); } for (tinyxml2::XMLElement* child = elem->FirstChildElement(); child; child = child->NextSiblingElement()) { char newIndent[256]; snprintf(newIndent, sizeof(newIndent), "%s ", indent); printElement(child, newIndent); } } bool write(const char* newFilepath) { if (doc.SaveFile(newFilepath) != tinyxml2::XML_SUCCESS) { printf("Failed to write file %s\n", newFilepath); return false; } printf("File written to %s\n", newFilepath); return true; } }; // Example usage // int main() { // MSDLHandler handler("example.msdl"); // if (handler.read()) { // handler.printProperties(); // handler.write("output.msdl"); // } // return 0; // } // ===== end task-428 .MSDL ===== // ===== task-429 .MSF [C++] ===== #include #include #include #include #include #include struct Sequence { std::string name; int len; int check; double weight; std::string sequence; }; class MSFHandler { private: std::string filepath; int alignment_length; std::string type; int global_checksum; std::vector sequences; public: MSFHandler(const std::string& fp = "") : filepath(fp) { if (!fp.empty()) read(fp); } void parse_header(std::ifstream& file) { std::string line; while (std::getline(file, line)) { std::istringstream iss(line); std::string token; if (line.find("..") != std::string::npos) { while (iss >> token) { if (token.find("MSF:") == 0) alignment_length = std::stoi(token.substr(4)); if (token.find("Type:") == 0) type = token.substr(5); if (token.find("Check:") == 0) global_checksum = std::stoi(token.substr(6)); } } else if (line.find("Name:") != std::string::npos) { Sequence seq; while (iss >> token) { if (token == "Name:") iss >> seq.name; if (token == "Len:") iss >> seq.len; if (token == "Check:") iss >> seq.check; if (token == "Weight:") iss >> seq.weight; } seq.sequence = ""; sequences.push_back(seq); } else if (line.find("//") != std::string::npos) { break; } } } void parse_alignment(std::ifstream& file) { std::string line; while (std::getline(file, line)) { if (line.empty()) continue; std::istringstream iss(line); std::string name, segment; iss >> name; while (iss >> segment) { for (char& c : segment) if (c == '.') c = '-'; } std::string full_segment; iss.clear(); iss.seekg(0); iss >> name; std::getline(iss, full_segment); full_segment.erase(std::remove(full_segment.begin(), full_segment.end(), ' '), full_segment.end()); for (auto& seq : sequences) { if (seq.name == name) { seq.sequence += full_segment; break; } } } } void read(const std::string& fp) { filepath = fp; std::ifstream file(fp); if (!file) { std::cerr << "Error opening file: " << fp << std::endl; return; } parse_header(file); parse_alignment(file); file.close(); } void print_properties() const { std::cout << "Alignment Length: " << alignment_length << std::endl; std::cout << "Type: " << type << std::endl; std::cout << "Global Checksum: " << global_checksum << std::endl; for (const auto& seq : sequences) { std::cout << "Name: " << seq.name << ", Length: " << seq.len << ", Checksum: " << seq.check << ", Weight: " << seq.weight << std::endl; } } void write(const std::string& new_fp = "") const { std::string out_fp = new_fp.empty() ? (filepath.empty() ? "output.msf" : filepath) : new_fp; std::ofstream file(out_fp); if (!file) { std::cerr << "Error writing file: " << out_fp << std::endl; return; } file << "MSF: " << alignment_length << " Type: " << type << " Check: " << global_checksum << " ..\n"; for (const auto& seq : sequences) { file << "Name: " << seq.name << " Len: " << seq.len << " Check: " << seq.check << " Weight: " << std::fixed << std::setprecision(2) << seq.weight << "\n"; } file << "//\n"; size_t max_name_len = 0; for (const auto& seq : sequences) max_name_len = std::max(max_name_len, seq.name.length()); size_t pos = 0; while (pos < static_cast(alignment_length)) { for (const auto& seq : sequences) { std::string segment = seq.sequence.substr(pos, 50); file << std::left << std::setw(max_name_len + 1) << seq.name << segment << "\n"; } file << "\n"; pos += 50; } file.close(); } }; // Example usage: // int main() { // MSFHandler msf("example.msf"); // msf.print_properties(); // msf.write("new.msf"); // return 0; // } // ===== end task-429 .MSF ===== // ===== task-430 .MSI [C++] ===== #include #include #include #include #include #include #include #include class MsiPropertyHandler { private: std::string filepath; std::vector data; std::map> properties; // PID -> (type, value as string) public: MsiPropertyHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); auto size = file.tellg(); data.resize(size); file.seekg(0); file.read(reinterpret_cast(data.data()), size); parseProperties(); } void printProperties() { if (properties.empty()) read(); for (const auto& [pid, info] : properties) { std::cout << "PID " << pid << ": Type " << info.first << ", Value: " << info.second << std::endl; } } void write(const std::string& outputPath, uint32_t pid, const std::string& newValue) { if (data.empty()) read(); // Similar modify logic as above auto summaryStream = getSummaryStream(); // Placeholder // Modify buffer... // For demo, assume modified std::ofstream out(outputPath, std::ios::binary); out.write(reinterpret_cast(data.data()), data.size()); std::cout << "Modified file saved to " << outputPath << std::endl; } private: void parseProperties() { // Full binary parsing similar to JS (use memcpy, etc. for views) // Omitted for brevity } std::vector getSummaryStream() { return {}; // Placeholder } }; // Example: // int main() { // MsiPropertyHandler handler("example.msi"); // handler.printProperties(); // handler.write("modified.msi", 3, "New Subject"); // return 0; // } // ===== end task-430 .MSI ===== // ===== task-431 .MSO [C] ===== #include #include #include #include #include // For pow typedef struct { char filepath[256]; uint8_t header[512]; uint32_t difat[109]; } MsoFileParser; void read_header(MsoFileParser *parser) { FILE *fp = fopen(parser->filepath, "rb"); if (fp == NULL) { perror("Error opening file"); exit(1); } size_t read_size = fread(parser->header, 1, 512, fp); fclose(fp); if (read_size < 512) { fprintf(stderr, "File too small to be a valid .MSO/CFB file.\n"); exit(1); } // Extract DIFAT memcpy(parser->difat, &parser->header[76], sizeof(uint32_t) * 109); } void print_properties(MsoFileParser *parser) { printf("MSO File Properties:\n"); // Signature (0-7) printf("Signature: 0x"); for (int i = 0; i < 8; i++) { printf("%02x ", parser->header[i]); } printf("\n"); // CLSID (8-23) printf("CLSID: "); for (int i = 8; i < 24; i += 4) { uint32_t part = *(uint32_t*)(&parser->header[i]); printf("%08x-", part); } printf("\b\n"); // Remove trailing - // Minor Version (24-25) uint16_t minor_ver = *(uint16_t*)(&parser->header[24]); printf("Minor Version: %u\n", minor_ver); // Major Version (26-27) uint16_t major_ver = *(uint16_t*)(&parser->header[26]); printf("Major Version: %u\n", major_ver); // Byte Order (28-29) uint16_t byte_order = *(uint16_t*)(&parser->header[28]); printf("Byte Order: 0x%04x\n", byte_order); // Sector Shift (30-31) uint16_t sector_shift = *(uint16_t*)(&parser->header[30]); printf("Sector Shift: %u (Sector Size: %d bytes)\n", sector_shift, (int)pow(2, sector_shift)); // Mini Sector Shift (32-33) uint16_t mini_sector_shift = *(uint16_t*)(&parser->header[32]); printf("Mini Sector Shift: %u (Mini Sector Size: %d bytes)\n", mini_sector_shift, (int)pow(2, mini_sector_shift)); // Reserved1 (34-35) uint16_t reserved1 = *(uint16_t*)(&parser->header[34]); printf("Reserved1: %u\n", reserved1); // Reserved2 (36-39) uint32_t reserved2 = *(uint32_t*)(&parser->header[36]); printf("Reserved2: %u\n", reserved2); // Number of Directory Sectors (40-43) uint32_t num_dir_sectors = *(uint32_t*)(&parser->header[40]); printf("Number of Directory Sectors: %u\n", num_dir_sectors); // Number of FAT Sectors (44-47) uint32_t num_fat_sectors = *(uint32_t*)(&parser->header[44]); printf("Number of FAT Sectors: %u\n", num_fat_sectors); // First Directory Sector Location (48-51) uint32_t first_dir_sect = *(uint32_t*)(&parser->header[48]); printf("First Directory Sector Location: %u\n", first_dir_sect); // Transaction Signature (52-55) uint32_t trans_sig = *(uint32_t*)(&parser->header[52]); printf("Transaction Signature: %u\n", trans_sig); // Mini Stream Cutoff Size (56-59) uint32_t mini_cutoff = *(uint32_t*)(&parser->header[56]); printf("Mini Stream Cutoff Size: %u\n", mini_cutoff); // First Mini FAT Sector Location (60-63) uint32_t first_mini_fat = *(uint32_t*)(&parser->header[60]); printf("First Mini FAT Sector Location: %u\n", first_mini_fat); // Number of Mini FAT Sectors (64-67) uint32_t num_mini_fat = *(uint32_t*)(&parser->header[64]); printf("Number of Mini FAT Sectors: %u\n", num_mini_fat); // First DIFAT Sector Location (68-71) uint32_t first_difat = *(uint32_t*)(&parser->header[68]); printf("First DIFAT Sector Location: %u\n", first_difat); // Number of DIFAT Sectors (72-75) uint32_t num_difat = *(uint32_t*)(&parser->header[72]); printf("Number of DIFAT Sectors: %u\n", num_difat); // DIFAT Array printf("DIFAT Array (first 109 FAT sectors):\n"); for (int i = 0; i < 109; i++) { printf(" Entry %d: %u (0x%x)\n", i, parser->difat[i], parser->difat[i]); } } void write_sample(MsoFileParser *parser, const char *output_path) { uint8_t header[512] = {0}; // Signature uint8_t sig[] = {0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1}; memcpy(header, sig, 8); // CLSID zero (8-23) // Minor ver (24-25) *(uint16_t*)(&header[24]) = 0x003E; // Major ver (26-27) *(uint16_t*)(&header[26]) = 3; // Byte order (28-29) *(uint16_t*)(&header[28]) = 0xFFFE; // Sector shift (30-31) *(uint16_t*)(&header[30]) = 9; // Mini sector shift (32-33) *(uint16_t*)(&header[32]) = 6; // Reserved1 (34-35) *(uint16_t*)(&header[34]) = 0; // Reserved2 (36-39) *(uint32_t*)(&header[36]) = 0; // Num dir sectors (40-43) *(uint32_t*)(&header[40]) = 0; // Num FAT sectors (44-47) *(uint32_t*)(&header[44]) = 1; // First dir sect (48-51) *(uint32_t*)(&header[48]) = 0; // Trans sig (52-55) *(uint32_t*)(&header[52]) = 0; // Mini cutoff (56-59) *(uint32_t*)(&header[56]) = 4096; // First mini FAT (60-63) *(uint32_t*)(&header[60]) = 1; // Num mini FAT (64-67) *(uint32_t*)(&header[64]) = 1; // First DIFAT (68-71) *(uint32_t*)(&header[68]) = 0xFFFFFFFE; // Num DIFAT (72-75) *(uint32_t*)(&header[72]) = 0; // DIFAT all ENDOFCHAIN (76-511) for (int i = 0; i < 109; i++) { *(uint32_t*)(&header[76 + i * 4]) = 0xFFFFFFFE; } FILE *fp = fopen(output_path, "wb"); if (fp == NULL) { perror("Error writing file"); exit(1); } fwrite(header, 1, 512, fp); fclose(fp); } int main(int argc, char *argv[]) { if (argc < 2) { printf("Usage: %s [output_path]\n", argv[0]); return 1; } MsoFileParser parser; strcpy(parser.filepath, argv[1]); read_header(&parser); print_properties(&parser); if (argc > 2) { write_sample(&parser, argv[2]); printf("Sample .MSO written to %s\n", argv[2]); } return 0; } // ===== end task-431 .MSO ===== // ===== task-432 .MSSTYLES [C++] ===== #include #include #include #include #include class MSStylesHandler { private: std::string filepath; std::vector data; std::vector properties = {"AMAP", "BCMAP", "CMAP", "PACKTHEM_VERSION", "RMAP", "IMAGE", "STREAM", "VARIANT", "VMAP", "DESKTOP", "PVL", "IMMERSIVE"}; std::vector foundProps; uint32_t readUint32(size_t offset) const { return (data[offset + 3] << 24) | (data[offset + 2] << 16) | (data[offset + 1] << 8) | data[offset]; } uint16_t readUint16(size_t offset) const { return (data[offset + 1] << 8) | data[offset]; } public: MSStylesHandler(const std::string& fp) : filepath(fp) {} void readDecode() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) throw std::runtime_error("Cannot open file"); size_t size = file.tellg(); data.resize(size); file.seekg(0); file.read(reinterpret_cast(data.data()), size); if (readUint16(0) != 0x5A4D) throw std::runtime_error("Not a valid PE file"); uint32_t peOffset = readUint32(0x3C); if (readUint32(peOffset) != 0x4550) throw std::runtime_error("Not a valid PE file"); uint32_t optHeaderOffset = peOffset + 24; uint32_t numDataDirs = readUint32(optHeaderOffset + 92); if (numDataDirs < 3) throw std::runtime_error("No resource directory"); uint32_t resourceRVA = readUint32(optHeaderOffset + 96 + 8); uint32_t resourceSize = readUint32(optHeaderOffset + 96 + 12); uint16_t numSections = readUint16(peOffset + 6); uint32_t sectionOffset = optHeaderOffset + readUint16(optHeaderOffset - 4); uint32_t resourceOffset = 0; for (uint16_t i = 0; i < numSections; ++i) { uint32_t secVA = readUint32(sectionOffset + 12); uint32_t secSize = readUint32(sectionOffset + 8); uint32_t secRawPtr = readUint32(sectionOffset + 20); if (resourceRVA >= secVA && resourceRVA < secVA + secSize) { resourceOffset = secRawPtr + (resourceRVA - secVA); break; } sectionOffset += 40; } if (resourceOffset == 0) throw std::runtime_error("Resource section not found"); uint16_t numNamed = readUint16(resourceOffset + 12); uint16_t numId = readUint16(resourceOffset + 14); uint32_t entryOffset = resourceOffset + 16; for (uint16_t i = 0; i < numNamed + numId; ++i) { uint32_t nameRVA = readUint32(entryOffset); if (nameRVA & 0x80000000) { uint32_t nameOffset = resourceOffset + (nameRVA & 0x7FFFFFFF); uint16_t nameLen = readUint16(nameOffset); std::string name; for (uint16_t j = 0; j < nameLen; ++j) { name += static_cast(readUint16(nameOffset + 2 + j * 2)); } for (const auto& prop : properties) { if (prop == name) { foundProps.push_back(name); break; } } } entryOffset += 8; } } void printProperties() const { if (foundProps.empty()) { std::cout << "No properties found or file not read." << std::endl; } else { std::cout << "Found properties:" << std::endl; for (const auto& prop : foundProps) { std::cout << prop << std::endl; } } } void write(const std::string& newFilepath) const { std::ofstream out(newFilepath, std::ios::binary); if (!out) throw std::runtime_error("Cannot write file"); out.write(reinterpret_cast(data.data()), data.size()); std::cout << "File written to " << newFilepath << std::endl; } }; // Example usage: // int main() { // try { // MSStylesHandler handler("example.msstyles"); // handler.readDecode(); // handler.printProperties(); // handler.write("modified.msstyles"); // } catch (const std::exception& e) { // std::cerr << "Error: " << e.what() << std::endl; // } // return 0; // } // ===== end task-432 .MSSTYLES ===== // ===== task-433 .MSU [C++] ===== #include #include #include #include #include struct FolderProp { uint32_t coffCabStart; uint16_t cCFData; uint16_t typeCompress; }; struct FileProp { uint32_t cbFile; uint32_t uoffFolderStart; uint16_t iFolder; uint16_t date; uint16_t time; uint16_t attribs; std::string szName; }; class MSUParser { private: std::string filename; std::vector data; size_t offset = 0; public: MSUParser(const std::string& fn) : filename(fn) {} void open() { std::ifstream f(filename, std::ios::binary); f.seekg(0, std::ios::end); size_t size = f.tellg(); f.seekg(0); data.resize(size); f.read(reinterpret_cast(data.data()), size); } uint8_t readU1() { return data[offset++]; } uint16_t readU2() { uint16_t val = *reinterpret_cast(&data[offset]); offset += 2; return val; } uint32_t readU4() { uint32_t val = *reinterpret_cast(&data[offset]); offset += 4; return val; } std::string readString() { size_t start = offset; while (readU1() != 0); return std::string(reinterpret_cast(&data[start]), offset - start - 1); } void decode() { std::string sig = ""; for (int i = 0; i < 4; i++) sig += static_cast(readU1()); if (sig != "MSCF") throw std::runtime_error("Invalid CAB signature"); readU4(); // reserved1 uint32_t cbCabinet = readU4(); readU4(); // reserved2 uint32_t coffFiles = readU4(); readU4(); // reserved3 readU1(); // versionMinor readU1(); // versionMajor uint16_t cFolders = readU2(); uint16_t cFiles = readU2(); uint16_t flags = readU2(); readU2(); // setID readU2(); // iCabinet uint16_t cbCFFolder = 0; if (flags & 0x0004) { readU2(); // cbCFHeader cbCFFolder = readU1(); readU1(); // cbCFData // Skip abReserve } // Skip optional strings... std::vector folders; for (uint16_t i = 0; i < cFolders; i++) { FolderProp fp; fp.coffCabStart = readU4(); fp.cCFData = readU2(); fp.typeCompress = readU2(); offset += cbCFFolder; folders.push_back(fp); } offset = coffFiles; std::vector files; for (uint16_t i = 0; i < cFiles; i++) { FileProp fp; fp.cbFile = readU4(); fp.uoffFolderStart = readU4(); fp.iFolder = readU2(); fp.date = readU2(); fp.time = readU2(); fp.attribs = readU2(); fp.szName = readString(); files.push_back(fp); } // Store in member if needed } void printProperties() { // Implement printing similar to above std::cout << "Properties printed" << std::endl; } void write(const std::string& newFilename) { std::ofstream f(newFilename, std::ios::binary); f.write(reinterpret_cast(data.data()), data.size()); } }; // Usage example: // MSUParser parser("example.msu"); // parser.open(); // parser.decode(); // parser.printProperties(); // parser.write("modified.msu"); // ===== end task-433 .MSU ===== // ===== task-434 .MTS [C] ===== #include #include #include #include #include #include #include struct MTSFileHandler { char *filepath; struct stat statbuf; }; struct MTSFileHandler* mts_create(const char *filepath) { if (strstr(filepath, ".mts") == NULL && strstr(filepath, ".MTS") == NULL) { fprintf(stderr, "File must be .MTS format\n"); return NULL; } struct MTSFileHandler *handler = malloc(sizeof(struct MTSFileHandler)); handler->filepath = strdup(filepath); if (stat(filepath, &handler->statbuf) != 0) { free(handler); return NULL; } return handler; } void mts_print_properties(struct MTSFileHandler *handler) { if (handler == NULL) return; printf("File size (bytes): %ld\n", handler->statbuf.st_size); printf("Creation time: %s", ctime(&handler->statbuf.st_ctime)); printf("Modification time: %s", ctime(&handler->statbuf.st_mtime)); printf("Access time: %s", ctime(&handler->statbuf.st_atime)); printf("Permissions (mode): %o\n", handler->statbuf.st_mode); printf("Owner UID: %d\n", handler->statbuf.st_uid); printf("Owner GID: %d\n", handler->statbuf.st_gid); printf("Inode number: %ld\n", handler->statbuf.st_ino); printf("Device ID: %ld\n", handler->statbuf.st_dev); printf("Number of hard links: %ld\n", handler->statbuf.st_nlink); } int mts_write_modification_time(struct MTSFileHandler *handler, time_t new_mtime) { if (handler == NULL) return -1; struct utimbuf ut; ut.actime = handler->statbuf.st_atime; ut.modtime = new_mtime; return utime(handler->filepath, &ut); } int mts_write_permissions(struct MTSFileHandler *handler, mode_t new_mode) { if (handler == NULL) return -1; return chmod(handler->filepath, new_mode); } void mts_destroy(struct MTSFileHandler *handler) { if (handler) { free(handler->filepath); free(handler); } } // Example usage: // int main() { // struct MTSFileHandler *handler = mts_create("example.mts"); // if (handler) { // mts_print_properties(handler); // mts_write_modification_time(handler, time(NULL)); // mts_write_permissions(handler, S_IRUSR | S_IWUSR); // mts_destroy(handler); // } // return 0; // } // ===== end task-434 .MTS ===== // ===== task-435 .MUP [C++] ===== #include #include #include #include #include #include class MupFileHandler { private: std::string filepath; std::map>> properties; // Nested: context -> subkey -> key:value public: MupFileHandler(const std::string& fp) : filepath(fp) { properties["score"]; properties["staff"]; properties["voice"]; } void read_decode() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file" << std::endl; return; } std::string line, current_context = "music"; while (std::getline(file, line)) { line.erase(0, line.find_first_not_of(" \t")); // Trim left line.erase(line.find_last_not_of(" \t") + 1); // Trim right if (line.empty() || line.substr(0, 2) == "//") continue; std::regex context_regex(R"(^(score|staff \d+|voice \d+ \d+|music|header|footer|block|grids|headshapes|symbol|accidentals|keymap))", std::regex::icase); std::smatch context_match; if (std::regex_match(line, context_match, context_regex)) { current_context = std::string(context_match[1]).erase(); // To lower? Use transform if needed std::transform(current_context.begin(), current_context.end(), current_context.begin(), ::tolower); continue; } std::regex prop_regex(R"(^(\w+)\s*=\s*(.+?)(;|$))"); std::smatch prop_match; if (std::regex_match(line, prop_match, prop_regex)) { std::string key = prop_match[1].str(); std::transform(key.begin(), key.end(), key.begin(), ::tolower); std::string value = prop_match[2].str(); if (current_context == "score") { properties["score"]["global"][key] = value; } else if (current_context.find("staff") == 0) { std::smatch num_match; std::regex_search(current_context, num_match, std::regex(R"(\d+)")); std::string staff_num = num_match[0].str(); properties["staff"][staff_num][key] = value; } else if (current_context.find("voice") == 0) { std::smatch num_match; std::regex_search(current_context, num_match, std::regex(R"((\d+) (\d+))")); std::string staff_num = num_match[1].str(); std::string voice_num = num_match[2].str(); properties["voice"][staff_num][key] = voice_num; // Wait, fix: properties["voice"][staff_num][voice_num] = ... no, map is context->subkey->k:v properties["voice"][staff_num + "_" + voice_num][key] = value; // Simplify nesting } } } file.close(); } void print_properties() { std::cout << "Extracted Properties:" << std::endl; for (const auto& [context, submaps] : properties) { std::cout << context << ":" << std::endl; for (const auto& [subkey, props] : submaps) { std::cout << " " << subkey << ":" << std::endl; for (const auto& [key, value] : props) { std::cout << " " << key << " = " << value << std::endl; } } } } void write(const std::string& new_filepath, const std::map>>& new_properties = {}) { auto write_props = new_properties.empty() ? properties : new_properties; std::ofstream file(new_filepath); if (!file.is_open()) { std::cerr << "Error opening file for write" << std::endl; return; } for (const auto& [context, submaps] : write_props) { file << context << "\n"; for (const auto& [subkey, props] : submaps) { for (const auto& [key, value] : props) { file << key << " = " << value << ";\n"; } } file << "\n"; } file.close(); } }; // Example usage: // int main() { // MupFileHandler handler("example.mup"); // handler.read_decode(); // handler.print_properties(); // std::map>> new_props; // new_props["score"]["global"]["staffs"] = "2"; // handler.write("new.mup", new_props); // return 0; // } // ===== end task-435 .MUP ===== // ===== task-436 .MX [C++] ===== #include #include #include #include #include #include #include // For big endian conversions, may need to include on some systems class MXFHandler { private: std::string filepath; std::map properties; // Use string for simplicity, convert as needed public: MXFHandler(const std::string& fp = "") : filepath(fp) { if (!fp.empty()) read(fp); } void read(const std::string& fp) { filepath = fp; std::ifstream file(fp, std::ios::binary); if (!file) { std::cerr << "Error opening file" << std::endl; return; } file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(reinterpret_cast(data.data()), size); parseProperties(data.data()); } void parseProperties(const uint8_t* data) { // Partition Pack Key (16 bytes) std::stringstream ss; for (int i = 0; i < 16; ++i) { if (i > 0) ss << '.'; ss << std::setfill('0') << std::setw(2) << std::hex << static_cast(data[i]); } properties["Partition Pack Key"] = ss.str(); // Major/Minor Version properties["Major Version"] = std::to_string(data[16]); properties["Minor Version"] = std::to_string(data[17]); // KAG Size (be32toh) uint32_t kag = be32toh(*reinterpret_cast(data + 18)); properties["KAG Size"] = std::to_string(kag); // This Partition (be64toh) uint64_t thisPart = be64toh(*reinterpret_cast(data + 22)); properties["This Partition"] = std::to_string(thisPart); // Previous Partition uint64_t prevPart = be64toh(*reinterpret_cast(data + 30)); properties["Previous Partition"] = std::to_string(prevPart); // Footer Partition uint64_t footPart = be64toh(*reinterpret_cast(data + 38)); properties["Footer Partition"] = std::to_string(footPart); // Header Byte Count uint64_t headCount = be64toh(*reinterpret_cast(data + 46)); properties["Header Byte Count"] = std::to_string(headCount); // Index Byte Count uint64_t indexCount = be64toh(*reinterpret_cast(data + 54)); properties["Index Byte Count"] = std::to_string(indexCount); // Index SID uint32_t indexSid = be32toh(*reinterpret_cast(data + 62)); properties["Index SID"] = std::to_string(indexSid); // Body Offset uint64_t bodyOff = be64toh(*reinterpret_cast(data + 66)); properties["Body Offset"] = std::to_string(bodyOff); // Body SID uint32_t bodySid = be32toh(*reinterpret_cast(data + 74)); properties["Body SID"] = std::to_string(bodySid); // Operational Pattern UL (16 bytes) ss.str(""); for (int i = 78; i < 94; ++i) { if (i > 78) ss << '.'; ss << std::setfill('0') << std::setw(2) << std::hex << static_cast(data[i]); } properties["Operational Pattern UL"] = ss.str(); // Essence Containers Batch uint32_t essenceCount = be32toh(*reinterpret_cast(data + 94)); properties["Essence Containers Count"] = std::to_string(essenceCount); // Skip len at 98 std::string ulsStr; size_t offset = 102; for (uint32_t i = 0; i < essenceCount; ++i) { if (i > 0) ulsStr += ", "; ss.str(""); for (int j = 0; j < 16; ++j) { if (j > 0) ss << '.'; ss << std::setfill('0') << std::setw(2) << std::hex << static_cast(data[offset + j]); } ulsStr += ss.str(); offset += 16; } properties["Essence Containers ULs"] = ulsStr; } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& fp) { std::ofstream file(fp, std::ios::binary); if (!file) { std::cerr << "Error writing file" << std::endl; return; } std::vector data(1024, 0); // Key std::string keyStr = properties["Partition Pack Key"].empty() ? "06.0e.2b.34.02.05.01.01.0d.01.02.01.01.02.04.00" : properties["Partition Pack Key"]; auto parts = split(keyStr, '.'); for (size_t i = 0; i < 16; ++i) { data[i] = static_cast(std::stoi(parts[i], nullptr, 16)); } size_t offset = 16; // Major/Minor data[offset++] = static_cast(std::stoi(properties["Major Version"].empty() ? "1" : properties["Major Version"])); data[offset++] = static_cast(std::stoi(properties["Minor Version"].empty() ? "3" : properties["Minor Version"])); // KAG Size uint32_t kag = htobe32(std::stoi(properties["KAG Size"].empty() ? "1" : properties["KAG Size"])); std::memcpy(data.data() + offset, &kag, 4); offset += 4; // This/Previous/Footer uint64_t thisPart = htobe64(std::stoull(properties["This Partition"].empty() ? "0" : properties["This Partition"])); std::memcpy(data.data() + offset, &thisPart, 8); offset += 8; uint64_t prevPart = htobe64(std::stoull(properties["Previous Partition"].empty() ? "0" : properties["Previous Partition"])); std::memcpy(data.data() + offset, &prevPart, 8); offset += 8; uint64_t footPart = htobe64(std::stoull(properties["Footer Partition"].empty() ? "0" : properties["Footer Partition"])); std::memcpy(data.data() + offset, &footPart, 8); offset += 8; // Header/Index Byte Count uint64_t headCount = htobe64(std::stoull(properties["Header Byte Count"].empty() ? "0" : properties["Header Byte Count"])); std::memcpy(data.data() + offset, &headCount, 8); offset += 8; uint64_t indexCount = htobe64(std::stoull(properties["Index Byte Count"].empty() ? "0" : properties["Index Byte Count"])); std::memcpy(data.data() + offset, &indexCount, 8); offset += 8; // Index SID uint32_t indexSid = htobe32(std::stoi(properties["Index SID"].empty() ? "0" : properties["Index SID"])); std::memcpy(data.data() + offset, &indexSid, 4); offset += 4; // Body Offset uint64_t bodyOff = htobe64(std::stoull(properties["Body Offset"].empty() ? "0" : properties["Body Offset"])); std::memcpy(data.data() + offset, &bodyOff, 8); offset += 8; // Body SID uint32_t bodySid = htobe32(std::stoi(properties["Body SID"].empty() ? "0" : properties["Body SID"])); std::memcpy(data.data() + offset, &bodySid, 4); offset += 4; // OP UL std::string opStr = properties["Operational Pattern UL"].empty() ? "06.0e.2b.34.04.01.01.0d.0d.01.02.01.01.02.00.00" : properties["Operational Pattern UL"]; parts = split(opStr, '.'); for (size_t i = 0; i < 16; ++i) { data[offset++] = static_cast(std::stoi(parts[i], nullptr, 16)); } // Essence Batch std::string ulsStr = properties["Essence Containers ULs"]; auto ulList = split(ulsStr, ','); uint32_t count = ulList.size(); uint32_t countBe = htobe32(count); std::memcpy(data.data() + offset, &countBe, 4); offset += 4; uint32_t lenBe = htobe32(16 * count); std::memcpy(data.data() + offset, &lenBe, 4); offset += 4; for (const auto& ul : ulList) { auto ulParts = split(ul, '.'); for (size_t i = 0; i < 16; ++i) { data[offset++] = static_cast(std::stoi(ulParts[i], nullptr, 16)); } } file.write(reinterpret_cast(data.data()), offset); std::cout << "Written minimal MXF to " << fp << std::endl; } private: std::vector split(const std::string& s, char delim) { std::vector result; std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { result.push_back(item); } return result; } }; // Example usage: // int main() { // MXFHandler handler("path/to/file.mxf"); // handler.printProperties(); // handler.write("new.mxf"); // return 0; // } // ===== end task-436 .MX ===== // ===== task-437 .MXF [C++] ===== #include #include #include #include #include #include class MXFParser { private: std::string filepath; std::map properties; // Use string for simplicity in printing public: MXFParser(const std::string& fp) : filepath(fp) {} void readAndPrint() { std::ifstream file(filepath, std::ios::binary); if (!file) { std::cout << "Failed to open file." << std::endl; return; } file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(reinterpret_cast(data.data()), size); // Find Header Key uint8_t headerKey[14] = {0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x01}; // Partial size_t offset = 0; bool found = false; for (; offset < size - 16; ++offset) { if (std::memcmp(&data[offset], headerKey, 14) == 0) { found = true; break; } } if (!found) { std::cout << "Invalid MXF: Header Partition Pack not found." << std::endl; return; } offset += 16; // BER Length (simple) uint8_t firstLen = data[offset++]; uint64_t length = 0; if (firstLen > 0x80) { int lenBytes = firstLen & 0x7F; for (int i = 0; i < lenBytes; ++i) { length = (length << 8) | data[offset++]; } } else { length = firstLen; } // Parse Value (big-endian macros) #define READ_U16() ((data[offset] << 8) | data[offset+1]); offset += 2; #define READ_U32() ((data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]); offset += 4; #define READ_U64() ((uint64_t)data[offset] << 56) | ((uint64_t)data[offset+1] << 48) | ((uint64_t)data[offset+2] << 40) | ((uint64_t)data[offset+3] << 32) | \ ((uint64_t)data[offset+4] << 24) | ((uint64_t)data[offset+5] << 16) | ((uint64_t)data[offset+6] << 8) | (uint64_t)data[offset+7]; offset += 8; properties["Major Version"] = std::to_string(READ_U16()); properties["Minor Version"] = std::to_string(READ_U16()); properties["KAG Size"] = std::to_string(READ_U32()); properties["This Partition Offset"] = std::to_string(READ_U64()); properties["Previous Partition Offset"] = std::to_string(READ_U64()); properties["Footer Partition Offset"] = std::to_string(READ_U64()); properties["Header Byte Count"] = std::to_string(READ_U64()); properties["Index Byte Count"] = std::to_string(READ_U64()); properties["Index SID"] = std::to_string(READ_U32()); properties["Body Offset"] = std::to_string(READ_U64()); properties["Body SID"] = std::to_string(READ_U32()); // OP UL std::stringstream opSs; for (int i = 0; i < 16; ++i) opSs << std::hex << std::setw(2) << std::setfill('0') << std::uppercase << (int)data[offset++] << " "; properties["Operational Pattern"] = opSs.str().substr(0, opSs.str().size() - 1); // Essence Containers uint32_t ecCount = READ_U32(); std::string ecs; for (uint32_t i = 0; i < ecCount; ++i) { std::stringstream ulSs; for (int j = 0; j < 16; ++j) ulSs << std::hex << std::setw(2) << std::setfill('0') << std::uppercase << (int)data[offset++] << " "; ecs += "[" + ulSs.str().substr(0, ulSs.str().size() - 1) + "] "; } properties["Essence Containers"] = ecs.empty() ? "[]" : ecs.substr(0, ecs.size() - 1); #undef READ_U16 #undef READ_U32 #undef READ_U64 // Print for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } void writeDummy(const std::string& outputPath = "dummy.mxf") { std::vector buffer(16 + 1 + 84); uint8_t key[16] = {0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x01,0x00,0x00}; std::memcpy(buffer.data(), key, 16); buffer[16] = 84; // Len size_t offset = 17; #define WRITE_U16(val) buffer[offset++] = (val >> 8) & 0xFF; buffer[offset++] = val & 0xFF; #define WRITE_U32(val) buffer[offset++] = (val >> 24) & 0xFF; buffer[offset++] = (val >> 16) & 0xFF; buffer[offset++] = (val >> 8) & 0xFF; buffer[offset++] = val & 0xFF; #define WRITE_U64(val) buffer[offset++] = (val >> 56) & 0xFF; buffer[offset++] = (val >> 48) & 0xFF; buffer[offset++] = (val >> 40) & 0xFF; buffer[offset++] = (val >> 32) & 0xFF; \ buffer[offset++] = (val >> 24) & 0xFF; buffer[offset++] = (val >> 16) & 0xFF; buffer[offset++] = (val >> 8) & 0xFF; buffer[offset++] = val & 0xFF; WRITE_U16(1); // Major WRITE_U16(3); // Minor WRITE_U32(1); // KAG WRITE_U64(0); // This WRITE_U64(0); // Prev WRITE_U64(0); // Footer WRITE_U64(0); // HeaderBC WRITE_U64(0); // IndexBC WRITE_U32(0); // IndexSID WRITE_U64(0); // BodyOffset WRITE_U32(0); // BodySID uint8_t opUL[16] = {0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x01,0x00}; std::memcpy(&buffer[offset], opUL, 16); offset += 16; WRITE_U32(0); // EC count #undef WRITE_U16 #undef WRITE_U32 #undef WRITE_U64 std::ofstream out(outputPath, std::ios::binary); out.write(reinterpret_cast(buffer.data()), buffer.size()); std::cout << "Dummy MXF written to " << outputPath << std::endl; } }; // Example usage: // int main() { // MXFParser parser("path/to/file.mxf"); // parser.readAndPrint(); // parser.writeDummy(); // return 0; // } // ===== end task-437 .MXF ===== // ===== task-438 .MYD [C] ===== #include #include #include #include typedef struct { char* filename; char** keys; char** values; int count; } MydFileHandler; MydFileHandler* myd_create(const char* filename) { MydFileHandler* handler = malloc(sizeof(MydFileHandler)); handler->filename = strdup(filename); handler->keys = NULL; handler->values = NULL; handler->count = 0; return handler; } void myd_read_and_decode(MydFileHandler* handler) { FILE* f = fopen(handler->filename, "r"); if (!f) return; char line[1024]; regex_t regex; regcomp(®ex, "(\\w+)\\s*\\((.*)\\)", REG_EXTENDED); regmatch_t matches[3]; while (fgets(line, sizeof(line), f)) { char* trimmed = line; while (*trimmed == ' ') trimmed++; if (strlen(trimmed) == 0 || trimmed[0] == '/' || strncmp(trimmed, "REM", 3) == 0 || trimmed[0] == '#' || strncmp(trimmed, "--", 2) == 0) continue; if (regexec(®ex, trimmed, 3, matches, 0) == 0) { char* key = strndup(trimmed + matches[1].rm_so, matches[1].rm_eo - matches[1].rm_so); char* value = strndup(trimmed + matches[2].rm_so, matches[2].rm_eo - matches[2].rm_so); // Remove quotes from value if (value[0] == '"' || value[0] == '\'') memmove(value, value + 1, strlen(value)); if (value[strlen(value) - 1] == '"' || value[strlen(value) - 1] == '\'') value[strlen(value) - 1] = '\0'; handler->keys = realloc(handler->keys, (handler->count + 1) * sizeof(char*)); handler->values = realloc(handler->values, (handler->count + 1) * sizeof(char*)); handler->keys[handler->count] = key; handler->values[handler->count] = value; handler->count++; } else if (strcspn(trimmed, " \t\n") == strlen(trimmed) && strlen(trimmed) > 0) { handler->keys = realloc(handler->keys, (handler->count + 1) * sizeof(char*)); handler->values = realloc(handler->values, (handler->count + 1) * sizeof(char*)); handler->keys[handler->count] = strdup(trimmed); handler->values[handler->count] = strdup("(no parameters)"); handler->count++; } } regfree(®ex); fclose(f); } void myd_print_properties(MydFileHandler* handler) { for (int i = 0; i < handler->count; i++) { printf("%s: %s\n", handler->keys[i], handler->values[i]); } } void myd_write(MydFileHandler* handler, const char* new_filename) { const char* file = new_filename ? new_filename : handler->filename; FILE* f = fopen(file, "w"); if (!f) return; for (int i = 0; i < handler->count; i++) { if (strcmp(handler->values[i], "(no parameters)") == 0) { fprintf(f, "%s\n", handler->keys[i]); } else { fprintf(f, "%s(\"%s\")\n", handler->keys[i], handler->values[i]); } } fclose(f); } void myd_destroy(MydFileHandler* handler) { for (int i = 0; i < handler->count; i++) { free(handler->keys[i]); free(handler->values[i]); } free(handler->keys); free(handler->values); free(handler->filename); free(handler); } // Example usage: // MydFileHandler* handler = myd_create("example.MYD"); // myd_read_and_decode(handler); // myd_print_properties(handler); // myd_write(handler, "modified.MYD"); // myd_destroy(handler); // ===== end task-438 .MYD ===== // ===== task-439 .MYI [C] ===== #include #include #include #include typedef struct { char *filename; // Properties (use a struct or map; for simplicity, individual vars) uint8_t file_version[4]; uint16_t options; uint16_t header_length; uint16_t state_info_length; uint16_t base_info_length; uint16_t base_pos; uint16_t key_parts; uint16_t unique_key_parts; uint8_t keys; uint8_t uniques; uint8_t language; uint8_t max_block_size_index; uint8_t fulltext_keys; uint8_t not_used; uint64_t split; uint64_t dellink; uint64_t auto_increment; // ... Add more } MYIParser; MYIParser* myi_parser_new(const char *filename) { MYIParser *parser = malloc(sizeof(MYIParser)); parser->filename = strdup(filename); FILE *f = fopen(filename, "rb"); if (!f) { free(parser); return NULL; } // Read header fread(parser->file_version, 1, 4, f); fread(&parser->options, 2, 1, f); fread(&parser->header_length, 2, 1, f); fread(&parser->state_info_length, 2, 1, f); fread(&parser->base_info_length, 2, 1, f); fread(&parser->base_pos, 2, 1, f); fread(&parser->key_parts, 2, 1, f); fread(&parser->unique_key_parts, 2, 1, f); fread(&parser->keys, 1, 1, f); fread(&parser->uniques, 1, 1, f); fread(&parser->language, 1, 1, f); fread(&parser->max_block_size_index, 1, 1, f); fread(&parser->fulltext_keys, 1, 1, f); fread(&parser->not_used, 1, 1, f); // State example fread(&parser->split, 8, 1, f); fread(&parser->dellink, 8, 1, f); fread(&parser->auto_increment, 8, 1, f); // ... Extend fclose(f); return parser; } void myi_parser_print(MYIParser *parser) { printf("file_version: [%u, %u, %u, %u]\n", parser->file_version[0], parser->file_version[1], parser->file_version[2], parser->file_version[3]); printf("options: %u\n", parser->options); // ... Print all } void myi_parser_write(MYIParser *parser, const char *new_filename) { FILE *f = fopen(new_filename, "wb"); if (!f) return; fwrite(parser->file_version, 1, 4, f); fwrite(&parser->options, 2, 1, f); // ... Write all fclose(f); } void myi_parser_free(MYIParser *parser) { free(parser->filename); free(parser); } // Usage // int main() { // MYIParser *parser = myi_parser_new("example.MYI"); // if (parser) { // myi_parser_print(parser); // myi_parser_write(parser, "modified.MYI"); // myi_parser_free(parser); // } // return 0; // } // ===== end task-439 .MYI ===== // ===== task-440 .NB [C++] ===== #include #include #include #include #include class NBFileHandler { private: std::string filepath; std::string content; std::map properties; public: NBFileHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::in); if (!file) throw std::runtime_error("Failed to open file"); std::string line; content.clear(); while (std::getline(file, line)) { content += line + "\n"; } file.close(); decodeProperties(); } void decodeProperties() { if (content.empty()) throw std::runtime_error("No content loaded"); properties["File Extension"] = ".nb"; properties["MIME Type"] = "application/vnd.wolfram.mathematica"; bool isAscii = true; for (char c : content) if (static_cast(c) > 127) { isAscii = false; break; } properties["Encoding"] = isAscii ? "7-bit ASCII" : "Unknown"; properties["Human-Readable"] = "Yes"; properties["Cross-Platform Compatibility"] = "Yes"; properties["Newline Convention"] = content.find("\r\n") != std::string::npos ? "CR+LF (Windows)" : "LF (Unix/macOS)"; std::smatch match; std::regex_search(content, match, std::regex(R"(\(\* CreatedBy='(.*?)' \*\))")); properties["CreatedBy Metadata"] = match.size() > 1 ? match[1] : "Not found"; std::regex_search(content, match, std::regex(R"(\(\*CacheID: (.*?) \*\))")); properties["CacheID"] = match.size() > 1 ? match[1] : "Not found"; std::regex_search(content, match, std::regex(R"(\(\* Internal cache information \*\)([\s\S]*?)\(\* End of internal cache information \*\))")); properties["File Outline Cache"] = match.size() > 1 ? std::regex_replace(match[1].str(), std::regex("\n"), " ") : "None"; // Trimmed properties["Notebook Expression Structure"] = "Notebook[{...}] (simplified)"; int cellCount = 0; size_t pos = 0; while ((pos = content.find("Cell[", pos)) != std::string::npos) { cellCount++; pos += 5; } properties["Number of Cells (approximate)"] = std::to_string(cellCount); properties["Security Features"] = content.find("DynamicUpdatingEnabled") != std::string::npos ? "Present" : "Not detected"; properties["Compression Support"] = content.find("Compress[") != std::string::npos ? "Inline compression detected" : "None detected"; } void printProperties() const { if (properties.empty()) throw std::runtime_error("Properties not decoded"); for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& newFilepath, const std::string& updateCreatedBy = "") const { if (content.empty()) throw std::runtime_error("No content loaded"); std::string newContent = content; if (!updateCreatedBy.empty()) { std::regex_replace(std::back_inserter(newContent), content.begin(), content.end(), std::regex(R"(\(\* CreatedBy='(.*?)' \*\))"), "(* CreatedBy='" + updateCreatedBy + "' *)"); } std::ofstream file(newFilepath, std::ios::out); if (!file) throw std::runtime_error("Failed to write file"); file << newContent; file.close(); } }; // Example usage: // int main() { // try { // NBFileHandler handler("example.nb"); // handler.read(); // handler.printProperties(); // handler.write("modified.nb", "Mathematica 14.1"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-440 .NB ===== // ===== task-441 .NC [C++] ===== #include #include #include #include #include #include #include // For bigendian, assume available or use htobe32 etc. class NetCDFHandler { private: std::string filepath; std::map properties; // Use std::any for mixed types public: NetCDFHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) throw std::runtime_error("Cannot open file"); auto size = file.tellg(); file.seekg(0); std::vector data(size); file.read(data.data(), size); parse(data.data()); } void parse(const char* data) { const char* ptr = data; std::string magic(ptr, 3); ptr += 3; if (magic != "CDF") throw std::runtime_error("Not a NetCDF file"); properties["magic"] = std::string("CDF"); uint8_t version = *reinterpret_cast(ptr++); if (version != 1) throw std::runtime_error("Only Classic format supported"); properties["version"] = version; uint32_t numrecs = be32toh(*reinterpret_cast(ptr)); ptr += 4; properties["numrecs"] = numrecs; // Dimensions uint32_t dim_tag = be32toh(*reinterpret_cast(ptr)); ptr += 4; std::vector> dims; if (dim_tag == 10) { uint32_t nelems = be32toh(*reinterpret_cast(ptr)); ptr += 4; for (uint32_t i = 0; i < nelems; ++i) { uint32_t name_len = be32toh(*reinterpret_cast(ptr)); ptr += 4; std::string name(ptr, name_len); ptr += name_len; ptr += pad(name_len); uint32_t length = be32toh(*reinterpret_cast(ptr)); ptr += 4; std::map dim; dim["name"] = name; dim["length"] = length; dims.push_back(dim); } } else if (dim_tag != 0) throw std::runtime_error("Invalid dim tag"); properties["dimensions"] = dims; // Global attributes uint32_t gatt_tag = be32toh(*reinterpret_cast(ptr)); ptr += 4; std::vector> global_attrs; if (gatt_tag == 12) { uint32_t nelems = be32toh(*reinterpret_cast(ptr)); ptr += 4; for (uint32_t i = 0; i < nelems; ++i) { auto [attr, new_ptr] = parse_attr(ptr); global_attrs.push_back(attr); ptr = new_ptr; } } else if (gatt_tag != 0) throw std::runtime_error("Invalid gatt tag"); properties["global_attributes"] = global_attrs; // Variables uint32_t var_tag = be32toh(*reinterpret_cast(ptr)); ptr += 4; std::vector> vars; if (var_tag == 11) { uint32_t nelems = be32toh(*reinterpret_cast(ptr)); ptr += 4; for (uint32_t i = 0; i < nelems; ++i) { uint32_t name_len = be32toh(*reinterpret_cast(ptr)); ptr += 4; std::string name(ptr, name_len); ptr += name_len; ptr += pad(name_len); uint32_t rank = be32toh(*reinterpret_cast(ptr)); ptr += 4; std::vector dimids; for (uint32_t j = 0; j < rank; ++j) { dimids.push_back(be32toh(*reinterpret_cast(ptr))); ptr += 4; } uint32_t vatt_tag = be32toh(*reinterpret_cast(ptr)); ptr += 4; std::vector> var_attrs; if (vatt_tag == 12) { uint32_t nelems_attr = be32toh(*reinterpret_cast(ptr)); ptr += 4; for (uint32_t j = 0; j < nelems_attr; ++j) { auto [attr, new_ptr] = parse_attr(ptr); var_attrs.push_back(attr); ptr = new_ptr; } } else if (vatt_tag != 0) throw std::runtime_error("Invalid vatt tag"); uint32_t type = be32toh(*reinterpret_cast(ptr)); ptr += 4; uint32_t vsize = be32toh(*reinterpret_cast(ptr)); ptr += 4; uint32_t begin = be32toh(*reinterpret_cast(ptr)); ptr += 4; std::map var; var["name"] = name; var["rank"] = rank; var["dimids"] = dimids; var["attributes"] = var_attrs; var["type"] = type_to_string(type); var["vsize"] = vsize; var["begin"] = begin; vars.push_back(var); } } else if (var_tag != 0) throw std::runtime_error("Invalid var tag"); properties["variables"] = vars; } int pad(uint32_t len) { return (4 - (len % 4)) % 4; } std::string type_to_string(uint32_t type) { switch (type) { case 1: return "NC_BYTE"; case 2: return "NC_CHAR"; case 3: return "NC_SHORT"; case 4: return "NC_INT"; case 5: return "NC_FLOAT"; case 6: return "NC_DOUBLE"; default: return "Unknown"; } } int get_type_size(uint32_t type) { switch (type) { case 1: case 2: return 1; case 3: return 2; case 4: case 5: return 4; case 6: return 8; default: return 0; } } std::pair, const char*> parse_attr(const char* ptr) { std::map attr; uint32_t name_len = be32toh(*reinterpret_cast(ptr)); ptr += 4; std::string name(ptr, name_len); ptr += name_len; ptr += pad(name_len); uint32_t type = be32toh(*reinterpret_cast(ptr)); ptr += 4; uint32_t nelems = be32toh(*reinterpret_cast(ptr)); ptr += 4; std::vector values; int size = get_type_size(type); for (uint32_t i = 0; i < nelems; ++i) { std::any val = read_value(ptr, type); values.push_back(val); ptr += size; } ptr += pad(nelems * size); attr["name"] = name; attr["type"] = type_to_string(type); attr["values"] = values; return {attr, ptr}; } std::any read_value(const char* ptr, uint32_t type) { switch (type) { case 1: return static_cast(*ptr); case 2: return static_cast(*ptr); case 3: return static_cast(be16toh(*reinterpret_cast(ptr))); case 4: return static_cast(be32toh(*reinterpret_cast(ptr))); case 5: { // Float uint32_t i = be32toh(*reinterpret_cast(ptr)); float f; std::memcpy(&f, &i, sizeof(float)); return f; } case 6: { // Double uint64_t i = be64toh(*reinterpret_cast(ptr)); double d; std::memcpy(&d, &i, sizeof(double)); return d; } default: return 0; } } void print_properties() { // Implement printing recursively, e.g., as JSON-like std::cout << "{\n"; std::cout << " \"magic\": \"" << std::any_cast(properties["magic"]) << "\",\n"; std::cout << " \"version\": " << static_cast(std::any_cast(properties["version"])) << ",\n"; std::cout << " \"numrecs\": " << std::any_cast(properties["numrecs"]) << ",\n"; // Add printing for dims, attrs, vars similarly (omitted for brevity; use recursion or loops) std::cout << "}\n"; } void write(const std::string& new_filepath) { std::ofstream file(new_filepath, std::ios::binary); if (!file) throw std::runtime_error("Cannot write file"); file.write("CDF", 3); uint8_t version = std::any_cast(properties["version"]); file.write(reinterpret_cast(&version), 1); uint32_t numrecs_be = htobe32(std::any_cast(properties["numrecs"])); file.write(reinterpret_cast(&numrecs_be), 4); // Dimensions, attrs, vars writing similar to above, with htobe32 etc. (omitted for brevity) // Header only. } }; // Example // int main() { // NetCDFHandler handler("example.nc"); // handler.read(); // handler.print_properties(); // handler.write("new.nc"); // return 0; // } // ===== end task-441 .NC ===== // ===== task-442 .NCD [C++] ===== #include #include #include #include #include #include struct Dim { std::string name; uint32_t length; }; struct Attr { std::string name; uint32_t type; std::vector values; // Simplify to double for print }; struct Var { std::string name; uint32_t rank; std::vector dimids; std::vector attrs; uint32_t type; uint32_t vsize; uint32_t begin; }; class NCDFile { public: NCDFile(const std::string& fn) : filename(fn) {} void read() { std::ifstream f(filename, std::ios::binary | std::ios::ate); auto size = f.tellg(); f.seekg(0); data.resize(size); f.read(data.data(), size); offset = 0; auto unpack32 = [&]() -> uint32_t { uint32_t val; std::memcpy(&val, data.data() + offset, 4); offset += 4; return __builtin_bswap32(val); // Big-endian }; auto readString = [&]() -> std::string { uint32_t len = unpack32(); std::string str(data.begin() + offset, data.begin() + offset + len); offset += len + (4 - len % 4) % 4; return str; }; auto readList = [&](uint32_t tag, auto itemReader) -> std::vector { uint32_t listTag = unpack32(); if (listTag == 0) return {}; if (listTag != tag) throw std::runtime_error("Invalid tag"); uint32_t count = unpack32(); std::vector items; for (uint32_t i = 0; i < count; i++) items.push_back(itemReader()); return items; }; auto readDim = [&]() { Dim d; d.name = readString(); d.length = unpack32(); return d; }; auto readAttr = [&]() { Attr a; a.name = readString(); a.type = unpack32(); uint32_t count = unpack32(); a.values.resize(count); int size = (int[]){1,1,2,4,4,8}[a.type-1]; for (uint32_t i = 0; i < count; i++) { double val; std::memcpy(&val, data.data() + offset, size); a.values[i] = val; // Simplified offset += size; } offset += (4 - (count * size % 4)) % 4; return a; }; auto readVar = [&]() { Var v; v.name = readString(); v.rank = unpack32(); v.dimids.resize(v.rank); for (uint32_t i = 0; i < v.rank; i++) v.dimids[i] = unpack32(); v.attrs = readList(12, readAttr); v.type = unpack32(); v.vsize = unpack32(); v.begin = unpack32(); // classic return v; }; magic = std::string(data.begin(), data.begin() + 3); offset = 3; version = data[offset++]; numrecs = unpack32(); dims = readList(10, readDim); gattrs = readList(12, readAttr); vars = readList(11, readVar); } void printProperties() { std::cout << "Magic: " << magic << std::endl; std::cout << "Version: " << version << std::endl; std::cout << "Numrecs: " << (numrecs == 0xFFFFFFFF ? "Streaming" : std::to_string(numrecs)) << std::endl; std::cout << "Dimensions:" << std::endl; for (const auto& d : dims) std::cout << " - " << d.name << ": " << d.length << std::endl; std::cout << "Global Attributes:" << std::endl; for (const auto& a : gattrs) { std::cout << " - " << a.name << " (type " << a.type << "): "; for (double v : a.values) std::cout << v << " "; std::cout << std::endl; } std::cout << "Variables:" << std::endl; for (const auto& v : vars) { std::cout << " - " << v.name << " (type " << v.type << ", rank " << v.rank << ", dimids ["; for (uint32_t id : v.dimids) std::cout << id << " "; std::cout << "], vsize " << v.vsize << ", begin " << v.begin << ")" << std::endl; std::cout << " Attributes: "; for (const auto& a : v.attrs) std::cout << a.name << " "; std::cout << std::endl; } } void write(const std::string& outFilename) { std::ofstream f(outFilename, std::ios::binary); auto pack32 = [&](uint32_t val) { val = __builtin_bswap32(val); f.write(reinterpret_cast(&val), 4); }; auto writeString = [&](const std::string& str) { pack32(str.length()); f.write(str.data(), str.length()); int pad = (4 - str.length() % 4) % 4; f.write("\0\0\0", pad); }; f.write("CDF", 3); f.put(1); // version pack32(0); // numrecs pack32(10); // dim_list pack32(1); // count writeString("time"); pack32(0); // length pack32(12); pack32(0); // gatt absent pack32(11); // var_list pack32(1); // count writeString("temp"); pack32(1); // rank pack32(0); // dimid pack32(12); pack32(0); // vatt absent pack32(5); // float pack32(0); // vsize pack32(100); // begin dummy // No data } private: std::string filename; std::string magic; uint8_t version; uint32_t numrecs; std::vector dims; std::vector gattrs; std::vector vars; std::vector data; size_t offset; }; int main(int argc, char** argv) { if (argc < 2) { std::cout << "Usage: " << argv[0] << " " << std::endl; return 1; } NCDFile ncd(argv[1]); ncd.read(); ncd.printProperties(); ncd.write("output.ncd"); return 0; } // ===== end task-442 .NCD ===== // ===== task-443 .NDK [C++] ===== #include #include #include #include #include #include #include class NDKFile { private: std::vector> events; // Using string for simplicity public: void read(const std::string& filename) { std::ifstream file(filename); std::string line; std::vector lines; while (std::getline(file, line)) { lines.push_back(line); } for (size_t i = 0; i < lines.size(); i += 5) { if (i + 4 >= lines.size()) break; std::string line1 = lines[i]; std::istringstream iss2(lines[i+1]); std::vector line2; std::string token; while (iss2 >> token) line2.push_back(token); std::istringstream iss3(lines[i+2]); std::vector line3; while (iss3 >> token) line3.push_back(token); std::istringstream iss4(lines[i+3]); std::vector line4; while (iss4 >> token) line4.push_back(token); std::istringstream iss5(lines[i+4]); std::vector line5; while (iss5 >> token) line5.push_back(token); auto event = parseEvent(line1, line2, line3, line4, line5); events.push_back(event); } } std::map parseEvent(const std::string& line1, const std::vector& line2, const std::vector& line3, const std::vector& line4, const std::vector& line5) { std::map event; // Parse line 1 event["hyp_cat"] = line1.substr(0,4); event["year"] = line1.substr(5,4); event["month"] = line1.substr(10,2); event["day"] = line1.substr(13,2); event["hour"] = line1.substr(16,2); event["minute"] = line1.substr(19,2); event["second"] = line1.substr(22,5); event["lat"] = line1.substr(27,7); event["lon"] = line1.substr(34,8); event["depth"] = line1.substr(42,5); event["mb"] = line1.substr(48,3); event["ms"] = line1.substr(52,3); event["region"] = line1.substr(56); // Parse line 2 event["event_name"] = line2[0]; event["body_stations"] = line2[2]; event["body_channels"] = line2[3]; event["body_components"] = line2[4]; event["surface_stations"] = line2[6]; event["surface_channels"] = line2[7]; event["surface_components"] = line2[8]; event["mantle_stations"] = line2[10]; event["mantle_channels"] = line2[11]; event["mantle_components"] = line2[12]; event["cmt_type"] = line2[14]; event["inv_type"] = (line2.size() > 15) ? line2[15] : ""; // Parse line 3 if (line3[0] == "CENTROID:") { event["centroid_time_offset"] = line3[1]; event["centroid_time_offset_err"] = line3[2]; event["centroid_lat"] = line3[3]; event["centroid_lat_err"] = line3[4]; event["centroid_lon"] = line3[5]; event["centroid_lon_err"] = line3[6]; event["centroid_depth"] = line3[7]; size_t idx = 8; if (line3[idx] == "FIXED" || line3[idx] == "FREE") { event["depth_type"] = line3[idx]; idx += 1; } else { event["centroid_depth_err"] = line3[idx]; idx += 1; event["depth_type"] = line3[idx]; idx += 1; } if (idx < line3.size() && line3[idx] == "BD:") { event["body_depth"] = line3[idx+1]; } } else { event["centroid_depth_err"] = "0"; event["body_depth"] = "0"; } // Parse line 4 event["exponent"] = line4[0]; event["mrr"] = line4[1]; event["mrr_err"] = line4[2]; event["mtt"] = line4[3]; event["mtt_err"] = line4[4]; event["mpp"] = line4[5]; event["mpp_err"] = line4[6]; event["mrt"] = line4[7]; event["mrt_err"] = line4[8]; event["mrp"] = line4[9]; event["mrp_err"] = line4[10]; event["mtp"] = line4[11]; event["mtp_err"] = line4[12]; // Parse line 5 event["version"] = line5[0]; event["principal_axis1_eigenvalue"] = line5[1]; event["principal_axis1_plunge"] = line5[2]; event["principal_axis1_azimuth"] = line5[3]; event["principal_axis2_eigenvalue"] = line5[4]; event["principal_axis2_plunge"] = line5[5]; event["principal_axis2_azimuth"] = line5[6]; event["principal_axis3_eigenvalue"] = line5[7]; event["principal_axis3_plunge"] = line5[8]; event["principal_axis3_azimuth"] = line5[9]; event["scalar_moment"] = line5[10]; event["nodal_plane1_strike"] = line5[11]; event["nodal_plane1_dip"] = line5[12]; event["nodal_plane1_rake"] = line5[13]; event["nodal_plane2_strike"] = line5[14]; event["nodal_plane2_dip"] = line5[15]; event["nodal_plane2_rake"] = line5[16]; return event; } void printProperties() { for (const auto& event : events) { std::cout << "Event: " << event.at("event_name") << std::endl; for (const auto& pair : event) { std::cout << pair.first << ": " << pair.second << std::endl; } std::cout << std::endl; } } void write(const std::string& filename) { std::ofstream file(filename); for (const auto& event : events) { // Line 1 (approximate formatting) file << std::left << std::setw(4) << event.at("hyp_cat") << std::setw(5) << event.at("year") << std::setw(3) << event.at("month") << std::setw(3) << event.at("day") << std::setw(3) << event.at("hour") << std::setw(3) << event.at("minute") << std::fixed << std::setprecision(1) << std::setw(6) << std::stof(event.at("second")) << std::setprecision(2) << std::setw(8) << std::stof(event.at("lat")) << std::setw(9) << std::stof(event.at("lon")) << std::setprecision(1) << std::setw(6) << std::stof(event.at("depth")) << std::setw(4) << std::stof(event.at("mb")) << std::setw(4) << std::stof(event.at("ms")) << " " << event.at("region") << std::endl; // Line 2 file << event.at("event_name") << " BW: " << event.at("body_stations") << " " << event.at("body_channels") << " " << event.at("body_components") << " SW: " << event.at("surface_stations") << " " << event.at("surface_channels") << " " << event.at("surface_components") << " MW: " << event.at("mantle_stations") << " " << event.at("mantle_channels") << " " << event.at("mantle_components") << " TMTC: " << event.at("cmt_type") << " " << event.at("inv_type") << std::endl; // Line 3 file << "CENTROID: " << std::setw(4) << std::setprecision(1) << std::stof(event.at("centroid_time_offset")) << " " << std::setw(3) << std::stof(event.at("centroid_time_offset_err")) << " " << std::setw(6) << std::setprecision(2) << std::stof(event.at("centroid_lat")) << " " << std::setw(4) << std::stof(event.at("centroid_lat_err")) << " " << std::setw(7) << std::stof(event.at("centroid_lon")) << " " << std::setw(4) << std::stof(event.at("centroid_lon_err")) << " " << std::setw(4) << std::setprecision(1) << std::stof(event.at("centroid_depth")); if (std::stof(event.at("centroid_depth_err")) > 0) { file << " " << std::setw(3) << std::stof(event.at("centroid_depth_err")); } file << " " << event.at("depth_type") << " BD: " << std::setw(4) << std::stof(event.at("body_depth")) << std::endl; // Line 4 file << event.at("exponent") << " " << std::setw(5) << std::setprecision(2) << std::stof(event.at("mrr")) << " " << std::setw(4) << std::stof(event.at("mrr_err")) << " " << std::setw(5) << std::stof(event.at("mtt")) << " " << std::setw(4) << std::stof(event.at("mtt_err")) << " " << std::setw(5) << std::stof(event.at("mpp")) << " " << std::setw(4) << std::stof(event.at("mpp_err")) << " " << std::setw(5) << std::stof(event.at("mrt")) << " " << std::setw(4) << std::stof(event.at("mrt_err")) << " " << std::setw(5) << std::stof(event.at("mrp")) << " " << std::setw(4) << std::stof(event.at("mrp_err")) << " " << std::setw(5) << std::stof(event.at("mtp")) << " " << std::setw(4) << std::stof(event.at("mtp_err")) << std::endl; // Line 5 file << event.at("version") << " " << std::setw(5) << std::stof(event.at("principal_axis1_eigenvalue")) << " " << std::setw(2) << event.at("principal_axis1_plunge") << " " << std::setw(3) << event.at("principal_axis1_azimuth") << " " << std::setw(5) << std::stof(event.at("principal_axis2_eigenvalue")) << " " << std::setw(2) << event.at("principal_axis2_plunge") << " " << std::setw(3) << event.at("principal_axis2_azimuth") << " " << std::setw(5) << std::stof(event.at("principal_axis3_eigenvalue")) << " " << std::setw(2) << event.at("principal_axis3_plunge") << " " << std::setw(3) << event.at("principal_axis3_azimuth") << " " << std::setw(5) << std::stof(event.at("scalar_moment")) << " " << std::setw(3) << event.at("nodal_plane1_strike") << " " << std::setw(2) << event.at("nodal_plane1_dip") << " " << std::setw(4) << event.at("nodal_plane1_rake") << " " << std::setw(3) << event.at("nodal_plane2_strike") << " " << std::setw(2) << event.at("nodal_plane2_dip") << " " << std::setw(4) << event.at("nodal_plane2_rake") << std::endl; } } }; // Example usage: // int main() { // NDKFile ndk; // ndk.read("example.ndk"); // ndk.printProperties(); // ndk.write("output.ndk"); // return 0; // } // ===== end task-443 .NDK ===== // ===== task-444 .NDS [C++] ===== #include #include #include #include #include class NDSFile { private: std::string filename; std::fstream file; uint8_t header[0x170]; std::map properties; // Use string for simplicity in printing public: NDSFile(const std::string& fn) : filename(fn) { file.open(filename, std::ios::in | std::ios::out | std::ios::binary); if (file) { file.read(reinterpret_cast(header), 0x170); decodeProperties(); } } ~NDSFile() { if (file.is_open()) file.close(); } void decodeProperties() { properties.clear(); char temp[13]; std::memcpy(temp, header + 0x000, 12); temp[12] = '\0'; properties["Game Title"] = std::string(temp); std::memcpy(temp, header + 0x00C, 4); temp[4] = '\0'; properties["Game Code"] = std::string(temp); std::memcpy(temp, header + 0x010, 2); temp[2] = '\0'; properties["Maker Code"] = std::string(temp); properties["Unit Code"] = std::to_string(header[0x012]); // Add all other properties similarly, using reinterpret_cast(header + offset)[0] for ints, etc. // For brevity, assuming similar pattern for all } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void writeProperty(const std::string& key, const std::string& value) { // Simplified; find offset, write based on type int offset = getPropertyOffset(key); if (offset != -1) { // Example for byte header[offset] = static_cast(std::stoi(value)); file.seekp(0); file.write(reinterpret_cast(header), 0x170); decodeProperties(); } } int getPropertyOffset(const std::string& key) { if (key == "Unit Code") return 0x012; // Add others return -1; } }; // Usage example: // int main() { // NDSFile nds("example.nds"); // nds.printProperties(); // nds.writeProperty("Unit Code", "0"); // return 0; // } // ===== end task-444 .NDS ===== // ===== task-445 .NEF [C++] ===== #include #include #include #include #include #include class NefParser { private: std::string filepath; std::vector data; std::map properties; bool isBigEndian = true; public: NefParser(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary); if (file) { data.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); decode(); } } void decode() { // TIFF Header std::string byteOrder(reinterpret_cast(&data[0]), 2); isBigEndian = (byteOrder == "MM"); uint16_t magic = getUint16(2); properties["MagicNumber"] = std::to_string(magic); uint32_t ifdOffset = getUint32(4); properties["FirstIFDOffset"] = std::to_string(ifdOffset); // Parse IFD0 size_t offset = ifdOffset; uint16_t numEntries = getUint16(offset); offset += 2; for (uint16_t i = 0; i < numEntries; ++i) { uint16_t tag = getUint16(offset); uint16_t type = getUint16(offset + 2); uint32_t count = getUint32(offset + 4); uint32_t valOffset = getUint32(offset + 8); if (tag == 0x0100) properties["ImageWidth"] = std::to_string(getUint32(valOffset)); if (tag == 0x0101) properties["ImageHeight"] = std::to_string(getUint32(valOffset)); if (tag == 0x0102) properties["BitsPerSample"] = std::to_string(getUint16(valOffset)); if (tag == 0x0103) properties["Compression"] = std::to_string(getUint16(valOffset)); if (tag == 0x010F) properties["Make"] = getString(valOffset, count); if (tag == 0x0110) properties["Model"] = getString(valOffset, count); if (tag == 0x001D) properties["SerialNumber"] = getString(valOffset, count); // Add more... offset += 12; } } uint16_t getUint16(size_t offset) { uint16_t val; if (isBigEndian) { val = (data[offset] << 8) | data[offset + 1]; } else { val = (data[offset + 1] << 8) | data[offset]; } return val; } uint32_t getUint32(size_t offset) { uint32_t val; if (isBigEndian) { val = (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]; } else { val = (data[offset + 3] << 24) | (data[offset + 2] << 16) | (data[offset + 1] << 8) | data[offset]; } return val; } std::string getString(size_t offset, uint32_t count) { std::string str(reinterpret_cast(&data[offset]), count - 1); // Trim null return str; } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& newFilepath, const std::string& modifyTag, const std::string& newValue) { // Demo: copy std::ofstream out(newFilepath, std::ios::binary); out.write(reinterpret_cast(data.data()), data.size()); std::cout << "File written; modification not implemented in demo." << std::endl; } }; // Usage: // int main() { // NefParser parser("sample.nef"); // parser.read(); // parser.printProperties(); // parser.write("modified.nef", "SerialNumber", "NEW123"); // return 0; // } // ===== end task-445 .NEF ===== // ===== task-446 .NEO [C] ===== #include #include #include #include typedef struct { char* filepath; uint16_t flag; uint16_t resolution; uint16_t palette[16]; char filename[13]; uint16_t color_anim_limits; uint16_t color_anim_speed_dir; uint16_t color_steps; uint16_t x_offset; uint16_t y_offset; uint16_t width; uint16_t height; uint8_t reserved[66]; uint8_t* picture_data; } NeoFile; NeoFile* neo_create(const char* filepath) { NeoFile* neo = (NeoFile*)malloc(sizeof(NeoFile)); neo->filepath = strdup(filepath); neo->picture_data = NULL; return neo; } void neo_destroy(NeoFile* neo) { free(neo->filepath); if (neo->picture_data) free(neo->picture_data); free(neo); } int neo_read(NeoFile* neo) { FILE* f = fopen(neo->filepath, "rb"); if (!f) return -1; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); if (size != 32128) { fclose(f); return -1; } uint8_t* data = (uint8_t*)malloc(32128); fread(data, 1, 32128, f); fclose(f); neo->flag = (data[0] << 8) | data[1]; neo->resolution = (data[2] << 8) | data[3]; for (int i = 0; i < 16; i++) { neo->palette[i] = (data[4 + i*2] << 8) | data[4 + i*2 + 1]; } memcpy(neo->filename, &data[36], 12); neo->filename[12] = '\0'; // Trim trailing spaces for (int i = 11; i >= 0; i--) { if (neo->filename[i] != ' ') break; neo->filename[i] = '\0'; } neo->color_anim_limits = (data[48] << 8) | data[49]; neo->color_anim_speed_dir = (data[50] << 8) | data[51]; neo->color_steps = (data[52] << 8) | data[53]; neo->x_offset = (data[54] << 8) | data[55]; neo->y_offset = (data[56] << 8) | data[57]; neo->width = (data[58] << 8) | data[59]; neo->height = (data[60] << 8) | data[61]; memcpy(neo->reserved, &data[62], 66); neo->picture_data = (uint8_t*)malloc(32000); memcpy(neo->picture_data, &data[128], 32000); free(data); return 0; } void neo_print_properties(const NeoFile* neo) { printf("Flag: %u\n", neo->flag); printf("Resolution: %u\n", neo->resolution); printf("Palette:\n"); for (int i = 0; i < 16; i++) { uint16_t color = neo->palette[i]; uint8_t r = (color >> 8) & 0x7; uint8_t g = (color >> 4) & 0x7; uint8_t b = color & 0x7; printf(" Color %d: R=%u, G=%u, B=%u (raw: 0x%X)\n", i, r, g, b, color); } printf("Filename: %s\n", neo->filename); printf("Color animation limits: %u\n", neo->color_anim_limits); printf("Color animation speed and direction: %u\n", neo->color_anim_speed_dir); printf("Number of color steps: %u\n", neo->color_steps); printf("Image X offset: %u\n", neo->x_offset); printf("Image Y offset: %u\n", neo->y_offset); printf("Image width: %u\n", neo->width); printf("Image height: %u\n", neo->height); printf("Reserved size: 66 bytes\n"); printf("Picture data size: 32000 bytes\n"); } int neo_write(const NeoFile* neo, const char* new_filepath) { const char* path = new_filepath ? new_filepath : neo->filepath; FILE* f = fopen(path, "wb"); if (!f) return -1; uint8_t header[128]; memset(header, 0, 128); header[0] = (neo->flag >> 8) & 0xFF; header[1] = neo->flag & 0xFF; header[2] = (neo->resolution >> 8) & 0xFF; header[3] = neo->resolution & 0xFF; for (int i = 0; i < 16; i++) { header[4 + i*2] = (neo->palette[i] >> 8) & 0xFF; header[4 + i*2 + 1] = neo->palette[i] & 0xFF; } size_t fn_len = strlen(neo->filename); memcpy(&header[36], neo->filename, fn_len < 12 ? fn_len : 12); for (int i = fn_len; i < 12; i++) { header[36 + i] = ' '; } header[48] = (neo->color_anim_limits >> 8) & 0xFF; header[49] = neo->color_anim_limits & 0xFF; header[50] = (neo->color_anim_speed_dir >> 8) & 0xFF; header[51] = neo->color_anim_speed_dir & 0xFF; header[52] = (neo->color_steps >> 8) & 0xFF; header[53] = neo->color_steps & 0xFF; header[54] = (neo->x_offset >> 8) & 0xFF; header[55] = neo->x_offset & 0xFF; header[56] = (neo->y_offset >> 8) & 0xFF; header[57] = neo->y_offset & 0xFF; header[58] = (neo->width >> 8) & 0xFF; header[59] = neo->width & 0xFF; header[60] = (neo->height >> 8) & 0xFF; header[61] = neo->height & 0xFF; memcpy(&header[62], neo->reserved, 66); fwrite(header, 1, 128, f); fwrite(neo->picture_data, 1, 32000, f); fclose(f); return 0; } // Example usage: // int main() { // NeoFile* neo = neo_create("example.neo"); // if (neo_read(neo) == 0) { // neo_print_properties(neo); // neo_write(neo, "output.neo"); // } // neo_destroy(neo); // return 0; // } // ===== end task-446 .NEO ===== // ===== task-447 .NET [C] ===== #include #include #include #include #define MAX_LINES 10000 #define MAX_PARTS 10 typedef struct { char **header; int header_count; struct Texture { int z_offset; char *filename; } *textures; int textures_count; struct LitTexture { char *filename; } *lit_textures; int lit_textures_count; struct Scale { float scale; } *scales; int scales_count; struct RoadType { int subtype; float width; float length; int texture; float red; float green; float blue; } *road_types; int road_types_count; struct Segment { float near_lod; float far_lod; float start_lat; float start_vert; float start_tex; float end_lat; float end_vert; float end_tex; } *segments; int segments_count; struct SegmentHard { float near_lod; float far_lod; float start_lat; float start_vert; float start_tex; float end_lat; float end_vert; float end_tex; char *surface; } *segment_hards; int segment_hards_count; struct Wire { float near_lod; float far_lod; float lateral_offset; float vertical_offset; float droop; } *wires; int wires_count; struct Object { char *name; float lateral_offset; float rotation; int on_ground; float frequency; float offset; } *objects; int objects_count; int *require_evens; int require_evens_count; struct Car { int reverse; float lateral_offset; float velocity; float spawn_ratio; int traffic_type; } *cars; int cars_count; struct CarModel { char *name; float lateral_offset; float long_offset; float scale; } *car_models; int car_models_count; } NetFileHandler; NetFileHandler* net_file_handler_new() { NetFileHandler* handler = (NetFileHandler*)malloc(sizeof(NetFileHandler)); memset(handler, 0, sizeof(NetFileHandler)); return handler; } void net_file_handler_read(NetFileHandler* handler, const char* filepath) { FILE* f = fopen(filepath, "r"); if (!f) { perror("File not found"); return; } char line[1024]; while (fgets(line, sizeof(line), f)) { char* trimmed = line; while (isspace(*trimmed)) trimmed++; if (*trimmed == 0 || *trimmed == '#') continue; char parts[MAX_PARTS][256]; int part_count = 0; char* token = strtok(trimmed, " \t\n"); while (token && part_count < MAX_PARTS) { strcpy(parts[part_count++], token); token = strtok(NULL, " \t\n"); } char cmd[256]; strcpy(cmd, parts[0]); for (char* p = cmd; *p; p++) *p = toupper(*p); if (strcmp(cmd, "A") == 0 || strcmp(cmd, "800") == 0 || strcmp(cmd, "ROADS") == 0) { handler->header = (char**)realloc(handler->header, (handler->header_count + 1) * sizeof(char*)); handler->header[handler->header_count] = strdup(line); handler->header_count++; } else if (strcmp(cmd, "TEXTURE") == 0) { handler->textures = (struct Texture*)realloc(handler->textures, (handler->textures_count + 1) * sizeof(struct Texture)); handler->textures[handler->textures_count].z_offset = atoi(parts[1]); handler->textures[handler->textures_count].filename = strdup(parts[2]); handler->textures_count++; } else if (strcmp(cmd, "TEXTURE_LIT") == 0) { handler->lit_textures = (struct LitTexture*)realloc(handler->lit_textures, (handler->lit_textures_count + 1) * sizeof(struct LitTexture)); handler->lit_textures[handler->lit_textures_count].filename = strdup(parts[1]); handler->lit_textures_count++; } else if (strcmp(cmd, "SCALE") == 0) { handler->scales = (struct Scale*)realloc(handler->scales, (handler->scales_count + 1) * sizeof(struct Scale)); handler->scales[handler->scales_count].scale = atof(parts[1]); handler->scales_count++; } else if (strcmp(cmd, "ROAD_TYPE") == 0) { handler->road_types = (struct RoadType*)realloc(handler->road_types, (handler->road_types_count + 1) * sizeof(struct RoadType)); struct RoadType* rt = &handler->road_types[handler->road_types_count]; rt->subtype = atoi(parts[1]); rt->width = atof(parts[2]); rt->length = atof(parts[3]); rt->texture = atoi(parts[4]); rt->red = atof(parts[5]); rt->green = atof(parts[6]); rt->blue = atof(parts[7]); handler->road_types_count++; } else if (strcmp(cmd, "SEGMENT") == 0) { handler->segments = (struct Segment*)realloc(handler->segments, (handler->segments_count + 1) * sizeof(struct Segment)); struct Segment* seg = &handler->segments[handler->segments_count]; seg->near_lod = atof(parts[1]); seg->far_lod = atof(parts[2]); seg->start_lat = atof(parts[3]); seg->start_vert = atof(parts[4]); seg->start_tex = atof(parts[5]); seg->end_lat = atof(parts[6]); seg->end_vert = atof(parts[7]); seg->end_tex = atof(parts[8]); handler->segments_count++; } else if (strcmp(cmd, "SEGMENT_HARD") == 0) { handler->segment_hards = (struct SegmentHard*)realloc(handler->segment_hards, (handler->segment_hards_count + 1) * sizeof(struct SegmentHard)); struct SegmentHard* sh = &handler->segment_hards[handler->segment_hards_count]; sh->near_lod = atof(parts[1]); sh->far_lod = atof(parts[2]); sh->start_lat = atof(parts[3]); sh->start_vert = atof(parts[4]); sh->start_tex = atof(parts[5]); sh->end_lat = atof(parts[6]); sh->end_vert = atof(parts[7]); sh->end_tex = atof(parts[8]); sh->surface = strdup(parts[9]); handler->segment_hards_count++; } else if (strcmp(cmd, "WIRE") == 0) { handler->wires = (struct Wire*)realloc(handler->wires, (handler->wires_count + 1) * sizeof(struct Wire)); struct Wire* wire = &handler->wires[handler->wires_count]; wire->near_lod = atof(parts[1]); wire->far_lod = atof(parts[2]); wire->lateral_offset = atof(parts[3]); wire->vertical_offset = atof(parts[4]); wire->droop = atof(parts[5]); handler->wires_count++; } else if (strcmp(cmd, "OBJECT") == 0) { handler->objects = (struct Object*)realloc(handler->objects, (handler->objects_count + 1) * sizeof(struct Object)); struct Object* obj = &handler->objects[handler->objects_count]; obj->name = strdup(parts[1]); obj->lateral_offset = atof(parts[2]); obj->rotation = atof(parts[3]); obj->on_ground = atoi(parts[4]); obj->frequency = atof(parts[5]); obj->offset = atof(parts[6]); handler->objects_count++; } else if (strcmp(cmd, "REQUIRE_EVEN") == 0) { handler->require_evens = (int*)realloc(handler->require_evens, (handler->require_evens_count + 1) * sizeof(int)); handler->require_evens[handler->require_evens_count] = 1; handler->require_evens_count++; } else if (strcmp(cmd, "CAR") == 0) { handler->cars = (struct Car*)realloc(handler->cars, (handler->cars_count + 1) * sizeof(struct Car)); struct Car* car = &handler->cars[handler->cars_count]; car->reverse = atoi(parts[1]); car->lateral_offset = atof(parts[2]); car->velocity = atof(parts[3]); car->spawn_ratio = atof(parts[4]); car->traffic_type = atoi(parts[5]); handler->cars_count++; } else if (strcmp(cmd, "CAR_MODEL") == 0) { handler->car_models = (struct CarModel*)realloc(handler->car_models, (handler->car_models_count + 1) * sizeof(struct CarModel)); struct CarModel* cm = &handler->car_models[handler->car_models_count]; cm->name = strdup(parts[1]); cm->lateral_offset = atof(parts[2]); cm->long_offset = atof(parts[3]); cm->scale = atof(parts[4]); handler->car_models_count++; } } fclose(f); } void net_file_handler_print_properties(NetFileHandler* handler) { printf("{\n"); printf(" \"header\": [\n"); for (int i = 0; i < handler->header_count; i++) { printf(" \"%s\"%s\n", handler->header[i], i < handler->header_count - 1 ? "," : ""); } printf(" ],\n"); printf(" \"textures\": [\n"); for (int i = 0; i < handler->textures_count; i++) { printf(" {\"z_offset\": %d, \"filename\": \"%s\"}%s\n", handler->textures[i].z_offset, handler->textures[i].filename, i < handler->textures_count - 1 ? "," : ""); } printf(" ],\n"); // Similarly for other fields... (abbreviated for brevity; implement similar loops for each property) printf("}\n"); } void net_file_handler_write(NetFileHandler* handler, const char* filepath) { FILE* f = fopen(filepath, "w"); if (!f) { perror("Cannot open file for writing"); return; } for (int i = 0; i < handler->header_count; i++) { fprintf(f, "%s\n", handler->header[i]); } for (int i = 0; i < handler->textures_count; i++) { fprintf(f, "TEXTURE %d %s\n", handler->textures[i].z_offset, handler->textures[i].filename); } // Similarly for other fields... (abbreviated; implement similar loops for each property) fclose(f); } void net_file_handler_free(NetFileHandler* handler) { // Free all allocated memory (abbreviated; free each array and strings) free(handler); } // Example usage // int main() { // NetFileHandler* handler = net_file_handler_new(); // net_file_handler_read(handler, "example.net"); // net_file_handler_print_properties(handler); // net_file_handler_write(handler, "output.net"); // net_file_handler_free(handler); // return 0; // } // ===== end task-447 .NET ===== // ===== task-448 .NEU [C] ===== #include #include #include #include #define MAX_LINE 1024 #define MAX_NODES 27 // Max nodes per element struct Control { char header[100]; char title[81]; char programVersion[50]; char dateTime[30]; int numNP; int nelem; int ngrps; int nbsets; int ndfcd; int ndfvl; }; struct Node { int id; double coords[3]; }; struct Element { int id; int type; int ndp; int nodes[MAX_NODES]; }; struct Group { int group; int nelgp; int mtyp; int nflags; char name[33]; int *flags; int *elements; }; struct BoundaryEntry { int elem_or_node; int type; // for element int face; // for element double *values; }; struct BoundarySet { char name[33]; int itype; int nentry; int nvalues; int ibcodes[5]; struct BoundaryEntry *entries; }; struct NEUFile { struct Control control; struct Node *nodalCoords; struct Element *elements; struct Group *groups; struct BoundarySet *boundarySets; }; void readNEU(struct NEUFile *neu, const char *filename) { FILE *fp = fopen(filename, "r"); if (!fp) { perror("fopen"); exit(1); } char line[MAX_LINE]; int lineNum = 0; // Read lines, skip comments char **lines = NULL; int numLines = 0; while (fgets(line, MAX_LINE, fp)) { lineNum++; char *trimmed = line; while (isspace(*trimmed)) trimmed++; if (*trimmed == 0 || *trimmed == '/') continue; lines = realloc(lines, (numLines + 1) * sizeof(char*)); lines[numLines] = strdup(trimmed); numLines++; } fclose(fp); int i = 0; // Parse Control if (strstr(lines[i], "CONTROL INFO")) { i++; strcpy(neu->control.header, lines[i++]); strcpy(neu->control.title, lines[i++]); strcpy(neu->control.programVersion, lines[i++]); strcpy(neu->control.dateTime, lines[i++]); i++; // Headings sscanf(lines[i++], "%d %d %d %d %d %d", &neu->control.numNP, &neu->control.nelem, &neu->control.ngrps, &neu->control.nbsets, &neu->control.ndfcd, &neu->control.ndfvl); i++; // ENDOFSECTION } // Allocate arrays neu->nodalCoords = malloc(neu->control.numNP * sizeof(struct Node)); neu->elements = malloc(neu->control.nelem * sizeof(struct Element)); neu->groups = malloc(neu->control.ngrps * sizeof(struct Group)); neu->boundarySets = malloc(neu->control.nbsets * sizeof(struct BoundarySet)); // Parse Nodal Coords if (strstr(lines[i], "NODAL COORDINATES")) { i++; for (int j = 0; j < neu->control.numNP; j++) { sscanf(lines[i++], "%d %lf %lf %lf", &neu->nodalCoords[j].id, &neu->nodalCoords[j].coords[0], &neu->nodalCoords[j].coords[1], &neu->nodalCoords[j].coords[2]); } i++; // ENDOFSECTION } // Parse Elements if (strstr(lines[i], "ELEMENTS/CELLS")) { i++; for (int j = 0; j < neu->control.nelem; j++) { char *tok = lines[i++]; neu->elements[j].id = strtol(tok, &tok, 10); neu->elements[j].type = strtol(tok, &tok, 10); neu->elements[j].ndp = strtol(tok, &tok, 10); for (int k = 0; k < neu->elements[j].ndp; k++) { neu->elements[j].nodes[k] = strtol(tok, &tok, 10); } } i++; // ENDOFSECTION } // Parse Groups for (int g = 0; g < neu->control.ngrps; g++) { if (strstr(lines[i], "ELEMENT GROUP")) { i++; sscanf(lines[i++], "GROUP: %d ELEMENTS: %d MATERIAL: %d NFLAGS: %d", &neu->groups[g].group, &neu->groups[g].nelgp, &neu->groups[g].mtyp, &neu->groups[g].nflags); strcpy(neu->groups[g].name, lines[i++]); neu->groups[g].flags = malloc(neu->groups[g].nflags * sizeof(int)); char *tok = lines[i++]; for (int f = 0; f < neu->groups[g].nflags; f++) { neu->groups[g].flags[f] = strtol(tok, &tok, 10); } neu->groups[g].elements = malloc(neu->groups[g].nelgp * sizeof(int)); int elemIdx = 0; while (!strstr(lines[i], "ENDOFSECTION")) { tok = lines[i++]; while (*tok) { neu->groups[g].elements[elemIdx++] = strtol(tok, &tok, 10); } } i++; } } // Parse Boundary Sets for (int b = 0; b < neu->control.nbsets; b++) { if (strstr(lines[i], "BOUNDARY CONDITIONS")) { i++; char *tok = lines[i++]; strncpy(neu->boundarySets[b].name, tok, 32); tok += 32; neu->boundarySets[b].itype = strtol(tok, &tok, 10); neu->boundarySets[b].nentry = strtol(tok, &tok, 10); neu->boundarySets[b].nvalues = strtol(tok, &tok, 10); for (int c = 0; c < 5; c++) { neu->boundarySets[b].ibcodes[c] = strtol(tok, &tok, 10); } neu->boundarySets[b].entries = malloc(neu->boundarySets[b].nentry * sizeof(struct BoundaryEntry)); for (int e = 0; e < neu->boundarySets[b].nentry; e++) { tok = lines[i++]; if (neu->boundarySets[b].itype == 0) { neu->boundarySets[b].entries[e].elem_or_node = strtol(tok, &tok, 10); neu->boundarySets[b].entries[e].values = malloc(neu->boundarySets[b].nvalues * sizeof(double)); for (int v = 0; v < neu->boundarySets[b].nvalues; v++) { neu->boundarySets[b].entries[e].values[v] = strtod(tok, &tok); } } else { neu->boundarySets[b].entries[e].elem_or_node = strtol(tok, &tok, 10); neu->boundarySets[b].entries[e].type = strtol(tok, &tok, 10); neu->boundarySets[b].entries[e].face = strtol(tok, &tok, 10); neu->boundarySets[b].entries[e].values = malloc(neu->boundarySets[b].nvalues * sizeof(double)); for (int v = 0; v < neu->boundarySets[b].nvalues; v++) { neu->boundarySets[b].entries[e].values[v] = strtod(tok, &tok); } } } i++; } } // Free lines for (int j = 0; j < numLines; j++) free(lines[j]); free(lines); } void printNEUProperties(const struct NEUFile *neu) { printf("Control Information:\n"); printf(" Header: %s\n", neu->control.header); printf(" Title: %s\n", neu->control.title); printf(" Program Version: %s\n", neu->control.programVersion); printf(" Date Time: %s\n", neu->control.dateTime); printf(" NUMNP: %d, NELEM: %d, NGRPS: %d, NBSETS: %d, NDFCD: %d, NDFVL: %d\n", neu->control.numNP, neu->control.nelem, neu->control.ngrps, neu->control.nbsets, neu->control.ndfcd, neu->control.ndfvl); printf("\nNodal Coordinates:\n"); for (int j = 0; j < neu->control.numNP; j++) { printf(" Node %d: %e %e %e\n", neu->nodalCoords[j].id, neu->nodalCoords[j].coords[0], neu->nodalCoords[j].coords[1], neu->nodalCoords[j].coords[2]); } printf("\nElements:\n"); for (int j = 0; j < neu->control.nelem; j++) { printf(" Element %d (Type %d, NDP %d): ", neu->elements[j].id, neu->elements[j].type, neu->elements[j].ndp); for (int k = 0; k < neu->elements[j].ndp; k++) { printf("%d ", neu->elements[j].nodes[k]); } printf("\n"); } printf("\nGroups:\n"); for (int g = 0; g < neu->control.ngrps; g++) { printf(" Group %d, Elements %d, Material %d, NFlags %d\n", neu->groups[g].group, neu->groups[g].nelgp, neu->groups[g].mtyp, neu->groups[g].nflags); printf(" Name: %s\n", neu->groups[g].name); printf(" Flags: "); for (int f = 0; f < neu->groups[g].nflags; f++) { printf("%d ", neu->groups[g].flags[f]); } printf("\n Elements: "); for (int e = 0; e < neu->groups[g].nelgp; e++) { printf("%d ", neu->groups[g].elements[e]); } printf("\n"); } printf("\nBoundary Sets:\n"); for (int b = 0; b < neu->control.nbsets; b++) { printf(" Name: %s, Type: %d, Entries: %d, Values: %d\n", neu->boundarySets[b].name, neu->boundarySets[b].itype, neu->boundarySets[b].nentry, neu->boundarySets[b].nvalues); printf(" IBCodes: %d %d %d %d %d\n", neu->boundarySets[b].ibcodes[0], neu->boundarySets[b].ibcodes[1], neu->boundarySets[b].ibcodes[2], neu->boundarySets[b].ibcodes[3], neu->boundarySets[b].ibcodes[4]); for (int e = 0; e < neu->boundarySets[b].nentry; e++) { if (neu->boundarySets[b].itype == 0) { printf(" Node %d: ", neu->boundarySets[b].entries[e].elem_or_node); } else { printf(" Elem %d Type %d Face %d: ", neu->boundarySets[b].entries[e].elem_or_node, neu->boundarySets[b].entries[e].type, neu->boundarySets[b].entries[e].face); } for (int v = 0; v < neu->boundarySets[b].nvalues; v++) { printf("%e ", neu->boundarySets[b].entries[e].values[v]); } printf("\n"); } } } void writeNEU(const struct NEUFile *neu, const char *filename) { FILE *fp = fopen(filename, "w"); if (!fp) { perror("fopen"); exit(1); } // Write Control fprintf(fp, "CONTROL INFO 1.2.1\n"); fprintf(fp, "%s\n", neu->control.header); fprintf(fp, "%s\n", neu->control.title); fprintf(fp, "%s\n", neu->control.programVersion); fprintf(fp, "%s\n", neu->control.dateTime); fprintf(fp, " NUMNP NELEM NGRPS NBSETS NDFCD NDFVL\n"); fprintf(fp, "%10d%10d%10d%10d%10d%10d\n", neu->control.numNP, neu->control.nelem, neu->control.ngrps, neu->control.nbsets, neu->control.ndfcd, neu->control.ndfvl); fprintf(fp, "ENDOFSECTION\n"); // Write Nodal Coords fprintf(fp, "NODAL COORDINATES 1.2.1\n"); for (int j = 0; j < neu->control.numNP; j++) { fprintf(fp, "%10d %20.11e %20.11e %20.11e\n", neu->nodalCoords[j].id, neu->nodalCoords[j].coords[0], neu->nodalCoords[j].coords[1], neu->nodalCoords[j].coords[2]); } fprintf(fp, "ENDOFSECTION\n"); // Write Elements fprintf(fp, "ELEMENTS/CELLS 1.2.1\n"); for (int j = 0; j < neu->control.nelem; j++) { fprintf(fp, "%8d %2d %2d", neu->elements[j].id, neu->elements[j].type, neu->elements[j].ndp); for (int k = 0; k < neu->elements[j].ndp; k++) { fprintf(fp, " %8d", neu->elements[j].nodes[k]); } fprintf(fp, "\n"); } fprintf(fp, "ENDOFSECTION\n"); // Write Groups for (int g = 0; g < neu->control.ngrps; g++) { fprintf(fp, "ELEMENT GROUP 1.2.1\n"); fprintf(fp, "GROUP: %10d ELEMENTS: %10d MATERIAL: %10d NFLAGS: %10d\n", neu->groups[g].group, neu->groups[g].nelgp, neu->groups[g].mtyp, neu->groups[g].nflags); fprintf(fp, "%s\n", neu->groups[g].name); for (int f = 0; f < neu->groups[g].nflags; f++) { fprintf(fp, "%d ", neu->groups[g].flags[f]); } fprintf(fp, "\n"); for (int e = 0; e < neu->groups[g].nelgp; e++) { fprintf(fp, "%8d", neu->groups[g].elements[e]); if ((e + 1) % 10 == 0) fprintf(fp, "\n"); } fprintf(fp, "\n"); fprintf(fp, "ENDOFSECTION\n"); } // Write Boundary Sets for (int b = 0; b < neu->control.nbsets; b++) { fprintf(fp, "BOUNDARY CONDITIONS 1.2.1\n"); fprintf(fp, "%-32s %8d %8d %8d", neu->boundarySets[b].name, neu->boundarySets[b].itype, neu->boundarySets[b].nentry, neu->boundarySets[b].nvalues); for (int c = 0; c < 5; c++) { fprintf(fp, " %d", neu->boundarySets[b].ibcodes[c]); } fprintf(fp, "\n"); for (int e = 0; e < neu->boundarySets[b].nentry; e++) { if (neu->boundarySets[b].itype == 0) { fprintf(fp, "%10d", neu->boundarySets[b].entries[e].elem_or_node); for (int v = 0; v < neu->boundarySets[b].nvalues; v++) { fprintf(fp, " %20.12e", neu->boundarySets[b].entries[e].values[v]); } fprintf(fp, "\n"); } else { fprintf(fp, "%10d %5d %5d", neu->boundarySets[b].entries[e].elem_or_node, neu->boundarySets[b].entries[e].type, neu->boundarySets[b].entries[e].face); for (int v = 0; v < neu->boundarySets[b].nvalues; v++) { fprintf(fp, " %20.12e", neu->boundarySets[b].entries[e].values[v]); } fprintf(fp, "\n"); } } fprintf(fp, "ENDOFSECTION\n"); } fclose(fp); } // Free memory function (call after use) void freeNEU(struct NEUFile *neu) { free(neu->nodalCoords); free(neu->elements); for (int g = 0; g < neu->control.ngrps; g++) { free(neu->groups[g].flags); free(neu->groups[g].elements); } free(neu->groups); for (int b = 0; b < neu->control.nbsets; b++) { for (int e = 0; e < neu->boundarySets[b].nentry; e++) { free(neu->boundarySets[b].entries[e].values); } free(neu->boundarySets[b].entries); } free(neu->boundarySets); } // Example usage // int main() { // struct NEUFile neu; // readNEU(&neu, "input.neu"); // printNEUProperties(&neu); // writeNEU(&neu, "output.neu"); // freeNEU(&neu); // return 0; // } // ===== end task-448 .NEU ===== // ===== task-449 .NEX [C] ===== #include #include #include #include typedef struct { char magic[5]; char version[5]; uint8_t ram_required; uint8_t num_banks; uint8_t loading_screen; uint8_t border_colour; uint16_t stack_pointer; uint16_t program_counter; uint16_t num_extra_files; uint8_t banks_included[112]; uint8_t layer2_loading_bar; uint8_t loading_bar_colour; uint8_t loading_delay_bank; uint8_t start_delay; uint8_t preserve_regs; uint8_t core_major; uint8_t core_minor; uint8_t core_subminor; uint8_t timex_colour_or_offset; uint8_t entry_bank; uint16_t file_handle_addr; uint8_t* header; // 512 bytes uint8_t* data; // Rest of file size_t data_size; } NexFile; NexFile* nex_create() { NexFile* nex = malloc(sizeof(NexFile)); strcpy(nex->magic, "Next"); strcpy(nex->version, "V1.2"); nex->ram_required = 0; nex->num_banks = 0; nex->loading_screen = 0; nex->border_colour = 0; nex->stack_pointer = 0; nex->program_counter = 0; nex->num_extra_files = 0; memset(nex->banks_included, 0, 112); nex->layer2_loading_bar = 0; nex->loading_bar_colour = 0; nex->loading_delay_bank = 0; nex->start_delay = 0; nex->preserve_regs = 0; nex->core_major = 0; nex->core_minor = 0; nex->core_subminor = 0; nex->timex_colour_or_offset = 0; nex->entry_bank = 0; nex->file_handle_addr = 0; nex->header = calloc(512, 1); nex->data = NULL; nex->data_size = 0; return nex; } void nex_load(NexFile* nex, const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) { perror("Failed to open file"); exit(1); } fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); if (size < 512) { fprintf(stderr, "Invalid .NEX file: too short.\n"); exit(1); } fread(nex->header, 512, 1, f); nex->data_size = size - 512; nex->data = malloc(nex->data_size); fread(nex->data, nex->data_size, 1, f); fclose(f); memcpy(nex->magic, nex->header + 0, 4); nex->magic[4] = '\0'; memcpy(nex->version, nex->header + 4, 4); nex->version[4] = '\0'; nex->ram_required = nex->header[8]; nex->num_banks = nex->header[9]; nex->loading_screen = nex->header[10]; nex->border_colour = nex->header[11]; nex->stack_pointer = *(uint16_t*)(nex->header + 12); nex->program_counter = *(uint16_t*)(nex->header + 14); nex->num_extra_files = *(uint16_t*)(nex->header + 16); memcpy(nex->banks_included, nex->header + 18, 112); nex->layer2_loading_bar = nex->header[130]; nex->loading_bar_colour = nex->header[131]; nex->loading_delay_bank = nex->header[132]; nex->start_delay = nex->header[133]; nex->preserve_regs = nex->header[134]; nex->core_major = nex->header[135]; nex->core_minor = nex->header[136]; nex->core_subminor = nex->header[137]; nex->timex_colour_or_offset = nex->header[138]; nex->entry_bank = nex->header[139]; nex->file_handle_addr = *(uint16_t*)(nex->header + 140); } void nex_print_properties(NexFile* nex) { printf(" .NEX File Properties:\n"); printf("Magic String: %s\n", nex->magic); printf("Version: %s\n", nex->version); printf("RAM Required: %u (0=768k, 1=1792k)\n", nex->ram_required); printf("Number of 16k Banks: %u\n", nex->num_banks); printf("Loading-Screen Blocks: %02X (bit flags)\n", nex->loading_screen); printf("Border Colour: %u\n", nex->border_colour); printf("Stack Pointer: 0x%04X\n", nex->stack_pointer); printf("Program Counter: 0x%04X\n", nex->program_counter); printf("Number of Extra Files: %u\n", nex->num_extra_files); printf("Banks Included: ["); for (int i = 0; i < 112; i++) { printf("%u%s", nex->banks_included[i], i < 111 ? ", " : ""); } printf("]\n"); printf("Layer2 Loading Bar: %u\n", nex->layer2_loading_bar); printf("Loading Bar Colour: %u\n", nex->loading_bar_colour); printf("Loading Delay Per Bank: %u\n", nex->loading_delay_bank); printf("Start Delay: %u\n", nex->start_delay); printf("Preserve Next-Registers: %u\n", nex->preserve_regs); printf("Required Core Version: %u.%u.%u\n", nex->core_major, nex->core_minor, nex->core_subminor); printf("Timex HiRes Colour / Palette Offset: %u\n", nex->timex_colour_or_offset); printf("Entry Bank: %u\n", nex->entry_bank); printf("File Handle Address: 0x%04X\n", nex->file_handle_addr); } void nex_save(NexFile* nex, const char* filename) { memset(nex->header, 0, 512); memcpy(nex->header + 0, nex->magic, 4); memcpy(nex->header + 4, nex->version, 4); nex->header[8] = nex->ram_required; nex->header[9] = nex->num_banks; nex->header[10] = nex->loading_screen; nex->header[11] = nex->border_colour; *(uint16_t*)(nex->header + 12) = nex->stack_pointer; *(uint16_t*)(nex->header + 14) = nex->program_counter; *(uint16_t*)(nex->header + 16) = nex->num_extra_files; memcpy(nex->header + 18, nex->banks_included, 112); nex->header[130] = nex->layer2_loading_bar; nex->header[131] = nex->loading_bar_colour; nex->header[132] = nex->loading_delay_bank; nex->header[133] = nex->start_delay; nex->header[134] = nex->preserve_regs; nex->header[135] = nex->core_major; nex->header[136] = nex->core_minor; nex->header[137] = nex->core_subminor; nex->header[138] = nex->timex_colour_or_offset; nex->header[139] = nex->entry_bank; *(uint16_t*)(nex->header + 140) = nex->file_handle_addr; FILE* f = fopen(filename, "wb"); if (!f) { perror("Failed to open file for writing"); exit(1); } fwrite(nex->header, 512, 1, f); fwrite(nex->data, nex->data_size, 1, f); fclose(f); } void nex_destroy(NexFile* nex) { free(nex->header); free(nex->data); free(nex); } // Example usage: // int main() { // NexFile* nex = nex_create(); // nex_load(nex, "example.nex"); // nex_print_properties(nex); // nex->ram_required = 1; // Modify // nex_save(nex, "modified.nex"); // nex_destroy(nex); // return 0; // } // ===== end task-449 .NEX ===== // ===== task-450 .NF [C++] ===== #include #include #include #include #include #include class NFHandler { private: std::string filename; std::string content; std::map> properties; public: NFHandler(const std::string& fn) : filename(fn) {} void read() { std::ifstream file(filename); if (file.is_open()) { std::string line; while (std::getline(file, line)) { content += line + "\n"; } file.close(); decode(); } else { std::cerr << "Unable to open file" << std::endl; } } void decode() { std::vector lines; std::string temp = content; size_t pos = 0; while ((pos = temp.find("\n")) != std::string::npos) { lines.push_back(temp.substr(0, pos)); temp.erase(0, pos + 1); } std::vector keywords = {"def", "println", "new", "assert", "if", "else", "tuple", "workflow"}; std::regex operatorRegex(R"(==|!=|<|>|&&|\|\|)"); properties["variables"] = {}; properties["lists"] = {}; properties["maps"] = {}; properties["tuples"] = {}; properties["operators"] = {}; properties["conditionals"] = {}; properties["strings"] = {}; properties["regex"] = {}; properties["closures"] = {}; properties["definitions"] = {}; properties["keywords"] = {}; properties["structures"] = {}; for (const auto& line : lines) { std::string trimmed = line; // Trim whitespace (simple implementation) trimmed.erase(0, trimmed.find_first_not_of(" \t")); trimmed.erase(trimmed.find_last_not_of(" \t") + 1); if (trimmed.rfind("def ", 0) == 0) properties["variables"].push_back(trimmed); if (line.find("[]") != std::string::npos) properties["lists"].push_back(trimmed); if (line.find("[:") != std::string::npos) properties["maps"].push_back(trimmed); if (line.find("tuple(") != std::string::npos) properties["tuples"].push_back(trimmed); if (std::regex_search(line, operatorRegex)) properties["operators"].push_back(trimmed); if (line.find("if") != std::string::npos || line.find("else") != std::string::npos || line.find("?") != std::string::npos) properties["conditionals"].push_back(trimmed); if (line.find("\"") != std::string::npos || line.find("'") != std::string::npos || line.find("\"\"\"") != std::string::npos) properties["strings"].push_back(trimmed); if (line.find("=~") != std::string::npos || line.find("==~") != std::string::npos) properties["regex"].push_back(trimmed); if (line.find("{") != std::string::npos && line.find("->") != std::string::npos) properties["closures"].push_back(trimmed); if (line.find("workflow {") != std::string::npos) properties["definitions"].push_back(trimmed); bool hasKw = false; for (const auto& kw : keywords) { if (line.find(kw) != std::string::npos) { properties["keywords"].push_back(trimmed); hasKw = true; break; } } if (line.find("#") != std::string::npos || line.find("{") != std::string::npos || line.find("(") != std::string::npos) properties["structures"].push_back(trimmed); } } void printProperties() { for (const auto& pair : properties) { if (!pair.second.empty()) { std::string key = pair.first; key[0] = std::toupper(key[0]); std::cout << key << ":" << std::endl; for (const auto& value : pair.second) { std::cout << " - " << value << std::endl; } } } } void write(const std::string& newFilename = "") { std::string file = newFilename.empty() ? filename : newFilename; std::ofstream outFile(file); if (outFile.is_open()) { outFile << content; outFile.close(); } else { std::cerr << "Unable to write file" << std::endl; } } }; // Example usage: // int main() { // NFHandler handler("example.nf"); // handler.read(); // handler.printProperties(); // handler.write("output.nf"); // return 0; // } // ===== end task-450 .NF ===== // ===== task-451 .NFO [C] ===== #include #include #include #define MAX_LINE 1024 const char* properties[] = { "title", "originaltitle", "sorttitle", "ratings", "userrating", "top250", "outline", "plot", "tagline", "runtime", "thumb", "fanart", "mpaa", "playcount", "lastplayed", "uniqueid", "genre", "tag", "set", "country", "credits", "director", "premiered", "year", "status", "code", "aired", "studio", "trailer", "fileinfo", "actor", "showlink", "resume", "dateadded", NULL }; typedef struct { char* filepath; } NFOHandler; NFOHandler* create_nfo_handler(const char* filepath) { NFOHandler* handler = malloc(sizeof(NFOHandler)); handler->filepath = strdup(filepath); return handler; } void print_properties(NFOHandler* handler) { FILE* fp = fopen(handler->filepath, "r"); if (fp == NULL) { printf("File not found\n"); return; } char line[MAX_LINE]; while (fgets(line, MAX_LINE, fp)) { for (int i = 0; properties[i]; i++) { char tag_open[50]; snprintf(tag_open, 50, "<%s>", properties[i]); if (strstr(line, tag_open)) { char* start = strstr(line, ">") + 1; char* end = strstr(start, "filepath, "a"); if (fp == NULL) { fp = fopen(handler->filepath, "w"); } fprintf(fp, "<%s>%s\n", prop, value, prop); fclose(fp); } void destroy_nfo_handler(NFOHandler* handler) { free(handler->filepath); free(handler); } // Example usage // int main() { // NFOHandler* nfo = create_nfo_handler("sample.nfo"); // print_properties(nfo); // write_property(nfo, "title", "Test Movie"); // destroy_nfo_handler(nfo); // return 0; // } // ===== end task-451 .NFO ===== // ===== task-452 .NIM [C++] ===== #include #include #include #include #include class NIMFile { private: static const unsigned char MAGIC[4]; static const std::string PROPERTIES[8]; std::string filepath; std::vector data; public: NIMFile(const std::string& fp) : filepath(fp) {} void openAndDecode() { std::ifstream file(filepath, std::ios::binary); if (!file) { throw std::runtime_error("Could not open file"); } unsigned char magic[4]; file.read(reinterpret_cast(magic), 4); if (std::memcmp(magic, MAGIC, 4) != 0) { throw std::runtime_error("Invalid .NIM file (magic number mismatch)"); } data.assign(magic, magic + 4); unsigned char byte; while (file.read(reinterpret_cast(&byte), 1)) { data.push_back(byte); } file.close(); } void printProperties() const { for (const auto& prop : PROPERTIES) { std::cout << prop << std::endl; } } void write(const std::string& newFilepath) const { if (data.empty()) { throw std::runtime_error("File not opened or decoded yet"); } std::ofstream file(newFilepath, std::ios::binary); if (!file) { throw std::runtime_error("Could not write file"); } file.write(reinterpret_cast(data.data()), data.size()); file.close(); } }; const unsigned char NIMFile::MAGIC[4] = {0x00, 0x00, 0x01, 0xff}; const std::string NIMFile::PROPERTIES[8] = { "Magic number: 0x00 0x00 0x01 0xff (at offset 0)", "File extension: .nim", "MIME type: video/vnd.nokia.interleaved-multimedia", "Content type: Multiplexed audio and video streams", "Proprietary status: Yes, developed by Nokia", "Intended device: Nokia 9210 Communicator video player", "Creation method: Converted from formats like AVI using Nokia Multimedia Converter", "File system integration: Stored as regular binary files; no special file system attributes beyond standard metadata (e.g., size, timestamps)" }; // Example usage: // int main() { // try { // NIMFile nim("example.nim"); // nim.openAndDecode(); // nim.printProperties(); // nim.write("new_example.nim"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-452 .NIM ===== // ===== task-453 .NMF [C] ===== #include #include #include typedef struct { xmlDocPtr doc; } NMFHandler; void nmf_open(NMFHandler *handler, const char *filename) { handler->doc = xmlReadFile(filename, NULL, 0); if (handler->doc == NULL) { fprintf(stderr, "Failed to parse %s\n", filename); } } xmlDocPtr nmf_decode_read(NMFHandler *handler) { if (handler->doc == NULL) { fprintf(stderr, "No file opened\n"); return NULL; } return handler->doc; } void nmf_print_properties(NMFHandler *handler) { if (handler->doc == NULL) { fprintf(stderr, "No file opened\n"); return; } xmlNode *root = xmlDocGetRootElement(handler->doc); dump_node(root, 0); } void dump_node(xmlNode *node, int level) { if (node == NULL) return; for (int i = 0; i < level; i++) printf(" "); printf("<%s", node->name); for (xmlAttr *attr = node->properties; attr; attr = attr->next) { printf(" %s=\"%s\"", attr->name, attr->children->content); } printf(">\n"); if (node->content && xmlStrlen(node->content) > 0) { for (int i = 0; i < level; i++) printf(" "); printf(" %s\n", node->content); } for (xmlNode *child = node->children; child; child = child->next) { dump_node(child, level + 1); } for (int i = 0; i < level; i++) printf(" "); printf("\n", node->name); } void nmf_write(NMFHandler *handler, const char *filename, const char *new_description) { if (handler->doc == NULL) { handler->doc = xmlNewDoc(BAD_CAST "1.0"); xmlNode *root = xmlNewNode(NULL, BAD_CAST "mbf"); xmlNewProp(root, BAD_CAST "version", BAD_CAST "4.0"); xmlNewProp(root, BAD_CAST "appname", BAD_CAST "Test"); xmlDocSetRootElement(handler->doc, root); } // Add example description xmlNode *desc = xmlNewChild(xmlDocGetRootElement(handler->doc), NULL, BAD_CAST "description", BAD_CAST (new_description ? new_description : "Example")); xmlSaveFormatFileEnc(filename, handler->doc, "ISO-8859-1", 1); } void nmf_close(NMFHandler *handler) { xmlFreeDoc(handler->doc); } // Example usage: // NMFHandler handler = {NULL}; // nmf_open(&handler, "example.nmf"); // nmf_print_properties(&handler); // nmf_write(&handler, "new.nmf", "New description"); // nmf_close(&handler); // ===== end task-453 .NMF ===== // ===== task-454 .NOFF [C++] ===== #include #include #include #include #include class NOFFFile { private: std::string header = "NOFF"; int nv = 0; int nf = 0; int ne = 0; std::vector> vertices; std::vector> normals; std::vector> faces; public: NOFFFile(const std::string& filename = "") { if (!filename.empty()) { read(filename); } } void read(const std::string& filename) { std::ifstream file(filename); if (!file.is_open()) { std::cerr << "Unable to open file: " << filename << std::endl; return; } std::vector lines; std::string line; while (std::getline(file, line)) { line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); if (!line.empty()) lines.push_back(line); } file.close(); size_t index = 0; header = lines[index++]; if (header != "NOFF") { std::cerr << "Invalid NOFF file: Missing or incorrect header." << std::endl; return; } std::istringstream meta(lines[index++]); meta >> nv >> nf >> ne; vertices.clear(); normals.clear(); vertices.resize(nv, std::vector(3)); normals.resize(nv, std::vector(3)); for (int i = 0; i < nv; ++i) { std::istringstream vertLine(lines[index++]); vertLine >> vertices[i][0] >> vertices[i][1] >> vertices[i][2] >> normals[i][0] >> normals[i][1] >> normals[i][2]; } faces.clear(); for (int i = 0; i < nf; ++i) { std::istringstream faceLine(lines[index++]); int count; faceLine >> count; std::vector face(count); for (int j = 0; j < count; ++j) { faceLine >> face[j]; } faces.push_back(face); } } void write(const std::string& filename) { std::ofstream file(filename); if (!file.is_open()) { std::cerr << "Unable to open file for writing: " << filename << std::endl; return; } file << header << std::endl; file << nv << " " << nf << " " << ne << std::endl; for (int i = 0; i < nv; ++i) { file << vertices[i][0] << " " << vertices[i][1] << " " << vertices[i][2] << " " << normals[i][0] << " " << normals[i][1] << " " << normals[i][2] << std::endl; } for (const auto& face : faces) { file << face.size(); for (int idx : face) { file << " " << idx; } file << std::endl; } file.close(); } void printProperties() { std::cout << "Header: " << header << std::endl; std::cout << "Number of vertices: " << nv << std::endl; std::cout << "Number of faces: " << nf << std::endl; std::cout << "Number of edges: " << ne << std::endl; std::cout << "Vertex coordinates:" << std::endl; for (const auto& v : vertices) { std::cout << "[" << v[0] << ", " << v[1] << ", " << v[2] << "]" << std::endl; } std::cout << "Vertex normals:" << std::endl; for (const auto& n : normals) { std::cout << "[" << n[0] << ", " << n[1] << ", " << n[2] << "]" << std::endl; } std::cout << "Face vertex counts and indices:" << std::endl; for (size_t i = 0; i < faces.size(); ++i) { std::cout << "Face " << i << ": count=" << faces[i].size() << ", indices=["; for (size_t j = 0; j < faces[i].size(); ++j) { std::cout << faces[i][j]; if (j < faces[i].size() - 1) std::cout << ", "; } std::cout << "]" << std::endl; } } }; // ===== end task-454 .NOFF ===== // ===== task-455 .NPR [C] ===== #include #include #include #include // For uint32_t typedef struct { char *filepath; char magic[5]; uint32_t chunk_size; char format_type[5]; } NPRFile; NPRFile* npr_create(const char *filepath) { NPRFile *npr = malloc(sizeof(NPRFile)); npr->filepath = strdup(filepath); memset(npr->magic, 0, 5); npr->chunk_size = 0; memset(npr->format_type, 0, 5); return npr; } void npr_read(NPRFile *npr) { FILE *f = fopen(npr->filepath, "rb"); if (!f) { perror("Failed to open file"); return; } char header[12]; if (fread(header, 1, 12, f) < 12) { fprintf(stderr, "File too small for .NPR header\n"); fclose(f); return; } fclose(f); strncpy(npr->magic, header, 4); memcpy(&npr->chunk_size, header + 4, 4); // Assume little-endian host strncpy(npr->format_type, header + 8, 4); // Further chunks would be parsed here if specs were available } void npr_print_properties(const NPRFile *npr) { printf("Magic number: %s\n", npr->magic); printf("Chunk size: %u\n", npr->chunk_size); printf("Format type: %s\n", npr->format_type); printf("(Note: Further chunks are proprietary and not printed here.)\n"); } void npr_write(const NPRFile *npr, const char *new_filepath) { char *path = new_filepath ? strdup(new_filepath) : strcat(strdup(npr->filepath), ".new"); FILE *f = fopen(path, "wb"); if (!f) { perror("Failed to write file"); free(path); return; } fwrite(npr->magic[0] ? npr->magic : "RIFF", 1, 4, f); uint32_t size = npr->chunk_size ? npr->chunk_size : 4; fwrite(&size, 4, 1, f); // Little-endian fwrite(npr->format_type[0] ? npr->format_type : "NUND", 1, 4, f); fclose(f); free(path); // Add proprietary chunks here if needed; this writes a minimal header } void npr_destroy(NPRFile *npr) { free(npr->filepath); free(npr); } // Example usage: // int main() { // NPRFile *npr = npr_create("example.npr"); // npr_read(npr); // npr_print_properties(npr); // npr_write(npr, "example_modified.npr"); // npr_destroy(npr); // return 0; // } // ===== end task-455 .NPR ===== // ===== task-456 .NRO [C] ===== #include #include #include #include #include // For big-endian systems, but assuming little-endian host typedef struct { char* filepath; uint8_t* data; size_t size; // Properties storage (use simple arrays/maps simulation) char rocrt_module_loc[37]; // Hex string uint32_t rocrt_reserved; char nro_signature[5]; uint32_t nro_version; uint32_t nro_size; uint32_t nro_flags; uint32_t nro_text_off; uint32_t nro_text_size; uint32_t nro_ro_off; uint32_t nro_ro_size; uint32_t nro_data_off; uint32_t nro_data_size; uint32_t nro_bss_size; uint32_t nro_reserved1; char nro_module_id[97]; // 32*3 -1 uint32_t nro_dso_handle; uint32_t nro_reserved2; uint32_t nro_embed_off; uint32_t nro_embed_size; uint32_t nro_dynstr_off; uint32_t nro_dynstr_size; uint32_t nro_dynsym_off; uint32_t nro_dynsym_size; int has_assets; char assets_magic[5]; uint32_t assets_version; uint64_t assets_icon_off; uint64_t assets_icon_size; uint64_t assets_nacp_off; uint64_t assets_nacp_size; uint64_t assets_romfs_off; uint64_t assets_romfs_size; } NROParser; void init_nro_parser(NROParser* parser, const char* filepath) { parser->filepath = strdup(filepath); FILE* f = fopen(filepath, "rb"); if (!f) { perror("Failed to open file"); exit(1); } fseek(f, 0, SEEK_END); parser->size = ftell(f); fseek(f, 0, SEEK_SET); parser->data = malloc(parser->size); fread(parser->data, 1, parser->size, f); fclose(f); parser->has_assets = 0; } void read_nro(NROParser* parser) { if (parser->size < 0x80) { fprintf(stderr, "Invalid .NRO file: too small\n"); exit(1); } uint8_t* data = parser->data; size_t offset = 0; // RocrtHeader for (int i = 0; i < 0xC; i++) { char hex[4]; sprintf(hex, "%02x ", data[offset + i]); strcat(parser->rocrt_module_loc, hex); } parser->rocrt_module_loc[strlen(parser->rocrt_module_loc) - 1] = '\0'; // Trim space offset += 0xC; memcpy(&parser->rocrt_reserved, data + offset, 4); offset += 4; // NroHeader memcpy(parser->nro_signature, data + offset, 4); parser->nro_signature[4] = '\0'; if (strcmp(parser->nro_signature, "NRO0") != 0) { fprintf(stderr, "Invalid signature\n"); exit(1); } offset += 4; memcpy(&parser->nro_version, data + offset, 4); offset += 4; memcpy(&parser->nro_size, data + offset, 4); offset += 4; memcpy(&parser->nro_flags, data + offset, 4); offset += 4; memcpy(&parser->nro_text_off, data + offset, 4); offset += 4; memcpy(&parser->nro_text_size, data + offset, 4); offset += 4; memcpy(&parser->nro_ro_off, data + offset, 4); offset += 4; memcpy(&parser->nro_ro_size, data + offset, 4); offset += 4; memcpy(&parser->nro_data_off, data + offset, 4); offset += 4; memcpy(&parser->nro_data_size, data + offset, 4); offset += 4; memcpy(&parser->nro_bss_size, data + offset, 4); offset += 4; memcpy(&parser->nro_reserved1, data + offset, 4); offset += 4; for (int i = 0; i < 32; i++) { char hex[4]; sprintf(hex, "%02x ", data[offset + i]); strcat(parser->nro_module_id, hex); } parser->nro_module_id[strlen(parser->nro_module_id) - 1] = '\0'; offset += 32; memcpy(&parser->nro_dso_handle, data + offset, 4); offset += 4; memcpy(&parser->nro_reserved2, data + offset, 4); offset += 4; memcpy(&parser->nro_embed_off, data + offset, 4); offset += 4; memcpy(&parser->nro_embed_size, data + offset, 4); offset += 4; memcpy(&parser->nro_dynstr_off, data + offset, 4); offset += 4; memcpy(&parser->nro_dynstr_size, data + offset, 4); offset += 4; memcpy(&parser->nro_dynsym_off, data + offset, 4); offset += 4; memcpy(&parser->nro_dynsym_size, data + offset, 4); // Optional Assets if (parser->size > parser->nro_size) { offset = parser->nro_size; memcpy(parser->assets_magic, data + offset, 4); parser->assets_magic[4] = '\0'; if (strcmp(parser->assets_magic, "ASET") == 0) { parser->has_assets = 1; offset += 4; memcpy(&parser->assets_version, data + offset, 4); offset += 4; memcpy(&parser->assets_icon_off, data + offset, 8); offset += 8; memcpy(&parser->assets_icon_size, data + offset, 8); offset += 8; memcpy(&parser->assets_nacp_off, data + offset, 8); offset += 8; memcpy(&parser->assets_nacp_size, data + offset, 8); offset += 8; memcpy(&parser->assets_romfs_off, data + offset, 8); offset += 8; memcpy(&parser->assets_romfs_size, data + offset, 8); } else { printf("No valid Assets Section\n"); } } else { printf("No Assets Section\n"); } } void print_nro_properties(const NROParser* parser) { printf("RocrtHeader:\n"); printf(" ModuleHeaderLocation: %s\n", parser->rocrt_module_loc); printf(" Reserved: 0x%x\n", parser->rocrt_reserved); printf("NroHeader:\n"); printf(" Signature: %s\n", parser->nro_signature); printf(" Version: %u\n", parser->nro_version); printf(" Size: %u\n", parser->nro_size); printf(" Flags: 0x%x\n", parser->nro_flags); printf(" TextMemoryOffset: 0x%x\n", parser->nro_text_off); printf(" TextSize: %u\n", parser->nro_text_size); printf(" RoMemoryOffset: 0x%x\n", parser->nro_ro_off); printf(" RoSize: %u\n", parser->nro_ro_size); printf(" DataMemoryOffset: 0x%x\n", parser->nro_data_off); printf(" DataSize: %u\n", parser->nro_data_size); printf(" BssSize: %u\n", parser->nro_bss_size); printf(" Reserved1: 0x%x\n", parser->nro_reserved1); printf(" ModuleId: %s\n", parser->nro_module_id); printf(" DsoHandleOffset: 0x%x\n", parser->nro_dso_handle); printf(" Reserved2: 0x%x\n", parser->nro_reserved2); printf(" EmbeddedOffset: 0x%x\n", parser->nro_embed_off); printf(" EmbeddedSize: %u\n", parser->nro_embed_size); printf(" DynStrOffset: 0x%x\n", parser->nro_dynstr_off); printf(" DynStrSize: %u\n", parser->nro_dynstr_size); printf(" DynSymOffset: 0x%x\n", parser->nro_dynsym_off); printf(" DynSymSize: %u\n", parser->nro_dynsym_size); if (parser->has_assets) { printf("Assets:\n"); printf(" Magic: %s\n", parser->assets_magic); printf(" Version: %u\n", parser->assets_version); printf(" IconOffset: 0x%llx\n", (unsigned long long)parser->assets_icon_off); printf(" IconSize: %llu\n", (unsigned long long)parser->assets_icon_size); printf(" NacpOffset: 0x%llx\n", (unsigned long long)parser->assets_nacp_off); printf(" NacpSize: %llu\n", (unsigned long long)parser->assets_nacp_size); printf(" RomfsOffset: 0x%llx\n", (unsigned long long)parser->assets_romfs_off); printf(" RomfsSize: %llu\n", (unsigned long long)parser->assets_romfs_size); } } void write_nro(const NROParser* parser, const char* new_filepath, uint32_t new_version) { uint8_t* new_data = malloc(parser->size); memcpy(new_data, parser->data, parser->size); // Example update: version at 0x14 memcpy(new_data + 0x14, &new_version, 4); char* out_path = (char*)new_filepath; if (!out_path) { out_path = malloc(strlen(parser->filepath) + 10); sprintf(out_path, "%s.modified", parser->filepath); } FILE* f = fopen(out_path, "wb"); fwrite(new_data, 1, parser->size, f); fclose(f); printf("Written to %s\n", out_path); free(new_data); if (!new_filepath) free(out_path); } void free_nro_parser(NROParser* parser) { free(parser->filepath); free(parser->data); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } NROParser parser; memset(&parser, 0, sizeof(parser)); init_nro_parser(&parser, argv[1]); read_nro(&parser); print_nro_properties(&parser); // Example write: set version to 2 write_nro(&parser, NULL, 2); free_nro_parser(&parser); return 0; } // ===== end task-456 .NRO ===== // ===== task-457 .NRW [C++] ===== #include #include #include #include #include #include class NRWParser { private: std::string filepath; std::vector data; std::map tagNames; bool littleEndian = true; public: NRWParser(const std::string& fp) : filepath(fp) { tagNames[0x0001] = "MakerNoteVersion"; tagNames[0x0002] = "ISO"; // ... (truncated; add full) load(); } void load() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(data.data(), size); } template T read(uint32_t offset) { T val; memcpy(&val, data.data() + offset, sizeof(T)); if (!littleEndian) { // Swap bytes if big-endian; not needed for Nikon } return val; } void parse() { if (data[0] != 'I' || data[1] != 'I') { std::cout << "Not little-endian TIFF" << std::endl; return; } if (read(2) != 42) { std::cout << "Not a TIFF file" << std::endl; return; } uint32_t ifdOffset = read(4); uint32_t exifIfd = findExifIfd(ifdOffset); if (exifIfd == 0) { std::cout << "No EXIF IFD" << std::endl; return; } auto makerNote = findMakerNote(exifIfd); if (makerNote.first == 0) { std::cout << "No MakerNote" << std::endl; return; } parseMakerNote(makerNote.first); } uint32_t findExifIfd(uint32_t ifdOffset) { uint16_t numEntries = read(ifdOffset); ifdOffset += 2; for (uint16_t i = 0; i < numEntries; ++i) { uint16_t tag = read(ifdOffset); if (tag == 0x8769) { return read(ifdOffset + 8); } ifdOffset += 12; } return 0; } std::pair findMakerNote(uint32_t ifdOffset) { uint16_t numEntries = read(ifdOffset); ifdOffset += 2; for (uint16_t i = 0; i < numEntries; ++i) { uint16_t tag = read(ifdOffset); if (tag == 0x927c) { return {read(ifdOffset + 8), read(ifdOffset + 4)}; } ifdOffset += 12; } return {0, 0}; } void parseMakerNote(uint32_t offset) { char header[7]; memcpy(header, data.data() + offset, 6); header[6] = '\0'; if (strcmp(header, "Nikon") != 0) { std::cout << "Invalid MakerNote header" << std::endl; return; } offset += 8; uint16_t numEntries = read(offset); offset += 2; for (uint16_t i = 0; i < numEntries; ++i) { uint16_t tag = read(offset); uint16_t type = read(offset + 2); uint32_t count = read(offset + 4); uint32_t valOffset = read(offset + 8); std::string name = tagNames[tag]; if (name.empty()) name = "Unknown (0x" + std::to_string(tag) + ")"; std::string value = getValue(type, count, valOffset); std::cout << name << ": " << value << std::endl; offset += 12; } } std::string getValue(uint16_t type, uint32_t count, uint32_t offset) { if (type == 2) { // ASCII std::string str(data.begin() + offset, data.begin() + offset + count); return str.substr(0, str.find('\0')); } else if (type == 3) { return std::to_string(read(offset)); } else if (type == 4) { return std::to_string(read(offset)); } else if (type == 5) { return std::to_string(read(offset)) + "/" + std::to_string(read(offset + 4)); } else if (type == 7) { return "[binary]"; } else if (type == 10) { return std::to_string(read(offset)) + "/" + std::to_string(read(offset + 4)); } return "[unsupported]"; } void write(const std::string& newFilepath) { std::ofstream out(newFilepath, std::ios::binary); out.write(data.data(), data.size()); std::cout << "File written to " << newFilepath << std::endl; } }; int main() { NRWParser parser("example.nrw"); parser.parse(); parser.write("modified.nrw"); return 0; } // ===== end task-457 .NRW ===== // ===== task-458 .NRX [C] ===== #include #include #include #include typedef struct { char *filepath; uint8_t *data; size_t size; // Properties as array of strings for simplicity char *properties[10]; int prop_count; } NRXFile; NRXFile* nrx_create(const char *filepath) { NRXFile *nrx = malloc(sizeof(NRXFile)); nrx->filepath = strdup(filepath); nrx->data = NULL; nrx->size = 0; nrx->prop_count = 0; return nrx; } void nrx_read(NRXFile *nrx) { FILE *f = fopen(nrx->filepath, "rb"); if (!f) { printf("Error opening file\n"); return; } fseek(f, 0, SEEK_END); nrx->size = ftell(f); fseek(f, 0, SEEK_SET); nrx->data = malloc(nrx->size); fread(nrx->data, 1, nrx->size, f); fclose(f); // Decode header if (nrx->size < 74 || nrx->data[0] != 0x04 || strncmp((char*)&nrx->data[1], "V3 DAT file", 11) || nrx->data[68] != 0x2B || nrx->data[69] != 0xAD) { printf("Invalid NRX header\n"); return; } nrx->properties[nrx->prop_count++] = "Header: Valid"; // Decode footer uint32_t footer = *(uint32_t*)(&nrx->data[nrx->size - 4]); if (footer == 0xAABBCCDD) { // Assumes little-endian host nrx->properties[nrx->prop_count++] = "Footer: Valid"; } else { nrx->properties[nrx->prop_count++] = "Footer: Invalid or extra data"; } // Blocks const char *blockTypes[] = {"Sections", "Image Data", "Global Markers", "Contours", "Trees", "Text"}; for (int i = 0; i < 6; i++) { char buf[50]; sprintf(buf, "%s: Present (inferred)", blockTypes[i]); nrx->properties[nrx->prop_count++] = strdup(buf); } nrx->properties[nrx->prop_count++] = "Additional: Coordinates (X, Y, Z), Radius, Type, Index and Parent, Scaling factors, Shrinkage corrections"; } void nrx_print_properties(NRXFile *nrx) { printf("NRX File Properties:\n"); for (int i = 0; i < nrx->prop_count; i++) { printf("- %s\n", nrx->properties[i]); } } void nrx_write(NRXFile *nrx, const char *new_filepath) { FILE *f = fopen(new_filepath, "wb"); if (!f) { printf("Error writing file\n"); return; } // Header uint8_t header[70] = {0x04}; memcpy(&header[1], "V3 DAT file", 11); header[68] = 0x2B; header[69] = 0xAD; fwrite(header, 1, 70, f); // Dummy blocks uint8_t dummy[100] = {0}; fwrite(dummy, 1, 100, f); // Footer uint32_t footer = 0xAABBCCDD; fwrite(&footer, 4, 1, f); fclose(f); printf("Wrote basic NRX file to %s\n", new_filepath); } void nrx_destroy(NRXFile *nrx) { free(nrx->data); for (int i = 0; i < nrx->prop_count; i++) { if (i >= 2) free(nrx->properties[i]); // Free duplicated strings } free(nrx->filepath); free(nrx); } // Example usage // int main() { // NRXFile *nrx = nrx_create("example.nrx"); // nrx_read(nrx); // nrx_print_properties(nrx); // nrx_write(nrx, "new.nrx"); // nrx_destroy(nrx); // return 0; // } // ===== end task-458 .NRX ===== // ===== task-459 .NS1 [C] ===== #include #include #include #include #include typedef struct { char identifier[32]; uint32_t version; uint64_t create_ft; uint64_t end_ft; char comments[256]; int32_t ap_count; int32_t signal_count; // Records as dynamic array // ... (omitted for brevity; use linked list in full impl) } NS1Header; typedef struct { uint64_t timestamp_ft; char ssid[33]; uint8_t mac[6]; int16_t signal; int16_t noise; uint8_t channel; uint8_t wep; uint8_t net_type; double lat, lon, alt; } NS1Record; // Function prototypes void filetime_to_time(uint64_t ft, struct tm *tm); void print_header(NS1Header *h); void print_record(NS1Record *r, int idx); int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } FILE *f = fopen(argv[1], "rb"); if (!f) { perror("fopen"); return 1; } NS1Header header = {0}; fread(header.identifier, 1, 31, f); header.identifier[31] = '\0'; // Trim nulls char *nullpos = strchr(header.identifier, '\0'); if (nullpos) *nullpos = '\0'; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); // Version (skip padding) uint8_t pad; while (fread(&pad, 1, 1, f) == 1 && pad == 0); fseek(f, -1, SEEK_CUR); fread(&header.version, 4, 1, f); fread(&header.create_ft, 8, 1, f); fread(&header.end_ft, 8, 1, f); // Comments fread(header.comments, 1, 255, f); header.comments[255] = '\0'; nullpos = strchr(header.comments, '\0'); if (nullpos) *nullpos = '\0'; fread(&header.ap_count, 4, 1, f); fread(&header.signal_count, 4, 1, f); print_header(&header); // Parse records (first 5) int rec_idx = 0; while (ftell(f) < size && rec_idx < 5) { NS1Record rec = {0}; fread(&rec.timestamp_ft, 8, 1, f); // SSID fread(rec.ssid, 1, 32, f); rec.ssid[32] = '\0'; nullpos = strchr(rec.ssid, '\0'); if (nullpos) *nullpos = '\0'; fread(rec.mac, 1, 6, f); fread(&rec.signal, 2, 1, f); fread(&rec.noise, 2, 1, f); fread(&rec.channel, 1, 1, f); fread(&rec.wep, 1, 1, f); fread(&rec.net_type, 1, 1, f); fread(&rec.lat, 8, 1, f); fread(&rec.lon, 8, 1, f); fread(&rec.alt, 8, 1, f); // Skip extras fseek(f, 50, SEEK_CUR); print_record(&rec, rec_idx++); } fclose(f); return 0; } void filetime_to_time(uint64_t ft, struct tm *tm) { uint64_t ms = (ft / 10000) - 11644473600000ULL; time_t sec = ms / 1000; gmtime_r(&sec, tm); } void print_header(NS1Header *h) { printf("=== Header ===\n"); printf("identifier: %s\n", h->identifier); printf("version: %u\n", h->version); struct tm tm; filetime_to_time(h->create_ft, &tm); printf("create_time: %04d-%02d-%02d %02d:%02d:%02d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); if (h->end_ft) { filetime_to_time(h->end_ft, &tm); printf("end_time: %04d-%02d-%02d %02d:%02d:%02d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); } else { printf("end_time: Ongoing\n"); } printf("comments: %s\n", h->comments); printf("ap_count: %d\n", h->ap_count); printf("signal_count: %d\n\n", h->signal_count); } void print_record(NS1Record *r, int idx) { struct tm tm; filetime_to_time(r->timestamp_ft, &tm); printf("Record %d timestamp: %04d-%02d-%02d %02d:%02d:%02d\n", idx + 1, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); printf(" ssid: %s\n", r->ssid); printf(" mac: %02x:%02x:%02x:%02x:%02x:%02x\n", r->mac[0], r->mac[1], r->mac[2], r->mac[3], r->mac[4], r->mac[5]); printf(" signal: %d dBm\n", r->signal); printf(" noise: %d dBm\n", r->noise); printf(" channel: %u\n", r->channel); printf(" wep: %u\n", r->wep); printf(" net_type: %u\n", r->net_type); printf(" lat: %f\n", r->lat); printf(" lon: %f\n", r->lon); printf(" alt: %f m\n\n", r->alt); } // Write function (stub) void write_ns1(const char *output) { FILE *f = fopen(output, "wb"); if (f) { // Pack and write... fclose(f); } } // ===== end task-459 .NS1 ===== // ===== task-460 .NSA [C] ===== #include #include #include #include typedef struct { uint64_t offset; uint64_t size; char* path; int compressed; } NSFile; typedef struct { char magic[4]; uint8_t version; uint64_t file_count; uint64_t str_table_size; uint64_t file_table_offset; uint64_t file_table_size; uint64_t str_table_offset; NSFile* files; } NSAArchive; NSAArchive* load_nsa(const char* filepath) { FILE* f = fopen(filepath, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); NSAArchive* arch = malloc(sizeof(NSAArchive)); int offset = 0; memcpy(arch->magic, data + offset, 4); arch->magic[4] = '\0'; offset += 4; arch->version = data[offset]; offset += 1; arch->file_count = *(uint64_t*)(data + offset); offset += 8; // Assume LE arch->str_table_size = *(uint64_t*)(data + offset); offset += 8; arch->file_table_offset = *(uint64_t*)(data + offset); offset += 8; arch->file_table_size = *(uint64_t*)(data + offset); offset += 8; arch->str_table_offset = *(uint64_t*)(data + offset); offset += 8; offset += 32; // Skip // String table uint8_t* str_table = data + arch->str_table_offset; arch->files = malloc(sizeof(NSFile) * arch->file_count); int str_off = 0; for (uint64_t i = 0; i < arch->file_count; i++) { int path_len = 0; while (str_off + path_len < arch->str_table_size && str_table[str_off + path_len] != 0) path_len++; arch->files[i].path = malloc(path_len + 1); memcpy(arch->files[i].path, str_table + str_off, path_len); arch->files[i].path[path_len] = '\0'; str_off += path_len + 1; } // File table uint8_t* file_start = data + arch->file_table_offset; for (uint64_t i = 0; i < arch->file_count; i++) { int entry_off = i * 0x20; arch->files[i].offset = *(uint64_t*)(file_start + entry_off); uint64_t fsize = *(uint64_t*)(file_start + entry_off + 8); arch->files[i].compressed = (fsize & 0x10) != 0; arch->files[i].size = fsize & ~0x10ULL; // Skip 8 bytes // str_idx = *(uint64_t*)(file_start + entry_off + 0x18); } free(data); return arch; } void print_properties(NSAArchive* arch) { printf("NSA Archive Properties:\n"); printf(" magic: %s\n", arch->magic); printf(" version: %u\n", arch->version); printf(" file_count: %lu\n", arch->file_count); printf(" str_table_size: %lu\n", arch->str_table_size); printf(" file_table_offset: 0x%lx\n", arch->file_table_offset); printf(" file_table_size: %lu\n", arch->file_table_size); printf(" str_table_offset: 0x%lx\n", arch->str_table_offset); printf("\nFiles:\n"); for (uint64_t i = 0; i < arch->file_count; i++) { printf(" %s: offset=0x%lx, size=%lu, compressed=%d\n", arch->files[i].path, arch->files[i].offset, arch->files[i].size, arch->files[i].compressed); } } void extract_file(NSAArchive* arch, int idx, const char* outpath) { FILE* inf = fopen("input.nsa", "rb"); // Reopen for extract fseek(inf, arch->files[idx].offset, SEEK_SET); uint8_t* buf = malloc(arch->files[idx].size); fread(buf, 1, arch->files[idx].size, inf); fclose(inf); if (arch->files[idx].compressed) { // Stub Yaz0 } FILE* outf = fopen(outpath, "wb"); fwrite(buf, 1, arch->files[idx].size, outf); fclose(outf); free(buf); } void free_nsa(NSAArchive* arch) { for (uint64_t i = 0; i < arch->file_count; i++) free(arch->files[i].path); free(arch->files); free(arch); } int main(int argc, char** argv) { if (argc < 2) return 1; NSAArchive* nsa = load_nsa(argv[1]); if (nsa) { print_properties(nsa); // extract_file(nsa, 0, "out.bin"); free_nsa(nsa); } return 0; } // ===== end task-460 .NSA ===== // ===== task-461 .NSF [C++] ===== #include #include #include #include #include #include class NSFHandler { private: std::string filename; std::vector header; std::vector payload; std::string signature; unsigned char version; unsigned char total_songs; unsigned char starting_song; unsigned short load_address; unsigned short init_address; unsigned short play_address; std::string song_name; std::string artist; std::string copyright_info; unsigned short ntsc_speed; unsigned char bankswitch_init[8]; unsigned short pal_speed; unsigned char video_system; unsigned char extra_chips; unsigned char reserved[4]; public: NSFHandler(const std::string& fn) : filename(fn) { read(); } void read() { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) { throw std::runtime_error("Cannot open file"); } size_t size = file.tellg(); file.seekg(0); if (size < 128) { throw std::runtime_error("Invalid NSF file: too short"); } std::vector data(size); file.read(reinterpret_cast(data.data()), size); header.assign(data.begin(), data.begin() + 128); payload.assign(data.begin() + 128, data.end()); // Signature signature.assign(header.begin(), header.begin() + 5); // Version version = header[5]; // Total Songs total_songs = header[6]; // Starting Song starting_song = header[7]; // Load Address load_address = (header[9] << 8) | header[8]; // Init Address init_address = (header[11] << 8) | header[10]; // Play Address play_address = (header[13] << 8) | header[12]; // Song Name song_name = get_null_term_string(&header[14], 32); // Artist artist = get_null_term_string(&header[46], 32); // Copyright copyright_info = get_null_term_string(&header[78], 32); // NTSC Speed ntsc_speed = (header[111] << 8) | header[110]; // Bankswitch Init std::memcpy(bankswitch_init, &header[112], 8); // PAL Speed pal_speed = (header[121] << 8) | header[120]; // Video System video_system = header[122]; // Extra Chips extra_chips = header[123]; // Reserved std::memcpy(reserved, &header[124], 4); } std::string get_null_term_string(const unsigned char* ptr, size_t max_len) { std::string str; for (size_t i = 0; i < max_len; ++i) { if (ptr[i] == 0) break; str += static_cast(ptr[i]); } return str.empty() ? "" : str; } void print_properties() { std::cout << "NSF Properties:" << std::endl; std::cout << "Signature: " << signature << std::endl; std::cout << "Version: " << static_cast(version) << std::endl; std::cout << "Total Songs: " << static_cast(total_songs) << std::endl; std::cout << "Starting Song: " << static_cast(starting_song) << std::endl; std::cout << "Load Address: 0x" << std::hex << std::uppercase << std::setw(4) << std::setfill('0') << load_address << std::endl; std::cout << "Init Address: 0x" << std::hex << std::uppercase << std::setw(4) << std::setfill('0') << init_address << std::endl; std::cout << "Play Address: 0x" << std::hex << std::uppercase << std::setw(4) << std::setfill('0') << play_address << std::endl; std::cout << "Song Name: " << song_name << std::endl; std::cout << "Artist: " << artist << std::endl; std::cout << "Copyright: " << copyright_info << std::endl; std::cout << "NTSC Speed: " << ntsc_speed << std::endl; std::cout << "Bankswitch Init: ["; for (int i = 0; i < 8; ++i) { std::cout << "0x" << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << static_cast(bankswitch_init[i]); if (i < 7) std::cout << ", "; } std::cout << "]" << std::endl; std::cout << "PAL Speed: " << pal_speed << std::endl; std::cout << "Video System: 0x" << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << static_cast(video_system) << std::endl; std::cout << "Extra Sound Chips: 0x" << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << static_cast(extra_chips) << std::endl; std::cout << "Reserved: ["; for (int i = 0; i < 4; ++i) { std::cout << "0x" << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << static_cast(reserved[i]); if (i < 3) std::cout << ", "; } std::cout << "]" << std::endl; std::cout << "Data Payload Size: " << payload.size() << " bytes" << std::endl; } void write(const std::string& output_filename) { // Rebuild header header[5] = version; header[6] = total_songs; header[7] = starting_song; header[8] = load_address & 0xFF; header[9] = (load_address >> 8) & 0xFF; header[10] = init_address & 0xFF; header[11] = (init_address >> 8) & 0xFF; header[12] = play_address & 0xFF; header[13] = (play_address >> 8) & 0xFF; set_null_term_string(&header[14], song_name, 32); set_null_term_string(&header[46], artist, 32); set_null_term_string(&header[78], copyright_info, 32); header[110] = ntsc_speed & 0xFF; header[111] = (ntsc_speed >> 8) & 0xFF; std::memcpy(&header[112], bankswitch_init, 8); header[120] = pal_speed & 0xFF; header[121] = (pal_speed >> 8) & 0xFF; header[122] = video_system; header[123] = extra_chips; std::memcpy(&header[124], reserved, 4); std::ofstream out(output_filename, std::ios::binary); if (!out) { throw std::runtime_error("Cannot write file"); } out.write(reinterpret_cast(header.data()), 128); out.write(reinterpret_cast(payload.data()), payload.size()); } void set_null_term_string(unsigned char* ptr, const std::string& str, size_t max_len) { size_t len = std::min(str.length(), max_len - 1); std::memcpy(ptr, str.c_str(), len); ptr[len] = 0; std::memset(ptr + len + 1, 0, max_len - len - 1); } }; int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Usage: " << argv[0] << " [output.nsf]" << std::endl; return 1; } try { NSFHandler handler(argv[1]); handler.print_properties(); if (argc > 2) { handler.write(argv[2]); std::cout << "Written to " << argv[2] << std::endl; } } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } // ===== end task-461 .NSF ===== // ===== task-462 .NSV [C] ===== #include #include #include #include typedef struct { char* filename; uint8_t* data; size_t size; struct { uint32_t header_length; uint32_t file_length; uint32_t metadata_length; uint32_t toc_entries; uint32_t toc_size; char* metadata; uint32_t* toc; } header; struct { char video_codec[5]; char audio_codec[5]; uint16_t width; uint16_t height; uint8_t framerate; int16_t sync_offset; } bitstream_props; } NSVFile; NSVFile* nsv_create(const char* filename) { NSVFile* nsv = malloc(sizeof(NSVFile)); nsv->filename = strdup(filename); nsv->data = NULL; nsv->size = 0; memset(&nsv->header, 0, sizeof(nsv->header)); memset(&nsv->bitstream_props, 0, sizeof(nsv->bitstream_props)); return nsv; } void nsv_read(NSVFile* nsv) { FILE* f = fopen(nsv->filename, "rb"); if (!f) return; fseek(f, 0, SEEK_END); nsv->size = ftell(f); fseek(f, 0, SEEK_SET); nsv->data = malloc(nsv->size); fread(nsv->data, 1, nsv->size, f); fclose(f); nsv_decode(nsv); } void nsv_decode(NSVFile* nsv) { size_t offset = 0; char sig[5] = {0}; memcpy(sig, nsv->data + offset, 4); offset += 4; if (strcmp(sig, "NSVf") == 0) { memcpy(&nsv->header.header_length, nsv->data + offset, 4); offset += 4; memcpy(&nsv->header.file_length, nsv->data + offset, 4); offset += 4; memcpy(&nsv->header.metadata_length, nsv->data + offset, 4); offset += 4; memcpy(&nsv->header.toc_entries, nsv->data + offset, 4); offset += 4; memcpy(&nsv->header.toc_size, nsv->data + offset, 4); offset += 4; nsv->header.metadata = malloc(nsv->header.metadata_length + 1); memcpy(nsv->header.metadata, nsv->data + offset, nsv->header.metadata_length); nsv->header.metadata[nsv->header.metadata_length] = '\0'; offset += nsv->header.metadata_length; nsv->header.toc = malloc(nsv->header.toc_entries * sizeof(uint32_t)); for (uint32_t i = 0; i < nsv->header.toc_entries; i++) { memcpy(&nsv->header.toc[i], nsv->data + offset, 4); offset += 4; } } // Find first sync frame while (offset < nsv->size - 4) { char sync_sig[5] = {0}; memcpy(sync_sig, nsv->data + offset, 4); if (strcmp(sync_sig, "NSVs") == 0) { offset += 4; memcpy(nsv->bitstream_props.video_codec, nsv->data + offset, 4); nsv->bitstream_props.video_codec[4] = '\0'; offset += 4; memcpy(nsv->bitstream_props.audio_codec, nsv->data + offset, 4); nsv->bitstream_props.audio_codec[4] = '\0'; offset += 4; memcpy(&nsv->bitstream_props.width, nsv->data + offset, 2); offset += 2; memcpy(&nsv->bitstream_props.height, nsv->data + offset, 2); offset += 2; nsv->bitstream_props.framerate = nsv->data[offset]; offset += 1; memcpy(&nsv->bitstream_props.sync_offset, nsv->data + offset, 2); offset += 2; break; } offset++; } } void nsv_print_properties(NSVFile* nsv) { printf("NSV File Properties:\n"); printf("- Header Length: %u\n", nsv->header.header_length); printf("- File Length: %u\n", nsv->header.file_length); printf("- Metadata Length: %u\n", nsv->header.metadata_length); printf("- TOC Entries: %u\n", nsv->header.toc_entries); printf("- TOC Size: %u\n", nsv->header.toc_size); printf("- Metadata: %s\n", nsv->header.metadata ? nsv->header.metadata : "None"); printf("- TOC: ["); for (uint32_t i = 0; i < nsv->header.toc_entries; i++) { printf("%u%s", nsv->header.toc[i], i < nsv->header.toc_entries - 1 ? ", " : ""); } printf("]\n"); printf("- Bitstream Video Codec: %s\n", nsv->bitstream_props.video_codec); printf("- Bitstream Audio Codec: %s\n", nsv->bitstream_props.audio_codec); printf("- Bitstream Width: %u\n", nsv->bitstream_props.width); printf("- Bitstream Height: %u\n", nsv->bitstream_props.height); printf("- Bitstream Framerate: %u\n", nsv->bitstream_props.framerate); printf("- Bitstream Sync Offset: %d\n", nsv->bitstream_props.sync_offset); } void nsv_write(NSVFile* nsv, const char* new_filename) { FILE* f = fopen(new_filename, "wb"); if (f) { fwrite(nsv->data, 1, nsv->size, f); fclose(f); } } void nsv_destroy(NSVFile* nsv) { free(nsv->data); free(nsv->header.metadata); free(nsv->header.toc); free(nsv->filename); free(nsv); } // Example usage: // int main() { // NSVFile* nsv = nsv_create("sample.nsv"); // nsv_read(nsv); // nsv_print_properties(nsv); // nsv_write(nsv, "output.nsv"); // nsv_destroy(nsv); // return 0; // } // ===== end task-462 .NSV ===== // ===== task-463 .NUMBERS [C] ===== #include #include #include #include // Requires libzip library struct NumbersFileHandler { const char* filepath; char* extension; long file_size; char** internal_files; int file_count; const char* mime_type; const char* developer; const char* category; const char* magic_number; }; struct NumbersFileHandler* create_handler(const char* filepath) { struct NumbersFileHandler* handler = malloc(sizeof(struct NumbersFileHandler)); handler->filepath = filepath; handler->extension = ".numbers"; handler->mime_type = "application/vnd.apple.numbers"; handler->developer = "Apple Inc."; handler->category = "Spreadsheet"; handler->magic_number = "0x504B0304"; handler->internal_files = NULL; handler->file_count = 0; return handler; } int read_properties(struct NumbersFileHandler* handler) { FILE* file = fopen(handler->filepath, "rb"); if (!file) return -1; fseek(file, 0, SEEK_END); handler->file_size = ftell(file); fclose(file); zip_t* za = zip_open(handler->filepath, ZIP_RDONLY, NULL); if (!za) return -1; int num_entries = zip_get_num_entries(za, 0); handler->internal_files = malloc(num_entries * sizeof(char*)); for (int i = 0; i < num_entries; i++) { const char* name = zip_get_name(za, i, 0); handler->internal_files[i] = strdup(name); } handler->file_count = num_entries; zip_close(za); return 0; } void print_properties(struct NumbersFileHandler* handler) { printf("file_extension: %s\n", handler->extension); printf("file_size: %ld\n", handler->file_size); printf("mime_type: %s\n", handler->mime_type); printf("developer: %s\n", handler->developer); printf("category: %s\n", handler->category); printf("magic_number: %s\n", handler->magic_number); printf("internal_files:\n"); for (int i = 0; i < handler->file_count; i++) { printf(" - %s\n", handler->internal_files[i]); } } int write_modified(struct NumbersFileHandler* handler, const char* output_path, int add_note) { zip_t* za_in = zip_open(handler->filepath, ZIP_RDONLY, NULL); if (!za_in) return -1; zip_t* za_out = zip_open(output_path, ZIP_CREATE | ZIP_TRUNCATE, NULL); if (!za_out) { zip_close(za_in); return -1; } int num_entries = zip_get_num_entries(za_in, 0); for (int i = 0; i < num_entries; i++) { zip_source_t* src = zip_file_add(za_out, zip_get_name(za_in, i, 0), zip_file_get_source(za_in, i), ZIP_FL_ENC_UTF_8); if (!src) { zip_close(za_in); zip_close(za_out); return -1; } } if (add_note) { zip_source_t* src = zip_source_buffer(za_out, "Modified by NumbersFileHandler", 30, 0); zip_file_add(za_out, "note.txt", src, ZIP_FL_ENC_UTF_8); } zip_close(za_in); zip_close(za_out); return 0; } void destroy_handler(struct NumbersFileHandler* handler) { for (int i = 0; i < handler->file_count; i++) { free(handler->internal_files[i]); } free(handler->internal_files); free(handler); } // Example usage: // int main() { // struct NumbersFileHandler* handler = create_handler("example.numbers"); // if (read_properties(handler) == 0) { // print_properties(handler); // write_modified(handler, "modified.numbers", 1); // } // destroy_handler(handler); // return 0; // } // ===== end task-463 .NUMBERS ===== // ===== task-464 .NWD [C] ===== #include #include #include typedef struct { char* filepath; unsigned char* data; size_t size; } NWDFileHandler; NWDFileHandler* createNWDHandler(const char* filepath) { NWDFileHandler* handler = (NWDFileHandler*)malloc(sizeof(NWDFileHandler)); handler->filepath = strdup(filepath); handler->data = NULL; handler->size = 0; return handler; } void openFile(NWDFileHandler* handler) { if (strstr(handler->filepath, ".nwd") == NULL) { fprintf(stderr, "Invalid .NWD file.\n"); return; } FILE* file = fopen(handler->filepath, "rb"); if (!file) { fprintf(stderr, "Could not open file.\n"); return; } fseek(file, 0, SEEK_END); handler->size = ftell(file); fseek(file, 0, SEEK_SET); handler->data = (unsigned char*)malloc(handler->size); fread(handler->data, 1, handler->size, file); fclose(file); } void decode(NWDFileHandler* handler) { printf("Decoding not implemented due to proprietary format.\n"); } void readProperties(NWDFileHandler* handler) { printf("Reading properties not implemented due to proprietary format.\n"); } void writeProperties(NWDFileHandler* handler) { printf("Writing not implemented due to proprietary format.\n"); } void printProperties(NWDFileHandler* handler) { if (!handler->data) { fprintf(stderr, "File not opened.\n"); return; } printf("Hex dump of first 256 bytes:\n"); for (size_t i = 0; i < 256 && i < handler->size; i++) { printf("%02X ", handler->data[i]); if ((i + 1) % 16 == 0) printf("\n"); } printf("\nNote: Full property printing requires proprietary specifications.\n"); } void destroyNWDHandler(NWDFileHandler* handler) { free(handler->data); free(handler->filepath); free(handler); } // Example usage: // int main() { // NWDFileHandler* handler = createNWDHandler("path/to/file.nwd"); // openFile(handler); // printProperties(handler); // destroyNWDHandler(handler); // return 0; // } // ===== end task-464 .NWD ===== // ===== task-465 .NWF [C++] ===== #include #include #include #include #include #include struct Item { std::string name; std::map parameters; std::vector conductors; std::vector pins; std::vector> attachments; std::string spool; // For WIRE/CABLE std::string num_conductors; // For CABLE_SPOOL }; class NWFHandler { private: std::map> data; public: NWFHandler() { data["wire_spools"] = {}; data["cable_spools"] = {}; data["connectors"] = {}; data["components"] = {}; data["wires"] = {}; data["cables"] = {}; data["rails"] = {}; } void read(const std::string& filepath) { std::ifstream file(filepath); if (!file.is_open()) return; std::string line; Item* currentItem = nullptr; std::string currentType; Item* currentSub = nullptr; while (std::getline(file, line)) { std::istringstream iss(line); std::string token; std::vector parts; while (iss >> token) parts.push_back(token); if (parts.empty() || parts[0] == "!" || parts[0] == "#") continue; std::string command = parts[0]; if (command == "NEW") { currentType = parts[1]; Item newItem; newItem.name = (parts.size() > 2 ? parts[2] : ""); if (currentType == "CABLE_SPOOL") { newItem.num_conductors = (parts.size() > 3 ? parts[3] : "0"); } else if (currentType == "WIRE" || currentType == "CABLE") { newItem.spool = (parts.size() > 3 ? parts[3] : ""); } data[currentType + "s"].push_back(newItem); currentItem = &data[currentType + "s"].back(); currentSub = nullptr; } else if (command == "PARAMETER" && currentItem) { if (parts.size() < 3) continue; std::string key = parts[1]; std::string value; for (size_t i = 2; i < parts.size(); ++i) value += (i > 2 ? " " : "") + parts[i]; (currentSub ? currentSub : currentItem)->parameters[key] = value; } else if (command == "PARAMETERS" && currentItem) { std::vector names(parts.begin() + 1, parts.end()); (currentSub ? currentSub : currentItem)->temp_names = names; // Use a temp vector member (add to struct) } else if (command == "VALUES" && currentItem && !(currentSub ? currentSub : currentItem)->temp_names.empty()) { auto& names = (currentSub ? currentSub : currentItem)->temp_names; for (size_t i = 1; i < parts.size() && (i - 1) < names.size(); ++i) { (currentSub ? currentSub : currentItem)->parameters[names[i - 1]] = parts[i]; } names.clear(); } else if (command == "CONDUCTOR" && currentItem && (currentType == "CABLE" || currentType == "CABLE_SPOOL")) { Item cond; cond.name = (parts.size() > 2 ? parts[2] : ""); cond.parameters["id"] = parts[1]; // Store id as param for simplicity currentItem->conductors.push_back(cond); currentSub = ¤tItem->conductors.back(); } else if (command == "PIN" && currentItem && (currentType == "CONNECTOR" || currentType == "COMPONENT")) { Item pin; pin.name = parts[1]; currentItem->pins.push_back(pin); currentSub = ¤tItem->pins.back(); } else if (command == "ATTACH" && currentItem) { std::map attach; attach["from_comp"] = parts[1]; attach["from_pin"] = parts[2]; attach["to_comp"] = parts[3]; attach["to_pin"] = (parts.size() > 4 ? parts[4] : ""); (currentSub ? currentSub : currentItem)->attachments.push_back(attach); } } file.close(); } void printProperties() const { // Simple JSON-like output for (const auto& entry : data) { std::cout << "\"" << entry.first << "\": [\n"; for (const auto& item : entry.second) { std::cout << " {\n"; std::cout << " \"name\": \"" << item.name << "\",\n"; if (!item.spool.empty()) std::cout << " \"spool\": \"" << item.spool << "\",\n"; if (!item.num_conductors.empty()) std::cout << " \"num_conductors\": \"" << item.num_conductors << "\",\n"; std::cout << " \"parameters\": {\n"; for (const auto& p : item.parameters) { std::cout << " \"" << p.first << "\": \"" << p.second << "\",\n"; } std::cout << " },\n"; std::cout << " \"conductors\": [\n"; for (const auto& cond : item.conductors) { std::cout << " { \"name\": \"" << cond.name << "\", \"parameters\": {"; for (const auto& p : cond.parameters) std::cout << "\"" << p.first << "\": \"" << p.second << "\", "; std::cout << "}, \"attachments\": ["; for (const auto& att : cond.attachments) { std::cout << "{ \"from_comp\": \"" << att.at("from_comp") << "\", \"from_pin\": \"" << att.at("from_pin") << "\", \"to_comp\": \"" << att.at("to_comp") << "\", \"to_pin\": \"" << att.at("to_pin") << "\" },"; } std::cout << "] },\n"; } std::cout << " ],\n"; std::cout << " \"pins\": [\n"; for (const auto& pin : item.pins) { std::cout << " { \"name\": \"" << pin.name << "\", \"parameters\": {"; for (const auto& p : pin.parameters) std::cout << "\"" << p.first << "\": \"" << p.second << "\", "; std::cout << "} },\n"; } std::cout << " ],\n"; std::cout << " \"attachments\": [\n"; for (const auto& att : item.attachments) { std::cout << " { \"from_comp\": \"" << att.at("from_comp") << "\", \"from_pin\": \"" << att.at("from_pin") << "\", \"to_comp\": \"" << att.at("to_comp") << "\", \"to_pin\": \"" << att.at("to_pin") << "\" },\n"; } std::cout << " ]\n },\n"; } std::cout << "],\n"; } } void write(const std::string& filepath) const { std::ofstream file(filepath); if (!file.is_open()) return; for (const auto& entry : data) { std::string category = entry.first; for (const auto& item : entry.second) { std::string type = category.substr(0, category.size() - 1); std::transform(type.begin(), type.end(), type.begin(), ::toupper); if (category == "wire_spools") { file << "NEW WIRE_SPOOL " << item.name << "\n"; } else if (category == "cable_spools") { file << "NEW CABLE_SPOOL " << item.name << " " << item.num_conductors << "\n"; } else if (category == "connectors") { file << "NEW CONNECTOR " << item.name << "\n"; } else if (category == "components") { file << "NEW COMPONENT " << item.name << "\n"; } else if (category == "wires") { file << "NEW WIRE " << item.name << " " << item.spool << "\n"; } else if (category == "cables") { file << "NEW CABLE " << item.name << " " << item.spool << "\n"; } else if (category == "rails") { file << "NEW RAIL " << item.name << "\n"; } for (const auto& p : item.parameters) { file << "PARAMETER " << p.first << " " << p.second << "\n"; } for (const auto& cond : item.conductors) { file << "CONDUCTOR " << cond.parameters.at("id") << " " << cond.name << "\n"; for (const auto& p : cond.parameters) { if (p.first != "id") file << "PARAMETER " << p.first << " " << p.second << "\n"; } for (const auto& att : cond.attachments) { file << "ATTACH " << att.at("from_comp") << " " << att.at("from_pin") << " " << att.at("to_comp") << " " << att.at("to_pin") << "\n"; } } for (const auto& pin : item.pins) { file << "PIN " << pin.name << "\n"; for (const auto& p : pin.parameters) { file << "PARAMETER " << p.first << " " << p.second << "\n"; } } for (const auto& att : item.attachments) { file << "ATTACH " << att.at("from_comp") << " " << att.at("from_pin") << " " << att.at("to_comp") << " " << att.at("to_pin") << "\n"; } file << "\n"; } } file.close(); } }; // Note: Add std::vector temp_names; to Item struct for PARAMETERS handling. // Example usage: // int main() { // NWFHandler handler; // handler.read("example.nwf"); // handler.printProperties(); // handler.write("output.nwf"); // return 0; // } // ===== end task-465 .NWF ===== // ===== task-466 .NXS [C] ===== #include #include #include #include #include #define MAX_TAXA 100 #define MAX_SETS 50 #define MAX_TREES 50 #define MAX_LINE 1024 #define MAX_COMMENT 1024 typedef struct { char *name; char *val; } KeyVal; typedef struct { char *name; char *desc; KeyVal *translate; int trans_count; } Tree; typedef struct { char *header; int ntax; int nchar; char *datatype; char missing; char gap; int interleave; char **taxlabels; char **matrix_data; int num_taxa; KeyVal *sets; int sets_count; KeyVal *assumptions; int ass_count; Tree *trees; int num_trees; char **comments; int comments_count; } NXS; void init_NXS(NXS *self) { self->header = strdup("#NEXUS"); self->ntax = 0; self->nchar = 0; self->datatype = strdup("standard"); self->missing = '?'; self->gap = '-'; self->interleave = 0; self->taxlabels = calloc(MAX_TAXA, sizeof(char*)); self->matrix_data = calloc(MAX_TAXA, sizeof(char*)); self->num_taxa = 0; self->sets = calloc(MAX_SETS, sizeof(KeyVal)); self->sets_count = 0; self->assumptions = calloc(MAX_SETS, sizeof(KeyVal)); self->ass_count = 0; self->trees = calloc(MAX_TREES, sizeof(Tree)); self->num_trees = 0; self->comments = calloc(MAX_COMMENT, sizeof(char*)); self->comments_count = 0; for (int i = 0; i < MAX_TREES; i++) { self->trees[i].translate = calloc(MAX_TAXA, sizeof(KeyVal)); self->trees[i].trans_count = 0; } } void free_NXS(NXS *self) { free(self->header); free(self->datatype); for (int i = 0; i < self->num_taxa; i++) { free(self->taxlabels[i]); free(self->matrix_data[i]); } free(self->taxlabels); free(self->matrix_data); for (int i = 0; i < self->sets_count; i++) { free(self->sets[i].name); free(self->sets[i].val); } free(self->sets); for (int i = 0; i < self->ass_count; i++) { free(self->assumptions[i].name); free(self->assumptions[i].val); } free(self->assumptions); for (int i = 0; i < self->num_trees; i++) { free(self->trees[i].name); free(self->trees[i].desc); for (int j = 0; j < self->trees[i].trans_count; j++) { free(self->trees[i].translate[j].name); free(self->trees[i].translate[j].val); } free(self->trees[i].translate); } free(self->trees); for (int i = 0; i < self->comments_count; i++) { free(self->comments[i]); } free(self->comments); } char* read_file(const char* filename) { FILE* fp = fopen(filename, "r"); if (!fp) return NULL; fseek(fp, 0, SEEK_END); long size = ftell(fp); fseek(fp, 0, SEEK_SET); char* text = malloc(size + 1); fread(text, 1, size, fp); text[size] = '\0'; fclose(fp); return text; } void parse_comments(NXS *self, const char *text) { regex_t regex; regcomp(®ex, "\\[\\s*[^!].*?\\]", REG_EXTENDED); regmatch_t match; int offset = 0; while (regexec(®ex, text + offset, 1, &match, 0) == 0 && self->comments_count < MAX_COMMENT) { int len = match.rm_eo - match.rm_so; self->comments[self->comments_count] = strndup(text + offset + match.rm_so, len); self->comments_count++; offset += match.rm_eo; } regfree(®ex); } void parse(NXS *self, char *text) { if (strncmp(text, "#NEXUS", 6) != 0) { fprintf(stderr, "Not a valid NEXUS file\n"); return; } parse_comments(self, text); char *block_start = strstr(text, "begin"); while (block_start) { char block_name[50]; sscanf(block_start, "begin %49s;", block_name); char *content_start = block_start + strlen("begin ") + strlen(block_name) + 1; char *end = strstr(content_start, "end;"); if (!end) break; char content[MAX_LINE * 10]; strncpy(content, content_start, end - content_start); content[end - content_start] = '\0'; if (strcasecmp(block_name, "data") == 0 || strcasecmp(block_name, "characters") == 0) { char *cmd = strtok(content, ";"); while (cmd) { cmd = strstr(cmd, "dimensions") ? cmd : strtok(NULL, ";"); if (!cmd) break; if (strstr(cmd, "dimensions")) { sscanf(cmd, "dimensions ntax=%d nchar=%d", &self->ntax, &self->nchar); } else if (strstr(cmd, "format")) { char *fmt = cmd + strlen("format"); char *dt = strstr(fmt, "datatype="); if (dt) sscanf(dt, "datatype=%s", self->datatype); char *ms = strstr(fmt, "missing="); if (ms) sscanf(ms, "missing=%c", &self->missing); char *gp = strstr(fmt, "gap="); if (gp) sscanf(gp, "gap=%c", &self->gap); char *inter = strstr(fmt, "interleave="); if (inter) { char inter_val[4]; sscanf(inter, "interleave=%3s", inter_val); self->interleave = strcasecmp(inter_val, "yes") == 0; } } else if (strstr(cmd, "matrix")) { char *mat = cmd + strlen("matrix"); char *line = strtok(mat, "\n"); while (line && self->num_taxa < MAX_TAXA) { while (*line == ' ') line++; if (*line) { char tax[100], data[MAX_LINE]; if (sscanf(line, "'%99[^']' %[^\n]", tax, data) == 2 || sscanf(line, "%99s %[^\n]", tax, data) == 2) { int idx = -1; for (int i = 0; i < self->num_taxa; i++) { if (strcmp(self->taxlabels[i], tax) == 0) { idx = i; break; } } if (idx == -1) { idx = self->num_taxa++; self->taxlabels[idx] = strdup(tax); self->matrix_data[idx] = strdup(data); } else { char *new_data = malloc(strlen(self->matrix_data[idx]) + strlen(data) + 1); strcpy(new_data, self->matrix_data[idx]); strcat(new_data, data); free(self->matrix_data[idx]); self->matrix_data[idx] = new_data; } } } line = strtok(NULL, "\n"); } } } } else if (strcasecmp(block_name, "taxa") == 0) { char *cmd = strtok(content, ";"); while (cmd) { if (strstr(cmd, "taxlabels")) { char *labels = cmd + strlen("taxlabels"); char *tax = strtok(labels, " \n"); while (tax && self->num_taxa < MAX_TAXA) { self->taxlabels[self->num_taxa++] = strdup(tax); tax = strtok(NULL, " \n"); } } cmd = strtok(NULL, ";"); } } else if (strcasecmp(block_name, "sets") == 0) { char *cmd = strtok(content, ";"); while (cmd) { if (strstr(cmd, "charset") || strstr(cmd, "taxset")) { char set_type[10], set_name[50], set_val[MAX_LINE]; sscanf(cmd, "%9s %49s = %[^\n]", set_type, set_name, set_val); if (self->sets_count < MAX_SETS) { char *full_name = malloc(strlen(set_type) + strlen(set_name) + 2); sprintf(full_name, "%s_%s", set_type, set_name); self->sets[self->sets_count].name = full_name; self->sets[self->sets_count].val = strdup(set_val); self->sets_count++; } } cmd = strtok(NULL, ";"); } } else if (strcasecmp(block_name, "assumptions") == 0) { char *cmd = strtok(content, ";"); while (cmd) { if (strstr(cmd, "exset")) { char ass_name[50], ass_val[MAX_LINE]; if (sscanf(cmd, "exset %49s = %[^\n]", ass_name, ass_val) != 2) { strcpy(ass_name, "default"); sscanf(cmd, "exset = %[^\n]", ass_val); } if (self->ass_count < MAX_SETS) { self->assumptions[self->ass_count].name = strdup(ass_name); self->assumptions[self->ass_count].val = strdup(ass_val); self->ass_count++; } } cmd = strtok(NULL, ";"); } } else if (strcasecmp(block_name, "trees") == 0) { char *cmd = strtok(content, ";"); int trans_idx = 0; int tree_idx = self->num_trees; while (cmd && tree_idx < MAX_TREES) { if (strstr(cmd, "translate")) { char *trans = cmd + strlen("translate"); char *pair = strtok(trans, ","); while (pair && trans_idx < MAX_TAXA) { char token[50], tname[100]; sscanf(pair, "%49s %99s", token, tname); self->trees[tree_idx].translate[trans_idx].name = strdup(token); self->trees[tree_idx].translate[trans_idx].val = strdup(tname); trans_idx++; pair = strtok(NULL, ","); } self->trees[tree_idx].trans_count = trans_idx; } else if (strstr(cmd, "tree")) { char name[50], desc[MAX_LINE]; sscanf(cmd, "tree %49s = %[^\n]", name, desc); self->trees[tree_idx].name = strdup(name); self->trees[tree_idx].desc = strdup(desc); tree_idx++; self->num_trees = tree_idx; trans_idx = 0; // Reset for next tree } cmd = strtok(NULL, ";"); } } block_start = strstr(end + 4, "begin"); } } void read_NXS(NXS *self, const char *filename) { char *text = read_file(filename); if (text) { parse(self, text); free(text); } } void print_NXS(const NXS *self) { printf("Header: %s\n", self->header); printf("ntax: %d\n", self->ntax); printf("nchar: %d\n", self->nchar); printf("datatype: %s\n", self->datatype); printf("missing: %c\n", self->missing); printf("gap: %c\n", self->gap); printf("interleave: %d\n", self->interleave); printf("taxlabels:\n"); for (int i = 0; i < self->num_taxa; i++) { printf(" %s\n", self->taxlabels[i]); } printf("matrix:\n"); for (int i = 0; i < self->num_taxa; i++) { printf(" %s: %s\n", self->taxlabels[i], self->matrix_data[i]); } printf("sets:\n"); for (int i = 0; i < self->sets_count; i++) { printf(" %s: %s\n", self->sets[i].name, self->sets[i].val); } printf("assumptions:\n"); for (int i = 0; i < self->ass_count; i++) { printf(" %s: %s\n", self->assumptions[i].name, self->assumptions[i].val); } printf("trees:\n"); for (int i = 0; i < self->num_trees; i++) { printf(" %s: %s\n", self->trees[i].name, self->trees[i].desc); if (self->trees[i].trans_count > 0) { printf(" translate:\n"); for (int j = 0; j < self->trees[i].trans_count; j++) { printf(" %s: %s\n", self->trees[i].translate[j].name, self->trees[i].translate[j].val); } } } printf("comments:\n"); for (int i = 0; i < self->comments_count; i++) { printf(" %s\n", self->comments[i]); } } void write_NXS(const NXS *self, const char *filename) { FILE *fp = fopen(filename, "w"); if (!fp) return; fprintf(fp, "%s\n", self->header); if (self->num_taxa > 0) { fprintf(fp, "begin taxa;\n"); fprintf(fp, " dimensions ntax=%d;\n", self->ntax); fprintf(fp, " taxlabels"); for (int i = 0; i < self->num_taxa; i++) { fprintf(fp, " '%s'", self->taxlabels[i]); } fprintf(fp, ";\n"); fprintf(fp, "end;\n"); } fprintf(fp, "begin data;\n"); fprintf(fp, " dimensions ntax=%d nchar=%d;\n", self->ntax, self->nchar); fprintf(fp, " format datatype=%s missing=%c gap=%c interleave=%s;\n", self->datatype, self->missing, self->gap, self->interleave ? "yes" : "no"); fprintf(fp, " matrix\n"); for (int i = 0; i < self->num_taxa; i++) { fprintf(fp, " '%s' %s\n", self->taxlabels[i], self->matrix_data[i]); } fprintf(fp, " ;\n"); fprintf(fp, "end;\n"); if (self->sets_count > 0) { fprintf(fp, "begin sets;\n"); for (int i = 0; i < self->sets_count; i++) { fprintf(fp, " %s = %s;\n", self->sets[i].name, self->sets[i].val); } fprintf(fp, "end;\n"); } if (self->ass_count > 0) { fprintf(fp, "begin assumptions;\n"); for (int i = 0; i < self->ass_count; i++) { fprintf(fp, " exset %s = %s;\n", self->assumptions[i].name, self->assumptions[i].val); } fprintf(fp, "end;\n"); } if (self->num_trees > 0) { fprintf(fp, "begin trees;\n"); for (int i = 0; i < self->num_trees; i++) { if (self->trees[i].trans_count > 0) { fprintf(fp, " translate\n"); for (int j = 0; j < self->trees[i].trans_count; j++) { fprintf(fp, " %s %s,\n", self->trees[i].translate[j].name, self->trees[i].translate[j].val); } fprintf(fp, " ;\n"); } fprintf(fp, " tree %s = %s;\n", self->trees[i].name, self->trees[i].desc); } fprintf(fp, "end;\n"); } // Comments not written fclose(fp); } // ===== end task-466 .NXS ===== // ===== task-467 .O [C] ===== #include #include #include typedef struct { char* filename; uint8_t* data; size_t size; } OMFHandler; void omf_read(OMFHandler* handler) { FILE* f = fopen(handler->filename, "rb"); fseek(f, 0, SEEK_END); handler->size = ftell(f); fseek(f, 0, SEEK_SET); handler->data = malloc(handler->size); fread(handler->data, 1, handler->size, f); fclose(f); } void omf_print_properties(OMFHandler* handler) { size_t offset = 0; while (offset < handler->size) { uint8_t type = handler->data[offset]; offset += 1; uint16_t length = handler->data[offset] + (handler->data[offset+1] << 8); offset += 2; printf("Record Type: 0x%02x\n", type); printf("Record Length: %u\n", length); printf("Content: "); for (int i = 0; i < length - 1; i++) { printf("%u ", handler->data[offset + i]); } printf("\n"); offset += length - 1; uint8_t checksum = handler->data[offset]; offset += 1; printf("Checksum: 0x%02x\n---\n", checksum); } } void omf_write(OMFHandler* handler, const char* new_filename) { FILE* f = fopen(new_filename, "wb"); fwrite(handler->data, 1, handler->size, f); fclose(f); } void omf_free(OMFHandler* handler) { free(handler->data); } // Example usage // int main() { // OMFHandler handler = {.filename = "example.o"}; // omf_read(&handler); // omf_print_properties(&handler); // omf_write(&handler, "copy.o"); // omf_free(&handler); // return 0; // } // ===== end task-467 .O ===== // ===== task-468 .OBJ [C++] ===== #include #include #include #include #include class OBJHandler { private: std::string filepath; std::vector> vertices; std::vector> texture_coords; std::vector> normals; std::vector> param_vertices; std::vector> faces; std::vector> lines; std::vector> objects; std::vector> groups; std::vector> smoothing_groups; std::vector> materials; std::vector> mtllib; std::vector comments; public: OBJHandler(const std::string& fp) : filepath(fp) { read(); } void read() { std::ifstream file(filepath); std::string line; while (std::getline(file, line)) { std::istringstream iss(line); std::string keyword; iss >> keyword; if (keyword.empty()) continue; std::vector parts; std::string part; while (iss >> part) { parts.push_back(part); } if (keyword == "#") { comments.push_back(line); } else if (keyword == "v") { vertices.push_back(parts); } else if (keyword == "vt") { texture_coords.push_back(parts); } else if (keyword == "vn") { normals.push_back(parts); } else if (keyword == "vp") { param_vertices.push_back(parts); } else if (keyword == "f") { faces.push_back(parts); } else if (keyword == "l") { lines.push_back(parts); } else if (keyword == "o") { objects.push_back(parts); } else if (keyword == "g") { groups.push_back(parts); } else if (keyword == "s") { smoothing_groups.push_back(parts); } else if (keyword == "usemtl") { materials.push_back(parts); } else if (keyword == "mtllib") { mtllib.push_back(parts); } } file.close(); } void write(const std::string& output_path) { std::ofstream file(output_path); for (const auto& comment : comments) { file << comment << "\n"; } for (const auto& lib : mtllib) { file << "mtllib"; for (const auto& p : lib) file << " " << p; file << "\n"; } for (const auto& obj : objects) { file << "o"; for (const auto& p : obj) file << " " << p; file << "\n"; } for (const auto& group : groups) { file << "g"; for (const auto& p : group) file << " " << p; file << "\n"; } for (const auto& smooth : smoothing_groups) { file << "s"; for (const auto& p : smooth) file << " " << p; file << "\n"; } for (const auto& mat : materials) { file << "usemtl"; for (const auto& p : mat) file << " " << p; file << "\n"; } for (const auto& vert : vertices) { file << "v"; for (const auto& p : vert) file << " " << p; file << "\n"; } for (const auto& tc : texture_coords) { file << "vt"; for (const auto& p : tc) file << " " << p; file << "\n"; } for (const auto& norm : normals) { file << "vn"; for (const auto& p : norm) file << " " << p; file << "\n"; } for (const auto& pv : param_vertices) { file << "vp"; for (const auto& p : pv) file << " " << p; file << "\n"; } for (const auto& face : faces) { file << "f"; for (const auto& p : face) file << " " << p; file << "\n"; } for (const auto& ln : lines) { file << "l"; for (const auto& p : ln) file << " " << p; file << "\n"; } file.close(); } void print_properties() { std::cout << "Vertices: " << vertices.size() << std::endl; std::cout << "Texture Coordinates: " << texture_coords.size() << std::endl; std::cout << "Normals: " << normals.size() << std::endl; std::cout << "Parameter Vertices: " << param_vertices.size() << std::endl; std::cout << "Faces: " << faces.size() << std::endl; std::cout << "Lines: " << lines.size() << std::endl; std::cout << "Objects: " << objects.size() << std::endl; std::cout << "Groups: " << groups.size() << std::endl; std::cout << "Smoothing Groups: " << smoothing_groups.size() << std::endl; std::cout << "Materials: "; for (const auto& mat : materials) { for (const auto& p : mat) std::cout << p << " "; } std::cout << std::endl; std::cout << "Material Libraries: "; for (const auto& lib : mtllib) { for (const auto& p : lib) std::cout << p << " "; } std::cout << std::endl; std::cout << "Comments: " << comments.size() << std::endl; } }; // Example usage: // int main() { // OBJHandler handler("example.obj"); // handler.print_properties(); // handler.write("output.obj"); // return 0; // } // ===== end task-468 .OBJ ===== // ===== task-469 .OBS [C++] ===== #include #include #include #include #include #include class ObsFileHandler { private: std::string filepath; std::map header; std::vector> data; // Simplified; use structs for complex data public: ObsFileHandler(const std::string& fp) : filepath(fp) { if (!fp.empty()) { read(); } } void read() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file." << std::endl; return; } std::string line; bool inHeader = true; std::string currentSystem; while (std::getline(file, line)) { if (line.find("END OF HEADER") != std::string::npos) { inHeader = false; continue; } if (inHeader) { std::string label = line.substr(60, line.size() - 60); label.erase(0, label.find_first_not_of(" \t")); label.erase(label.find_last_not_of(" \t") + 1); std::string value = line.substr(0, 60); value.erase(0, value.find_first_not_of(" \t")); value.erase(value.find_last_not_of(" \t") + 1); if (label == "SYS / # / OBS TYPES") { currentSystem = value[0]; label = label + " (" + currentSystem + ")"; } if (!label.empty()) { header[label] = header[label] + value + " "; } } else { if (line[0] == '>') { std::map epoch; epoch["timestamp"] = line.substr(2, 29); epoch["timestamp"].erase(epoch["timestamp"].find_last_not_of(" \t") + 1); epoch["flag"] = line.substr(32, 1); epoch["num_sats"] = line.substr(35, 3); epoch["num_sats"].erase(epoch["num_sats"].find_last_not_of(" \t") + 1); data.push_back(epoch); } else if (!line.empty()) { auto& lastEpoch = data.back(); lastEpoch["observations"] = lastEpoch["observations"] + line + "\n"; } } } file.close(); } void printProperties() const { std::cout << "Header Properties:" << std::endl; for (const auto& pair : header) { std::string value = pair.second; value.erase(value.find_last_not_of(" \t") + 1); std::cout << pair.first << ": " << value << std::endl; } std::cout << "\nData Properties (Epoch Summaries):" << std::endl; for (size_t i = 0; i < data.size(); ++i) { const auto& epoch = data[i]; std::cout << "Epoch " << (i + 1) << ": Timestamp = " << epoch.at("timestamp") << ", Flag = " << epoch.at("flag") << ", Satellites = " << epoch.at("num_sats") << std::endl; if (epoch.count("observations")) { std::cout << " Observations: " << epoch.at("observations") << std::endl; } } } void write(const std::string& newFilepath) const { std::ofstream file(newFilepath.empty() ? filepath : newFilepath); if (!file.is_open()) { std::cerr << "Error writing file." << std::endl; return; } for (const auto& pair : header) { std::string value = pair.second; value.erase(value.find_last_not_of(" \t") + 1); file << std::left << std::setw(60) << value << pair.first << std::endl; } file << std::left << std::setw(60) << "" << "END OF HEADER" << std::endl; for (const auto& epoch : data) { file << "> " << std::left << std::setw(28) << epoch.at("timestamp") << " " << epoch.at("flag") << " " << std::left << std::setw(3) << epoch.at("num_sats") << " 0.000000000" << std::endl; if (epoch.count("observations")) { file << epoch.at("observations"); } } file.close(); } }; // Example usage: // int main() { // ObsFileHandler handler("example.obs"); // handler.printProperties(); // handler.write("modified.obs"); // return 0; // } // ===== end task-469 .OBS ===== // ===== task-470 .OCX [C++] ===== #include #include #include #include #include #include #include class OCXFile { private: std::string filepath; std::vector data; std::map properties; public: OCXFile(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { std::cerr << "Failed to open file." << std::endl; return; } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(data.data(), size); parseHeader(); parseRootDirectory(); } void parseHeader() { std::stringstream ss; ss << "0x"; for (int i = 0; i < 8; ++i) { ss << std::hex << std::setw(2) << std::setfill('0') << (static_cast(data[i])); } properties["Header Signature"] = ss.str(); ss.str(""); for (int i = 8; i < 24; ++i) { ss << std::hex << std::setw(2) << std::setfill('0') << (static_cast(data[i])); } properties["CLSID"] = ss.str(); unsigned short minorVer = *reinterpret_cast(&data[24]); properties["Minor Version"] = std::to_string(minorVer); unsigned short majorVer = *reinterpret_cast(&data[26]); properties["Major Version"] = std::to_string(majorVer); unsigned short byteOrder = *reinterpret_cast(&data[28]); properties["Byte Order"] = std::to_string(byteOrder); unsigned short sectorShift = *reinterpret_cast(&data[30]); properties["Sector Shift"] = std::to_string(sectorShift); unsigned short miniShift = *reinterpret_cast(&data[32]); properties["Mini Sector Shift"] = std::to_string(miniShift); unsigned short reserved = *reinterpret_cast(&data[34]); properties["Reserved"] = std::to_string(reserved); unsigned int reserved1 = *reinterpret_cast(&data[36]); properties["Reserved1"] = std::to_string(reserved1); unsigned int dirSects = *reinterpret_cast(&data[40]); properties["Number of Directory Sectors"] = std::to_string(dirSects); unsigned int fatSects = *reinterpret_cast(&data[44]); properties["Number of FAT Sectors"] = std::to_string(fatSects); unsigned int firstDir = *reinterpret_cast(&data[48]); properties["First Directory Sector Location"] = std::to_string(firstDir); unsigned int transSig = *reinterpret_cast(&data[52]); properties["Transaction Signature Number"] = std::to_string(transSig); unsigned int miniCutoff = *reinterpret_cast(&data[56]); properties["Mini Stream Cutoff Size"] = std::to_string(miniCutoff); unsigned int firstMiniFat = *reinterpret_cast(&data[60]); properties["First MiniFAT Sector Location"] = std::to_string(firstMiniFat); unsigned int numMiniFat = *reinterpret_cast(&data[64]); properties["Number of MiniFAT Sectors"] = std::to_string(numMiniFat); unsigned int firstDifat = *reinterpret_cast(&data[68]); properties["First DIFAT Sector Location"] = std::to_string(firstDifat); unsigned int numDifat = *reinterpret_cast(&data[72]); properties["Number of DIFAT Sectors"] = std::to_string(numDifat); ss.str("["); for (int i = 0; i < 109; ++i) { unsigned int val = *reinterpret_cast(&data[76 + i * 4]); ss << val << ", "; } std::string difatStr = ss.str(); difatStr = difatStr.substr(0, difatStr.size() - 2) + "]"; properties["DIFAT Array"] = difatStr; } void parseRootDirectory() { unsigned short sectorShift = std::stoi(properties["Sector Shift"]); unsigned int sectorSize = 1 << sectorShift; unsigned int dirStart = std::stoi(properties["First Directory Sector Location"]); size_t dirOffset = (dirStart + 1) * sectorSize; std::string name; for (size_t i = 0; i < 64; i += 2) { unsigned short charVal = *reinterpret_cast(&data[dirOffset + i]); if (charVal == 0) break; name += static_cast(charVal); } properties["Root Name"] = name; unsigned char type = data[dirOffset + 66]; properties["Root Type"] = std::to_string(type); unsigned char color = data[dirOffset + 67]; properties["Root Node Color"] = std::to_string(color); int leftSib = *reinterpret_cast(&data[dirOffset + 68]); properties["Root Left Sibling SID"] = std::to_string(leftSib); int rightSib = *reinterpret_cast(&data[dirOffset + 72]); properties["Root Right Sibling SID"] = std::to_string(rightSib); int child = *reinterpret_cast(&data[dirOffset + 76]); properties["Root Child SID"] = std::to_string(child); std::stringstream ss; for (size_t i = 80; i < 96; ++i) { ss << std::hex << std::setw(2) << std::setfill('0') << (static_cast(data[dirOffset + i])); } properties["Root CLSID"] = ss.str(); unsigned int stateBits = *reinterpret_cast(&data[dirOffset + 96]); properties["Root State Bits"] = std::to_string(stateBits); long long creation = *reinterpret_cast(&data[dirOffset + 100]); properties["Root Creation Time"] = filetimeToString(creation); long long mod = *reinterpret_cast(&data[dirOffset + 108]); properties["Root Modification Time"] = filetimeToString(mod); unsigned int startSect = *reinterpret_cast(&data[dirOffset + 116]); properties["Root Starting Sector"] = std::to_string(startSect); long long size = *reinterpret_cast(&data[dirOffset + 120]); properties["Root Stream Size"] = std::to_string(size); } std::string filetimeToString(long long filetime) { filetime /= 10000000; // To seconds filetime -= 11644473600LL; // Epoch adjustment std::time_t tt = static_cast(filetime); std::tm* tm = std::gmtime(&tt); std::stringstream ss; ss << std::put_time(tm, "%Y-%m-%dT%H:%M:%SZ"); return ss.str(); } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& newFilepath = "") { std::string outPath = newFilepath.empty() ? filepath : newFilepath; std::ofstream out(outPath, std::ios::binary); if (!out) { std::cerr << "Failed to write file." << std::endl; return; } out.write(data.data(), data.size()); } }; // Example usage: // int main() { // OCXFile ocx("example.ocx"); // ocx.read(); // ocx.printProperties(); // ocx.write("modified.ocx"); // return 0; // } // ===== end task-470 .OCX ===== // ===== task-471 .ODB [C] ===== #include #include #include #include #include #include #include typedef struct { char *filename; char *properties[15][2]; // Key-value pairs } ODBHandler; ODBHandler* odb_create(const char *filename) { ODBHandler *handler = malloc(sizeof(ODBHandler)); handler->filename = strdup(filename); return handler; } void odb_read(ODBHandler *handler) { // Stub implementation; in practice, use libzip to open ZIP and libxml2 to parse XML files // Populate handler->properties with values as in Python/Java examples // For brevity, printing placeholder printf("Reading .ODB file: %s\n", handler->filename); // Actual code would extract and parse as above } void odb_print_properties(ODBHandler *handler) { // Print the properties printf("MIME Type: application/vnd.oasis.opendocument.base\n"); // Placeholder // Add for all 15 } void odb_write(ODBHandler *handler, const char *output_filename) { // Use libzip to create ZIP and add files as in examples printf("Writing minimal .ODB to %s\n", output_filename); // Actual code would create ZIP and add strings as above } void odb_destroy(ODBHandler *handler) { free(handler->filename); free(handler); } // Example usage // int main() { // ODBHandler *handler = odb_create("example.odb"); // odb_read(handler); // odb_print_properties(handler); // odb_write(handler, "new.odb"); // odb_destroy(handler); // return 0; // } // ===== end task-471 .ODB ===== // ===== task-472 .ODF [C++] ===== #include #include #include #include #include class ODFMetadataHandler { private: std::string filename; zip_t* zip; tinyxml2::XMLDocument doc; std::map properties; void parseMeta() { zip_file_t* file = zip_fopen(zip, "meta.xml", 0); if (!file) throw std::runtime_error("No meta.xml found"); std::string xmlContent; char buffer[1024]; zip_int64_t len; while ((len = zip_fread(file, buffer, sizeof(buffer))) > 0) { xmlContent.append(buffer, len); } zip_fclose(file); doc.Parse(xmlContent.c_str()); } void extractProperties() { tinyxml2::XMLElement* meta = doc.FirstChildElement("office:document-meta")->FirstChildElement("office:meta"); if (!meta) throw std::runtime_error("No meta element found"); const char* metaNS = "urn:oasis:names:tc:opendocument:xmlns:meta:1.0"; const char* dcNS = "http://purl.org/dc/elements/1.1/"; const char* metaKeys[] = {"meta:generator", "meta:keyword", "meta:initial-creator", "meta:printed-by", "meta:creation-date", "meta:print-date", "meta:template", "meta:auto-reload", "meta:hyperlink-behaviour", "meta:editing-cycles", "meta:editing-duration", "meta:document-statistic"}; for (const char* key : metaKeys) { tinyxml2::XMLElement* el = meta->FirstChildElement(key); while (el) { properties[key] = el->GetText() ? el->GetText() : ""; el = el->NextSiblingElement(key); } } const char* dcKeys[] = {"dc:title", "dc:description", "dc:subject", "dc:creator", "dc:date", "dc:language"}; for (const char* key : dcKeys) { tinyxml2::XMLElement* el = meta->FirstChildElement(key); while (el) { properties[key] = el->GetText() ? el->GetText() : ""; el = el->NextSiblingElement(key); } } tinyxml2::XMLElement* ud = meta->FirstChildElement("meta:user-defined"); while (ud) { std::string name = ud->Attribute("meta:name"); properties["user-defined:" + name] = ud->GetText() ? ud->GetText() : ""; ud = ud->NextSiblingElement("meta:user-defined"); } } public: ODFMetadataHandler(const std::string& fn) : filename(fn) { int err = 0; zip = zip_open(filename.c_str(), ZIP_RDONLY, &err); if (!zip) throw std::runtime_error("Failed to open ZIP"); parseMeta(); extractProperties(); } ~ODFMetadataHandler() { zip_close(zip); } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void writeProperty(const std::string& key, const std::string& value) { tinyxml2::XMLElement* meta = doc.FirstChildElement("office:document-meta")->FirstChildElement("office:meta"); tinyxml2::XMLElement* el = meta->FirstChildElement(key.c_str()); if (!el) { el = doc.NewElement(key.c_str()); meta->InsertEndChild(el); } el->SetText(value.c_str()); } void save(const std::string& newFilename = "") { std::string outFn = newFilename.empty() ? filename : newFilename; zip_t* newZip = zip_open(outFn.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); if (!newZip) throw std::runtime_error("Failed to create new ZIP"); zip_source_t* src; int numEntries = zip_get_num_entries(zip, 0); for (int i = 0; i < numEntries; ++i) { const char* name = zip_get_name(zip, i, 0); if (std::string(name) == "meta.xml") { tinyxml2::XMLPrinter printer; doc.Print(&printer); src = zip_source_buffer(newZip, printer.CStr(), printer.CStrSize() - 1, 0); } else { src = zip_source_zip(newZip, zip, i, 0, 0, -1); } if (src && zip_file_add(newZip, name, src, ZIP_FL_ENC_UTF_8) < 0) { zip_source_free(src); throw std::runtime_error("Failed to add file to new ZIP"); } } zip_close(newZip); } }; // ===== end task-472 .ODF ===== // ===== task-473 .ODG [C] ===== #include #include #include #include #include #include typedef struct { char *file_path; // Use a simple array or map simulation for properties; for brevity, use printf directly } ODGHandler; void read_properties(ODGHandler *handler) { struct zip *za; struct zip_file *zf; struct zip_stat sb; int err; char *buf; if ((err = zip_open(handler->file_path, 0, &err)) != 0) { printf("Error opening ZIP: %d\n", err); return; } if (zip_stat(za, "meta.xml", 0, &sb) == 0) { buf = (char *)malloc(sb.size + 1); zf = zip_fopen(za, "meta.xml", 0); zip_fread(zf, buf, sb.size); buf[sb.size] = '\0'; zip_fclose(zf); xmlDocPtr doc = xmlReadMemory(buf, sb.size, "noname.xml", NULL, 0); if (doc != NULL) { xmlNodePtr root = xmlDocGetRootElement(doc); xmlNodePtr meta = NULL; for (xmlNodePtr node = root->children; node; node = node->next) { if (node->type == XML_ELEMENT_NODE && xmlStrcmp(node->name, (const xmlChar *)"meta") == 0) { meta = node; break; } } if (meta) { // Print properties (simplified; extend for full map) printf("dc:title: %s\n", get_node_content(meta, "title", "http://purl.org/dc/elements/1.1/")); printf("dc:creator: %s\n", get_node_content(meta, "creator", "http://purl.org/dc/elements/1.1/")); // ... Add similar for all properties // For keywords, user-defined, stats: iterate children and print } xmlFreeDoc(doc); } free(buf); } zip_close(za); } char *get_node_content(xmlNodePtr parent, const char *tag, const char *ns) { xmlNodePtr cur = parent->children; while (cur) { if (cur->type == XML_ELEMENT_NODE && xmlStrcmp(cur->name, (const xmlChar *)tag) == 0 && (ns == NULL || xmlStrcmp(cur->ns->href, (const xmlChar *)ns) == 0)) { return (char *)xmlNodeGetContent(cur); } cur = cur->next; } return strdup("N/A"); } void print_properties(ODGHandler *handler) { // Since read prints directly for simplicity; extend to store if needed } void write_properties(ODGHandler *handler, const char *output_path, /* updates struct or map */) { // Similar to read, but modify doc, then replace in new ZIP // Copy all files, update meta.xml } ODGHandler *create_handler(const char *file_path) { ODGHandler *h = malloc(sizeof(ODGHandler)); h->file_path = strdup(file_path); return h; } void destroy_handler(ODGHandler *h) { free(h->file_path); free(h); } // Example usage: // int main(int argc, char **argv) { // ODGHandler *handler = create_handler("example.odg"); // read_properties(handler); // // write_properties(handler, "updated.odg", updates); // destroy_handler(handler); // return 0; // } // ===== end task-473 .ODG ===== // ===== task-474 .ODP [C++] ===== #include #include #include #include #include #include "unzip.h" // From minizip #include "zip.h" // From minizip #include "tinyxml2.h" class ODPFile { private: std::string path; tinyxml2::XMLDocument doc; std::map simpleProps; std::vector keywords; std::map userDefined; std::map statistics; void readProperties() { unzFile uf = unzOpen(path.c_str()); if (uf == nullptr) return; unzLocateFile(uf, "meta.xml", 0); unz_file_info fileInfo; unzGetCurrentFileInfo(uf, &fileInfo, nullptr, 0, nullptr, 0, nullptr, 0); std::vector buffer(fileInfo.uncompressed_size); unzOpenCurrentFile(uf); unzReadCurrentFile(uf, buffer.data(), fileInfo.uncompressed_size); unzCloseCurrentFile(uf); unzClose(uf); doc.Parse(buffer.data(), fileInfo.uncompressed_size); tinyxml2::XMLElement* meta = doc.FirstChildElement("office:document-meta")->FirstChildElement("office:meta"); simpleProps["title"] = meta->FirstChildElement("dc:title") ? meta->FirstChildElement("dc:title")->GetText() : ""; simpleProps["subject"] = meta->FirstChildElement("dc:subject") ? meta->FirstChildElement("dc:subject")->GetText() : ""; simpleProps["description"] = meta->FirstChildElement("dc:description") ? meta->FirstChildElement("dc:description")->GetText() : ""; simpleProps["creator"] = meta->FirstChildElement("dc:creator") ? meta->FirstChildElement("dc:creator")->GetText() : ""; simpleProps["date"] = meta->FirstChildElement("dc:date") ? meta->FirstChildElement("dc:date")->GetText() : ""; simpleProps["language"] = meta->FirstChildElement("dc:language") ? meta->FirstChildElement("dc:language")->GetText() : ""; simpleProps["generator"] = meta->FirstChildElement("meta:generator") ? meta->FirstChildElement("meta:generator")->GetText() : ""; simpleProps["initial_creator"] = meta->FirstChildElement("meta:initial-creator") ? meta->FirstChildElement("meta:initial-creator")->GetText() : ""; simpleProps["creation_date"] = meta->FirstChildElement("meta:creation-date") ? meta->FirstChildElement("meta:creation-date")->GetText() : ""; simpleProps["editing_cycles"] = meta->FirstChildElement("meta:editing-cycles") ? meta->FirstChildElement("meta:editing-cycles")->GetText() : ""; simpleProps["editing_duration"] = meta->FirstChildElement("meta:editing-duration") ? meta->FirstChildElement("meta:editing-duration")->GetText() : ""; tinyxml2::XMLElement* kw = meta->FirstChildElement("meta:keyword"); while (kw) { keywords.push_back(kw->GetText() ? kw->GetText() : ""); kw = kw->NextSiblingElement("meta:keyword"); } tinyxml2::XMLElement* ud = meta->FirstChildElement("meta:user-defined"); while (ud) { userDefined[ud->Attribute("meta:name")] = ud->GetText() ? ud->GetText() : ""; ud = ud->NextSiblingElement("meta:user-defined"); } tinyxml2::XMLElement* stat = meta->FirstChildElement("meta:document-statistic"); if (stat) { for (const tinyxml2::XMLAttribute* attr = stat->FirstAttribute(); attr; attr = attr->Next()) { statistics[attr->Name()] = attr->Value(); } } } public: ODPFile(const std::string& p) : path(p) { readProperties(); } void printProperties() { std::cout << "Properties:" << std::endl; for (const auto& pair : simpleProps) { std::cout << pair.first << ": " << pair.second << std::endl; } std::cout << "keywords: "; for (size_t i = 0; i < keywords.size(); ++i) { std::cout << keywords[i]; if (i < keywords.size() - 1) std::cout << ", "; } std::cout << std::endl; std::cout << "user_defined:" << std::endl; for (const auto& pair : userDefined) { std::cout << " " << pair.first << ": " << pair.second << std::endl; } std::cout << "statistics:" << std::endl; for (const auto& pair : statistics) { std::cout << " " << pair.first << ": " << pair.second << std::endl; } } void setProperty(const std::string& key, const std::string& value) { tinyxml2::XMLElement* meta = doc.FirstChildElement("office:document-meta")->FirstChildElement("office:meta"); tinyxml2::XMLElement* elem = meta->FirstChildElement(key.c_str()); if (elem) { elem->SetText(value.c_str()); } // For lists/dicts, extend as needed } void save(const std::string& newPath) { std::string xmlStr; tinyxml2::XMLPrinter printer; doc.Print(&printer); xmlStr = printer.CStr(); zipFile zf = zipOpen(newPath.c_str(), APPEND_STATUS_CREATE); unzFile uf = unzOpen(path.c_str()); unz_global_info gi; unzGetGlobalInfo(uf, &gi); for (int i = 0; i < gi.number_entry; ++i) { unz_file_info fileInfo; char filename[256]; unzGetCurrentFileInfo(uf, &fileInfo, filename, sizeof(filename), nullptr, 0, nullptr, 0); if (std::string(filename) == "meta.xml") { zipOpenNewFileInZip(zf, "meta.xml", nullptr, nullptr, 0, nullptr, 0, nullptr, Z_DEFLATED, Z_DEFAULT_COMPRESSION); zipWriteInFileInZip(zf, xmlStr.c_str(), xmlStr.size()); zipCloseFileInZip(zf); } else { std::vector buffer(fileInfo.uncompressed_size); unzOpenCurrentFile(uf); unzReadCurrentFile(uf, buffer.data(), fileInfo.uncompressed_size); unzCloseCurrentFile(uf); zipOpenNewFileInZip(zf, filename, nullptr, nullptr, 0, nullptr, 0, nullptr, Z_DEFLATED, Z_DEFAULT_COMPRESSION); zipWriteInFileInZip(zf, buffer.data(), fileInfo.uncompressed_size); zipCloseFileInZip(zf); } unzGoToNextFile(uf); } unzClose(uf); zipClose(zf, nullptr); } }; // Example usage: // int main() { // ODPFile odp("sample.odp"); // odp.printProperties(); // odp.setProperty("dc:title", "New Title"); // odp.save("modified.odp"); // return 0; // } // ===== end task-474 .ODP ===== // ===== task-475 .ODS [C] ===== #include #include #include #include #include #include #define NAMESPACE_OFFICE "urn:oasis:names:tc:opendocument:xmlns:office:1.0" #define NAMESPACE_META "urn:oasis:names:tc:opendocument:xmlns:meta:1.0" #define NAMESPACE_DC "http://purl.org/dc/elements/1.1/" typedef struct { char *file_path; xmlDocPtr meta_doc; xmlNodePtr meta_root; } ODSMetadataHandler; ODSMetadataHandler* ods_create(const char *file_path) { ODSMetadataHandler *handler = malloc(sizeof(ODSMetadataHandler)); handler->file_path = strdup(file_path); handler->meta_doc = NULL; handler->meta_root = NULL; ods_load_meta(handler); return handler; } void ods_load_meta(ODSMetadataHandler *handler) { zip_t *zf = zip_open(handler->file_path, ZIP_RDONLY, NULL); if (!zf) { fprintf(stderr, "Error opening ZIP file\n"); return; } zip_file_t *meta_file = zip_fopen(zf, "meta.xml", 0); if (!meta_file) { fprintf(stderr, "meta.xml not found\n"); zip_close(zf); return; } zip_stat_t stat; zip_stat(zf, "meta.xml", 0, &stat); char *buffer = malloc(stat.size + 1); zip_fread(meta_file, buffer, stat.size); buffer[stat.size] = '\0'; handler->meta_doc = xmlReadMemory(buffer, stat.size, NULL, NULL, 0); if (!handler->meta_doc) { fprintf(stderr, "Error parsing XML\n"); } handler->meta_root = xmlDocGetRootElement(handler->meta_doc)->children; // office:meta while (handler->meta_root && strcmp((char*)handler->meta_root->name, "meta") != 0) { handler->meta_root = handler->meta_root->next; } free(buffer); zip_fclose(meta_file); zip_close(zf); } void ods_read_and_print_properties(ODSMetadataHandler *handler) { if (!handler->meta_root) return; const char *tags[] = { "generator", "title", "description", "subject", "keyword", "initial-creator", "creator", "printed-by", "creation-date", "date", "print-date", "template", "auto-reload", "hyperlink-behaviour", "language", "editing-cycles", "editing-duration", NULL }; const char *ns[] = {NAMESPACE_META, NAMESPACE_DC, NAMESPACE_DC, NAMESPACE_DC, NAMESPACE_META, NAMESPACE_META, NAMESPACE_DC, NAMESPACE_META, NAMESPACE_META, NAMESPACE_DC, NAMESPACE_META, NAMESPACE_META, NAMESPACE_META, NAMESPACE_META, NAMESPACE_DC, NAMESPACE_META, NAMESPACE_META}; for (int i = 0; tags[i]; i++) { xmlNodePtr node = handler->meta_root->children; while (node) { if (node->type == XML_ELEMENT_NODE && xmlStrcmp(node->name, (xmlChar*)tags[i]) == 0 && xmlStrcmp(node->ns->href, (xmlChar*)ns[i]) == 0) { xmlChar *content = xmlNodeGetContent(node); printf("%s: %s\n", tags[i], content); xmlFree(content); break; } node = node->next; } } // Statistics xmlNodePtr stats = handler->meta_root->children; while (stats) { if (stats->type == XML_ELEMENT_NODE && xmlStrcmp(stats->name, (xmlChar*)"document-statistic") == 0) { const char *attrs[] = {"table-count", "cell-count", "row-count", "column-count", "object-count", NULL}; for (int j = 0; attrs[j]; j++) { xmlChar *val = xmlGetNsProp(stats, (xmlChar*)attrs[j], (xmlChar*)NAMESPACE_META); if (val) { printf("meta:%s: %s\n", attrs[j], val); xmlFree(val); } } break; } stats = stats->next; } // User-defined xmlNodePtr ud = handler->meta_root->children; int index = 0; while (ud) { if (ud->type == XML_ELEMENT_NODE && xmlStrcmp(ud->name, (xmlChar*)"user-defined") == 0) { xmlChar *name = xmlGetNsProp(ud, (xmlChar*)"name", (xmlChar*)NAMESPACE_META); xmlChar *content = xmlNodeGetContent(ud); printf("meta:user-defined[%d] (name: %s): %s\n", index++, name ? (char*)name : "", content); if (name) xmlFree(name); xmlFree(content); } ud = ud->next; } } void ods_write_property(ODSMetadataHandler *handler, const char *key, const char *value) { // Simplified: assumes key is tag name without ns, creates if not exists xmlNodePtr node = handler->meta_root->children; int found = 0; while (node) { if (node->type == XML_ELEMENT_NODE && xmlStrcmp(node->name, (xmlChar*)key) == 0) { xmlNodeSetContent(node, (xmlChar*)value); found = 1; break; } node = node->next; } if (!found) { xmlNewChild(handler->meta_root, NULL, (xmlChar*)key, (xmlChar*)value); } } void ods_save(ODSMetadataHandler *handler, const char *output_path) { const char *out = output_path ? output_path : handler->file_path; zip_t *zf_in = zip_open(handler->file_path, ZIP_RDONLY, NULL); zip_t *zf_out = zip_open(out, ZIP_CREATE | ZIP_TRUNCATE, NULL); int num_entries = zip_get_num_entries(zf_in, 0); for (int i = 0; i < num_entries; i++) { const char *name = zip_get_name(zf_in, i, 0); zip_file_t *file_in = zip_fopen_index(zf_in, i, 0); zip_stat_t stat; zip_stat_index(zf_in, i, 0, &stat); char *buffer = malloc(stat.size); zip_fread(file_in, buffer, stat.size); zip_source_t *src; if (strcmp(name, "meta.xml") == 0) { xmlChar *xml_buff; int xml_size; xmlDocDumpFormatMemory(handler->meta_doc, &xml_buff, &xml_size, 1); src = zip_source_buffer(zf_out, xml_buff, xml_size, 0); } else { src = zip_source_buffer(zf_out, buffer, stat.size, 1); } zip_file_add(zf_out, name, src, ZIP_FL_OVERWRITE); zip_fclose(file_in); } zip_close(zf_out); zip_close(zf_in); } void ods_destroy(ODSMetadataHandler *handler) { xmlFreeDoc(handler->meta_doc); free(handler->file_path); free(handler); } // Example usage: // int main() { // ODSMetadataHandler *handler = ods_create("path/to/file.ods"); // ods_read_and_print_properties(handler); // ods_write_property(handler, "title", "Updated Title"); // ods_save(handler, NULL); // ods_destroy(handler); // return 0; // } // ===== end task-475 .ODS ===== // ===== task-476 .ODT [C++] ===== #include #include #include #include #include #include class ODTHandler { private: std::string filePath; std::map simpleProps; std::vector keywords; std::map userDefined; std::map statistics; std::string metaXml; void readMeta() { zip_t* za = zip_open(filePath.c_str(), ZIP_RDONLY, nullptr); if (za) { zip_file_t* zf = zip_fopen(za, "meta.xml", 0); if (zf) { zip_stat_t zs; zip_stat(za, "meta.xml", 0, &zs); char* buffer = new char[zs.size + 1]; zip_fread(zf, buffer, zs.size); buffer[zs.size] = '\0'; metaXml = buffer; tinyxml2::XMLDocument doc; doc.Parse(buffer); tinyxml2::XMLElement* meta = doc.FirstChildElement("office:document-meta")->FirstChildElement("office:meta"); if (meta) { const char* ns_dc = "dc"; const char* ns_meta = "meta"; simpleProps["title"] = meta->FirstChildElement("title", ns_dc) ? meta->FirstChildElement("title", ns_dc)->GetText() : "N/A"; simpleProps["subject"] = meta->FirstChildElement("subject", ns_dc) ? meta->FirstChildElement("subject", ns_dc)->GetText() : "N/A"; simpleProps["description"] = meta->FirstChildElement("description", ns_dc) ? meta->FirstChildElement("description", ns_dc)->GetText() : "N/A"; simpleProps["creator"] = meta->FirstChildElement("creator", ns_dc) ? meta->FirstChildElement("creator", ns_dc)->GetText() : "N/A"; simpleProps["date"] = meta->FirstChildElement("date", ns_dc) ? meta->FirstChildElement("date", ns_dc)->GetText() : "N/A"; simpleProps["language"] = meta->FirstChildElement("language", ns_dc) ? meta->FirstChildElement("language", ns_dc)->GetText() : "N/A"; simpleProps["generator"] = meta->FirstChildElement("generator", ns_meta) ? meta->FirstChildElement("generator", ns_meta)->GetText() : "N/A"; simpleProps["initial-creator"] = meta->FirstChildElement("initial-creator", ns_meta) ? meta->FirstChildElement("initial-creator", ns_meta)->GetText() : "N/A"; simpleProps["creation-date"] = meta->FirstChildElement("creation-date", ns_meta) ? meta->FirstChildElement("creation-date", ns_meta)->GetText() : "N/A"; simpleProps["editing-cycles"] = meta->FirstChildElement("editing-cycles", ns_meta) ? meta->FirstChildElement("editing-cycles", ns_meta)->GetText() : "N/A"; simpleProps["editing-duration"] = meta->FirstChildElement("editing-duration", ns_meta) ? meta->FirstChildElement("editing-duration", ns_meta)->GetText() : "N/A"; for (tinyxml2::XMLElement* kw = meta->FirstChildElement("keyword", ns_meta); kw; kw = kw->NextSiblingElement("keyword", ns_meta)) { keywords.push_back(kw->GetText() ? kw->GetText() : "N/A"); } for (tinyxml2::XMLElement* ud = meta->FirstChildElement("user-defined", ns_meta); ud; ud = ud->NextSiblingElement("user-defined", ns_meta)) { const char* name = ud->Attribute("name", ns_meta); userDefined[name ? name : "N/A"] = ud->GetText() ? ud->GetText() : "N/A"; } tinyxml2::XMLElement* stats = meta->FirstChildElement("document-statistic", ns_meta); if (stats) { for (const tinyxml2::XMLAttribute* attr = stats->FirstAttribute(); attr; attr = attr->Next()) { statistics[attr->Name()] = attr->Value(); } } } delete[] buffer; zip_fclose(zf); } zip_close(za); } } public: ODTHandler(const std::string& path) : filePath(path) { readMeta(); } void printProperties() { for (const auto& p : simpleProps) { std::cout << p.first << ": " << p.second << std::endl; } std::cout << "keywords: "; for (const auto& kw : keywords) { std::cout << kw << " "; } std::cout << std::endl; std::cout << "user_defined: "; for (const auto& ud : userDefined) { std::cout << ud.first << ": " << ud.second << "; "; } std::cout << std::endl; std::cout << "statistics: "; for (const auto& stat : statistics) { std::cout << stat.first << ": " << stat.second << "; "; } std::cout << std::endl; } void writeModified(const std::string& outputPath, const std::map& modifications) { zip_t* za_in = zip_open(filePath.c_str(), ZIP_RDONLY, nullptr); zip_t* za_out = zip_open(outputPath.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); if (za_in && za_out) { int num_entries = zip_get_num_entries(za_in, 0); for (int i = 0; i < num_entries; ++i) { const char* name = zip_get_name(za_in, i, 0); zip_file_t* zf_in = zip_fopen_index(za_in, i, 0); if (zf_in) { zip_stat_t zs; zip_stat_index(za_in, i, 0, &zs); char* buffer = new char[zs.size]; zip_fread(zf_in, buffer, zs.size); if (std::string(name) == "meta.xml") { tinyxml2::XMLDocument doc; doc.Parse(metaXml.c_str()); tinyxml2::XMLElement* meta = doc.FirstChildElement("office:document-meta")->FirstChildElement("office:meta"); for (const auto& mod : modifications) { const char* ns = mod.first.find("dc") == 0 ? "dc" : "meta"; tinyxml2::XMLElement* elem = meta->FirstChildElement(mod.first.c_str(), ns); if (elem) { elem->SetText(mod.second.c_str()); } } tinyxml2::XMLPrinter printer; doc.Print(&printer); delete[] buffer; buffer = const_cast(printer.CStr()); zs.size = printer.Size(); } zip_file_add(za_out, name, zip_buffer_create(buffer, zs.size), ZIP_FL_ENC_UTF_8); zip_fclose(zf_in); } } zip_close(za_in); zip_close(za_out); } } }; // ===== end task-476 .ODT ===== // ===== task-477 .OFF [C] ===== #include #include #include #include #define MAX_LINE 1024 typedef struct { char *header; int dimensionality; int N, F, E; double **vertices; // N x dimensionality struct Face *faces; // F faces int has_colors; } OFFFile; typedef struct Face { int num_verts; int *indices; double *color; // NULL if none, else 3 or 4 elems int color_count; } Face; OFFFile* off_create(const char *filename) { OFFFile *off = malloc(sizeof(OFFFile)); off->header = strdup("OFF"); off->dimensionality = 3; off->N = off->F = off->E = 0; off->vertices = NULL; off->faces = NULL; off->has_colors = 0; if (filename) { off_read(off, filename); } return off; } void off_destroy(OFFFile *off) { free(off->header); if (off->vertices) { for (int i = 0; i < off->N; i++) free(off->vertices[i]); free(off->vertices); } if (off->faces) { for (int i = 0; i < off->F; i++) { free(off->faces[i].indices); if (off->faces[i].color) free(off->faces[i].color); } free(off->faces); } free(off); } void off_read(OFFFile *off, const char *filename) { FILE *fp = fopen(filename, "r"); if (!fp) { perror("Failed to open file"); return; } char line[MAX_LINE]; int line_count = 0; char **lines = NULL; while (fgets(line, MAX_LINE, fp)) { char *trimmed = line; while (isspace(*trimmed)) trimmed++; if (*trimmed && *trimmed != '#') { lines = realloc(lines, (line_count + 1) * sizeof(char*)); lines[line_count++] = strdup(trimmed); } } fclose(fp); int index = 0; off->header = strdup(lines[index++]); char *counts_str = lines[index++]; sscanf(counts_str, "%d %d %d", &off->N, &off->F, &off->E); off->dimensionality = strstr(off->header, "4") ? 4 : 3; off->has_colors = strstr(off->header, "C") ? 1 : 0; off->vertices = malloc(off->N * sizeof(double*)); for (int i = 0; i < off->N; i++) { off->vertices[i] = malloc(off->dimensionality * sizeof(double)); char *v_str = lines[index++]; char *token = strtok(v_str, " "); for (int j = 0; j < off->dimensionality; j++) { off->vertices[i][j] = atof(token); token = strtok(NULL, " "); } } off->faces = malloc(off->F * sizeof(Face)); for (int i = 0; i < off->F; i++) { char *f_str = lines[index++]; char *token = strtok(f_str, " "); off->faces[i].num_verts = atoi(token); off->faces[i].indices = malloc(off->faces[i].num_verts * sizeof(int)); token = strtok(NULL, " "); for (int j = 0; j < off->faces[i].num_verts; j++) { off->faces[i].indices[j] = atoi(token); token = strtok(NULL, " "); } off->faces[i].color = NULL; off->faces[i].color_count = 0; if (off->has_colors && token) { int color_max = 4; // RGBA max off->faces[i].color = malloc(color_max * sizeof(double)); int c = 0; while (token && c < color_max) { off->faces[i].color[c++] = atof(token); token = strtok(NULL, " "); } off->faces[i].color_count = c; } } for (int i = 0; i < line_count; i++) free(lines[i]); free(lines); } void off_write(OFFFile *off, const char *filename) { FILE *fp = fopen(filename, "w"); if (!fp) { perror("Failed to write file"); return; } fprintf(fp, "%s\n", off->header); fprintf(fp, "%d %d %d\n", off->N, off->F, off->E); for (int i = 0; i < off->N; i++) { for (int j = 0; j < off->dimensionality; j++) { fprintf(fp, "%f ", off->vertices[i][j]); } fprintf(fp, "\n"); } for (int i = 0; i < off->F; i++) { fprintf(fp, "%d ", off->faces[i].num_verts); for (int j = 0; j < off->faces[i].num_verts; j++) { fprintf(fp, "%d ", off->faces[i].indices[j]); } for (int j = 0; j < off->faces[i].color_count; j++) { fprintf(fp, "%f ", off->faces[i].color[j]); } fprintf(fp, "\n"); } fclose(fp); } void off_print_properties(OFFFile *off) { printf("Header Keyword: %s\n", off->header); printf("Dimensionality: %d\n", off->dimensionality); printf("Number of Vertices (N): %d\n", off->N); printf("Number of Faces (F): %d\n", off->F); printf("Number of Edges (E): %d\n", off->E); printf("Vertices:\n"); for (int i = 0; i < off->N; i++) { printf(" ["); for (int j = 0; j < off->dimensionality; j++) { printf("%f%s", off->vertices[i][j], j < off->dimensionality - 1 ? ", " : ""); } printf("]\n"); } printf("Faces:\n"); for (int i = 0; i < off->F; i++) { printf(" Num Verts: %d, Indices: [", off->faces[i].num_verts); for (int j = 0; j < off->faces[i].num_verts; j++) { printf("%d%s", off->faces[i].indices[j], j < off->faces[i].num_verts - 1 ? ", " : ""); } printf("], Color: ["); if (off->faces[i].color_count > 0) { for (int j = 0; j < off->faces[i].color_count; j++) { printf("%f%s", off->faces[i].color[j], j < off->faces[i].color_count - 1 ? ", " : ""); } } else { printf("none"); } printf("]\n"); } } int main(int argc, char **argv) { if (argc > 1) { OFFFile *off = off_create(argv[1]); off_print_properties(off); off_write(off, "new.off"); off_destroy(off); } return 0; } // ===== end task-477 .OFF ===== // ===== task-478 .OGA [C++] ===== #include #include #include #include #include #include struct OgaParser { std::string filename; struct Page { size_t offset; char capture_pattern[5]; uint8_t version; bool continuation; bool bos; bool eos; int64_t granule_position; uint32_t serial_number; uint32_t page_sequence; uint32_t checksum; uint8_t num_segments; std::vector segment_table; size_t body_offset; size_t body_size; }; std::vector pages; std::vector data; OgaParser(const std::string& fn) : filename(fn) {} void read() { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) return; size_t size = file.tellg(); file.seekg(0); data.resize(size); file.read(reinterpret_cast(data.data()), size); size_t offset = 0; while (offset < size) { if (std::memcmp(data.data() + offset, "OggS", 4) != 0) { ++offset; continue; } Page page; page.offset = offset; std::strncpy(page.capture_pattern, reinterpret_cast(data.data() + offset), 4); page.capture_pattern[4] = '\0'; page.version = data[offset + 4]; uint8_t header_type = data[offset + 5]; page.continuation = header_type & 0x01; page.bos = header_type & 0x02; page.eos = header_type & 0x04; std::memcpy(&page.granule_position, data.data() + offset + 6, 8); // Little-endian assumed std::memcpy(&page.serial_number, data.data() + offset + 14, 4); std::memcpy(&page.page_sequence, data.data() + offset + 18, 4); std::memcpy(&page.checksum, data.data() + offset + 22, 4); page.num_segments = data[offset + 26]; page.segment_table.resize(page.num_segments); size_t body_size = 0; for (uint8_t i = 0; i < page.num_segments; ++i) { page.segment_table[i] = data[offset + 27 + i]; body_size += page.segment_table[i]; } page.body_offset = offset + 27 + page.num_segments; page.body_size = body_size; pages.push_back(page); offset += 27 + page.num_segments + body_size; } } void print_properties() { if (pages.empty()) { std::cout << "No valid Ogg pages found." << std::endl; return; } for (size_t idx = 0; idx < pages.size(); ++idx) { const auto& page = pages[idx]; std::cout << "Page " << (idx + 1) << " at offset " << page.offset << ":" << std::endl; std::cout << "- Capture pattern: " << page.capture_pattern << std::endl; std::cout << "- Stream structure version: " << static_cast(page.version) << std::endl; std::cout << "- Header type flags: Continuation=" << std::boolalpha << page.continuation << ", BOS=" << page.bos << ", EOS=" << page.eos << std::endl; std::cout << "- Absolute granule position: " << page.granule_position << std::endl; std::cout << "- Stream serial number: " << page.serial_number << std::endl; std::cout << "- Page sequence number: " << page.page_sequence << std::endl; std::cout << "- Page checksum: " << std::hex << std::uppercase << std::setw(8) << std::setfill('0') << page.checksum << std::dec << std::endl; std::cout << "- Number of page segments: " << static_cast(page.num_segments) << std::endl; std::cout << "- Segment table: ["; for (size_t i = 0; i < page.segment_table.size(); ++i) { std::cout << static_cast(page.segment_table[i]); if (i < page.segment_table.size() - 1) std::cout << ", "; } std::cout << "]" << std::endl << std::endl; } } void write(const std::string& output_filename) { if (pages.empty()) { throw std::runtime_error("No data to write; read a file first."); } std::ofstream file(output_filename, std::ios::binary); if (!file) return; for (const auto& page : pages) { // Build header char header[27 + 255]; // Max segments std::memcpy(header, "OggS", 4); header[4] = page.version; uint8_t header_type = (page.continuation ? 1 : 0) | (page.bos ? 2 : 0) | (page.eos ? 4 : 0); header[5] = header_type; std::memcpy(header + 6, &page.granule_position, 8); std::memcpy(header + 14, &page.serial_number, 4); std::memcpy(header + 18, &page.page_sequence, 4); std::memset(header + 22, 0, 4); // Placeholder checksum header[26] = page.num_segments; for (uint8_t i = 0; i < page.num_segments; ++i) { header[27 + i] = page.segment_table[i]; } size_t header_size = 27 + page.num_segments; // Full page for CRC std::vector full_page(header_size + page.body_size); std::memcpy(full_page.data(), header, header_size); std::memcpy(full_page.data() + header_size, data.data() + page.body_offset, page.body_size); // Calculate CRC-32 (simple impl; in prod use lib) uint32_t crc = 0; for (uint8_t byte : full_page) { crc ^= (byte << 24); for (int i = 0; i < 8; ++i) { crc = (crc << 1) ^ ((crc & 0x80000000) ? 0x04C11DB7 : 0); } } std::memcpy(full_page.data() + 22, &crc, 4); file.write(reinterpret_cast(full_page.data()), full_page.size()); } } }; // Example usage: // int main() { // OgaParser parser("example.oga"); // parser.read(); // parser.print_properties(); // parser.write("output.oga"); // return 0; // } // ===== end task-478 .OGA ===== // ===== task-479 .OGG [C] ===== #include #include #include #include #include typedef struct { char capture[5]; uint8_t version; uint8_t header_type; bool continuation; bool bos; bool eos; int64_t granule; uint32_t serial; uint32_t sequence; uint32_t checksum; uint8_t segments; uint8_t *segment_table; uint8_t *data; size_t data_size; } OggPage; typedef struct { OggPage *pages; size_t page_count; } OggHandler; void init_handler(OggHandler *handler) { handler->pages = NULL; handler->page_count = 0; } void read_and_decode(OggHandler *handler, const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) { perror("Failed to open file"); exit(1); } fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); size_t offset = 0; while (offset < size) { if (memcmp(data + offset, "OggS", 4) != 0) { fprintf(stderr, "Invalid capture pattern at offset %zu\n", offset); free(data); exit(1); } OggPage page; strcpy(page.capture, "OggS"); page.version = data[offset + 4]; page.header_type = data[offset + 5]; page.continuation = (page.header_type & 0x01) != 0; page.bos = (page.header_type & 0x02) != 0; page.eos = (page.header_type & 0x04) != 0; memcpy(&page.granule, data + offset + 6, 8); // Assume little-endian host or swap if needed memcpy(&page.serial, data + offset + 14, 4); memcpy(&page.sequence, data + offset + 18, 4); memcpy(&page.checksum, data + offset + 22, 4); page.segments = data[offset + 26]; page.segment_table = malloc(page.segments); memcpy(page.segment_table, data + offset + 27, page.segments); page.data_size = 0; for (int i = 0; i < page.segments; i++) page.data_size += page.segment_table[i]; page.data = malloc(page.data_size); memcpy(page.data, data + offset + 27 + page.segments, page.data_size); handler->pages = realloc(handler->pages, sizeof(OggPage) * (handler->page_count + 1)); handler->pages[handler->page_count] = page; handler->page_count++; offset += 27 + page.segments + page.data_size; } free(data); } void print_properties(const OggHandler *handler) { for (size_t i = 0; i < handler->page_count; i++) { const OggPage *page = &handler->pages[i]; printf("Page %zu:\n", i + 1); printf(" Capture Pattern: %s\n", page->capture); printf(" Stream Structure Version: %u\n", page->version); printf(" Header Type Flag: 0x%02x (Continuation: %s, BOS: %s, EOS: %s)\n", page->header_type, page->continuation ? "true" : "false", page->bos ? "true" : "false", page->eos ? "true" : "false"); printf(" Absolute Granule Position: %ld\n", page->granule); printf(" Stream Serial Number: %u\n", page->serial); printf(" Page Sequence Number: %u\n", page->sequence); printf(" Page Checksum: 0x%08x\n", page->checksum); printf(" Page Segments: %u\n", page->segments); printf(" Segment Table: ["); for (int j = 0; j < page->segments; j++) { printf("%u", page->segment_table[j]); if (j < page->segments - 1) printf(", "); } printf("]\n\n"); } } void write(const OggHandler *handler, const char *output_filename) { FILE *f = fopen(output_filename, "wb"); if (!f) { perror("Failed to open output file"); exit(1); } for (size_t i = 0; i < handler->page_count; i++) { const OggPage *page = &handler->pages[i]; uint8_t header[27 + page->segments]; memcpy(header, "OggS", 4); header[4] = page->version; header[5] = page->header_type; memcpy(header + 6, &page->granule, 8); memcpy(header + 14, &page->serial, 4); memcpy(header + 18, &page->sequence, 4); uint32_t checksum_placeholder = 0; memcpy(header + 22, &checksum_placeholder, 4); header[26] = page->segments; memcpy(header + 27, page->segment_table, page->segments); size_t full_size = sizeof(header) + page->data_size; uint8_t *full_page = malloc(full_size); memcpy(full_page, header, sizeof(header)); memcpy(full_page + sizeof(header), page->data, page->data_size); // Calculate checksum (simplified) uint32_t crc = 0; for (size_t j = 0; j < full_size; j++) { crc = (crc << 8) ^ (crc >> 24) ^ full_page[j]; } memcpy(full_page + 22, &crc, 4); fwrite(full_page, 1, full_size, f); free(full_page); } fclose(f); } void free_handler(OggHandler *handler) { for (size_t i = 0; i < handler->page_count; i++) { free(handler->pages[i].segment_table); free(handler->pages[i].data); } free(handler->pages); } // Example usage: // int main(int argc, char **argv) { // OggHandler handler; // init_handler(&handler); // read_and_decode(&handler, "example.ogg"); // print_properties(&handler); // write(&handler, "output.ogg"); // free_handler(&handler); // return 0; // } // ===== end task-479 .OGG ===== // ===== task-480 .OGV [C++] ===== #include #include #include #include #include struct OggPage { char capture[5] = "OggS"; uint8_t version; uint8_t header_type; uint64_t granule; uint32_t serial; uint32_t page_seq; uint32_t checksum; uint8_t seg_count; std::vector seg_table; }; class OGVHandler { private: std::string filepath; std::vector pages; public: OGVHandler(const std::string& fp) : filepath(fp) { parse(); } void parse() { std::ifstream file(filepath, std::ios::binary); if (!file) return; file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(data.data(), size); size_t offset = 0; while (offset < size) { if (std::memcmp(&data[offset], "OggS", 4) != 0) { std::cout << "Invalid magic at offset " << offset << std::endl; break; } OggPage page; page.version = static_cast(data[offset + 4]); page.header_type = static_cast(data[offset + 5]); std::memcpy(&page.granule, &data[offset + 6], 8); // Little-endian assumed std::memcpy(&page.serial, &data[offset + 14], 4); std::memcpy(&page.page_seq, &data[offset + 18], 4); std::memcpy(&page.checksum, &data[offset + 22], 4); page.seg_count = static_cast(data[offset + 26]); page.seg_table.resize(page.seg_count); std::memcpy(page.seg_table.data(), &data[offset + 27], page.seg_count); size_t payload_size = 0; for (auto len : page.seg_table) payload_size += len; pages.push_back(page); offset += 27 + page.seg_count + payload_size; } } void printProperties() const { for (size_t i = 0; i < pages.size(); ++i) { const auto& page = pages[i]; std::cout << "Page " << (i + 1) << ":" << std::endl; std::cout << " Capture Pattern: " << page.capture << std::endl; std::cout << " Version: " << static_cast(page.version) << std::endl; std::cout << " Header Type: 0x" << std::hex << static_cast(page.header_type) << " (Continued: " << ((page.header_type & 1) ? "Yes" : "No") << ", BOS: " << ((page.header_type & 2) ? "Yes" : "No") << ", EOS: " << ((page.header_type & 4) ? "Yes" : "No") << ")" << std::dec << std::endl; std::cout << " Granule Position: " << page.granule << std::endl; std::cout << " Serial Number: " << page.serial << std::endl; std::cout << " Page Sequence: " << page.page_seq << std::endl; std::cout << " Checksum: 0x" << std::hex << page.checksum << std::dec << std::endl; std::cout << " Segments Count: " << static_cast(page.seg_count) << std::endl; std::cout << " Segment Table: ["; for (size_t j = 0; j < page.seg_table.size(); ++j) { std::cout << static_cast(page.seg_table[j]); if (j < page.seg_table.size() - 1) std::cout << ", "; } std::cout << "]" << std::endl; } } void writeModified(const std::string& output_path, const std::vector& modify_granule) const { std::ifstream fin(filepath, std::ios::binary); if (!fin) return; fin.seekg(0, std::ios::end); size_t size = fin.tellg(); fin.seekg(0); std::vector data(size); fin.read(data.data(), size); size_t offset = 0; size_t page_num = 0; while (offset < size) { if (std::memcmp(&data[offset], "OggS", 4) != 0) break; uint8_t seg_count = static_cast(data[offset + 26]); size_t payload_size = 0; for (size_t i = 0; i < seg_count; ++i) { payload_size += static_cast(data[offset + 27 + i]); } if (page_num < modify_granule.size()) { std::memcpy(&data[offset + 6], &modify_granule[page_num], 8); // Recalculate checksum (placeholder) std::memset(&data[offset + 22], 0, 4); } offset += 27 + seg_count + payload_size; ++page_num; } std::ofstream fout(output_path, std::ios::binary); fout.write(data.data(), size); } }; // Example usage: // int main() { // OGVHandler handler("sample.ogv"); // handler.printProperties(); // handler.writeModified("modified.ogv", {12345, 67890}); // return 0; // } // ===== end task-480 .OGV ===== // ===== task-481 .OGX [C++] ===== #include #include #include #include #include #include class OGXHandler { private: std::string filepath; std::map properties; public: OGXHandler(const std::string& fp) : filepath(fp) { decode(); } void decode() { std::ifstream file(filepath, std::ios::binary); if (!file) return; file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(data.data(), size); size_t offset = 0; while (offset < size) { if (std::memcmp(&data[offset], "OggS", 4) == 0) { properties["Capture Pattern"] = "OggS"; offset += 4; uint8_t version = static_cast(data[offset]); properties["Version"] = std::to_string(version); offset += 1; uint8_t headerType = static_cast(data[offset]); properties["Header Type"] = std::to_string(headerType); offset += 1; int64_t granulePos = *reinterpret_cast(&data[offset]); properties["Granule Position"] = std::to_string(granulePos); offset += 8; uint32_t serial = *reinterpret_cast(&data[offset]); properties["Bitstream Serial Number"] = std::to_string(serial); offset += 4; uint32_t pageSeq = *reinterpret_cast(&data[offset]); properties["Page Sequence Number"] = std::to_string(pageSeq); offset += 4; uint32_t checksum = *reinterpret_cast(&data[offset]); properties["Checksum"] = std::to_string(checksum); offset += 4; uint8_t pageSegments = static_cast(data[offset]); properties["Page Segments"] = std::to_string(pageSegments); offset += 1; std::vector segmentTable(pageSegments); for (uint8_t i = 0; i < pageSegments; ++i) { segmentTable[i] = static_cast(data[offset++]); } std::string segStr = "["; for (auto len : segmentTable) segStr += std::to_string(len) + ", "; segStr += "]"; properties["Segment Table"] = segStr; size_t packetSize = 0; for (auto len : segmentTable) packetSize += len; std::vector packet(packetSize); std::memcpy(packet.data(), &data[offset], packetSize); offset += packetSize; if ((headerType & 0x02) && std::memcmp(packet.data(), "fishead\0", 8) == 0) { properties["Skeleton Identifier"] = "fishead"; uint16_t major = *reinterpret_cast(&packet[8]); uint16_t minor = *reinterpret_cast(&packet[10]); properties["Skeleton Version"] = std::to_string(major) + "." + std::to_string(minor); // Add other fields... } else if (std::memcmp(packet.data(), "fisbone\0", 8) == 0) { properties["Skeleton Fisbone Identifier"] = "fisbone"; // Parse fisbone... } } else { offset++; } } } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& newFilepath) { std::ifstream src(filepath, std::ios::binary); std::ofstream dst(newFilepath, std::ios::binary); dst << src.rdbuf(); std::cout << "Wrote to " << newFilepath << std::endl; } }; // Example usage: // int main() { // OGXHandler handler("example.ogx"); // handler.printProperties(); // handler.write("new.ogx"); // return 0; // } // ===== end task-481 .OGX ===== // ===== task-482 .OPUS [C++] ===== #include #include #include #include #include #include #include class OpusFile { private: std::string filename; std::map head; // Use int64_t for values std::string vendor; std::vector comments; uint16_t le16(const unsigned char* p) { return (p[1] << 8) | p[0]; } int16_t sle16(const unsigned char* p) { return static_cast(le16(p)); } uint32_t le32(const unsigned char* p) { return (p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0]; } int32_t sle32(const unsigned char* p) { return static_cast(le32(p)); } public: OpusFile(const std::string& fn) : filename(fn) { parse(); } void parse() { std::ifstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Error opening file"); } file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0); std::vector filedata(size); file.read(reinterpret_cast(filedata.data()), size); size_t offset = 0; std::vector current_packet; std::vector> packets; while (offset < size && packets.size() < 2) { if (std::memcmp(&filedata[offset], "OggS", 4) != 0) { throw std::runtime_error("Invalid Ogg file"); } offset += 4; unsigned char version = filedata[offset++]; if (version != 0) { throw std::runtime_error("Invalid Ogg version"); } unsigned char header_type = filedata[offset++]; offset += 8; // granule offset += 4; // serial offset += 4; // page seq offset += 4; // crc unsigned char num_segments = filedata[offset++]; std::vector seg_table(num_segments); std::memcpy(seg_table.data(), &filedata[offset], num_segments); offset += num_segments; size_t page_data_len = 0; for (auto s : seg_table) page_data_len += s; std::vector page_data(page_data_len); std::memcpy(page_data.data(), &filedata[offset], page_data_len); offset += page_data_len; size_t seg_idx = 0; size_t data_pos = 0; while (seg_idx < num_segments) { if (!current_packet.empty()) { unsigned char seg_size = seg_table[seg_idx]; current_packet.insert(current_packet.end(), page_data.begin() + data_pos, page_data.begin() + data_pos + seg_size); data_pos += seg_size; seg_idx++; if (seg_size < 255) { packets.push_back(current_packet); current_packet.clear(); } } else { std::vector packet_data; while (seg_idx < num_segments && seg_table[seg_idx] == 255) { unsigned char seg_size = seg_table[seg_idx]; packet_data.insert(packet_data.end(), page_data.begin() + data_pos, page_data.begin() + data_pos + seg_size); data_pos += seg_size; seg_idx++; } if (seg_idx < num_segments) { unsigned char seg_size = seg_table[seg_idx]; packet_data.insert(packet_data.end(), page_data.begin() + data_pos, page_data.begin() + data_pos + seg_size); data_pos += seg_size; seg_idx++; packets.push_back(packet_data); } else { current_packet = packet_data; } } } } if (packets.size() < 2) { throw std::runtime_error("Incomplete headers"); } // Parse OpusHead auto& head_bytes = packets[0]; if (std::memcmp(head_bytes.data(), "OpusHead", 8) != 0) { throw std::runtime_error("Invalid OpusHead"); } head["version"] = head_bytes[8]; head["channels"] = head_bytes[9]; head["pre_skip"] = le16(&head_bytes[10]); head["input_sample_rate"] = le32(&head_bytes[12]); head["output_gain"] = sle16(&head_bytes[16]); head["channel_mapping_family"] = head_bytes[18]; size_t extra_offset = 19; if (head["channel_mapping_family"] > 0) { head["stream_count"] = head_bytes[extra_offset++]; head["coupled_count"] = head_bytes[extra_offset++]; // Channel mapping as comma-separated string for simplicity std::string mapping_str; for (int i = 0; i < head["channels"]; ++i) { if (!mapping_str.empty()) mapping_str += ", "; mapping_str += std::to_string(head_bytes[extra_offset + i]); } // Store as string since map is int64 head["channel_mapping"] = 0; // Placeholder; print separately if needed std::cout << "Channel Mapping: " << mapping_str << std::endl; // Handle list separately } // Parse OpusTags auto& tags_bytes = packets[1]; if (std::memcmp(tags_bytes.data(), "OpusTags", 8) != 0) { throw std::runtime_error("Invalid OpusTags"); } size_t p_offset = 8; uint32_t vendor_len = le32(&tags_bytes[p_offset]); p_offset += 4; vendor = std::string(reinterpret_cast(&tags_bytes[p_offset]), vendor_len); p_offset += vendor_len; uint32_t comment_count = le32(&tags_bytes[p_offset]); p_offset += 4; for (uint32_t i = 0; i < comment_count; ++i) { uint32_t len = le32(&tags_bytes[p_offset]); p_offset += 4; std::string comm(reinterpret_cast(&tags_bytes[p_offset]), len); comments.push_back(comm); p_offset += len; } } void printProperties() { std::cout << "OpusHead Properties:" << std::endl; for (const auto& kv : head) { std::cout << kv.first << ": " << kv.second << std::endl; } std::cout << "\nOpusTags Properties:" << std::endl; std::cout << "Vendor: " << vendor << std::endl; std::cout << "Comments:" << std::endl; for (const auto& comm : comments) { std::cout << comm << std::endl; } } // For write: Simple example to write modified headers (audio data not included) void write(const std::string& new_filename) { // Rebuild packets (simplified) std::vector head_packet; head_packet.insert(head_packet.end(), "OpusHead", "OpusHead" + 8); head_packet.push_back(static_cast(head["version"])); head_packet.push_back(static_cast(head["channels"])); uint16_t pre = static_cast(head["pre_skip"]); head_packet.push_back(pre & 0xFF); head_packet.push_back((pre >> 8) & 0xFF); uint32_t rate = static_cast(head["input_sample_rate"]); head_packet.push_back(rate & 0xFF); head_packet.push_back((rate >> 8) & 0xFF); head_packet.push_back((rate >> 16) & 0xFF); head_packet.push_back((rate >> 24) & 0xFF); int16_t gain = static_cast(head["output_gain"]); head_packet.push_back(gain & 0xFF); head_packet.push_back((gain >> 8) & 0xFF); head_packet.push_back(static_cast(head["channel_mapping_family"])); if (head["channel_mapping_family"] > 0) { head_packet.push_back(static_cast(head["stream_count"])); head_packet.push_back(static_cast(head["coupled_count"])); // Assume mapping not modified; skip detailed rebuild for simplicity } std::vector tags_packet; tags_packet.insert(tags_packet.end(), "OpusTags", "OpusTags" + 8); uint32_t vlen = vendor.size(); tags_packet.push_back(vlen & 0xFF); tags_packet.push_back((vlen >> 8) & 0xFF); tags_packet.push_back((vlen >> 16) & 0xFF); tags_packet.push_back((vlen >> 24) & 0xFF); tags_packet.insert(tags_packet.end(), vendor.begin(), vendor.end()); uint32_t ccount = comments.size(); tags_packet.push_back(ccount & 0xFF); tags_packet.push_back((ccount >> 8) & 0xFF); tags_packet.push_back((ccount >> 16) & 0xFF); tags_packet.push_back((ccount >> 24) & 0xFF); for (const auto& comm : comments) { uint32_t clen = comm.size(); tags_packet.push_back(clen & 0xFF); tags_packet.push_back((clen >> 8) & 0xFF); tags_packet.push_back((clen >> 16) & 0xFF); tags_packet.push_back((clen >> 24) & 0xFF); tags_packet.insert(tags_packet.end(), comm.begin(), comm.end()); } std::ofstream out(new_filename, std::ios::binary); out.write(reinterpret_cast(head_packet.data()), head_packet.size()); out.write(reinterpret_cast(tags_packet.data()), tags_packet.size()); std::cout << "Wrote modified headers (audio data not included in this simple implementation)." << std::endl; } }; // Example usage: // int main() { // OpusFile opus("example.opus"); // opus.printProperties(); // opus.write("modified.opus"); // return 0; // } // ===== end task-482 .OPUS ===== // ===== task-483 .ORG [C] ===== #include #include #include #include #define MAX_LINE_LEN 1024 #define MAX_HEADINGS 100 #define MAX_PROPS_PER_HEADING 50 const char* PROPERTY_LIST[] = { "ALLTAGS", "BLOCKED", "CATEGORY", "CLOCKSUM", "CLOCKSUM_T", "CLOSED", "DEADLINE", "FILE", "ITEM", "PRIORITY", "SCHEDULED", "TAGS", "TIMESTAMP", "TIMESTAMP_IA", "TODO", "ARCHIVE", "COLUMNS", "COOKIE_DATA", "LOGGING", "NOBLOCKING", "ORDERED", "STYLE" }; const int NUM_PROPERTIES = sizeof(PROPERTY_LIST) / sizeof(PROPERTY_LIST[0]); typedef struct { char* key; char* value; } Prop; typedef struct { char* heading; Prop props[MAX_PROPS_PER_HEADING]; int prop_count; } HeadingProps; typedef struct { char* filename; char* content; HeadingProps headings[MAX_HEADINGS]; int heading_count; } OrgFile; OrgFile* orgfile_new(const char* filename) { OrgFile* org = malloc(sizeof(OrgFile)); org->filename = strdup(filename); org->content = NULL; org->heading_count = 0; return org; } void orgfile_free(OrgFile* org) { free(org->filename); if (org->content) free(org->content); for (int i = 0; i < org->heading_count; i++) { free(org->headings[i].heading); for (int j = 0; j < org->headings[i].prop_count; j++) { free(org->headings[i].props[j].key); free(org->headings[i].props[j].value); } } free(org); } char* orgfile_open_and_read(OrgFile* org) { FILE* fp = fopen(org->filename, "r"); if (!fp) return NULL; fseek(fp, 0, SEEK_END); long size = ftell(fp); fseek(fp, 0, SEEK_SET); org->content = malloc(size + 1); fread(org->content, 1, size, fp); org->content[size] = '\0'; fclose(fp); return org->content; } void orgfile_decode_properties(OrgFile* org) { if (!org->content) orgfile_open_and_read(org); char* content_copy = strdup(org->content); char* line = strtok(content_copy, "\n"); char* current_heading = NULL; int in_properties_drawer = 0; org->heading_count = 0; while (line) { char* trimmed = line; while (*trimmed == ' ' || *trimmed == '\t') trimmed++; if (strncmp(trimmed, "*", 1) == 0) { if (current_heading) free(current_heading); current_heading = strdup(trimmed); if (org->heading_count < MAX_HEADINGS) { org->headings[org->heading_count].heading = strdup(current_heading); org->headings[org->heading_count].prop_count = 0; org->heading_count++; } } else if (strcmp(trimmed, ":PROPERTIES:") == 0) { in_properties_drawer = 1; } else if (strcmp(trimmed, ":END:") == 0) { in_properties_drawer = 0; } else if (in_properties_drawer && strncmp(trimmed, ":", 1) == 0) { char* colon_pos = strchr(trimmed + 1, ':'); if (colon_pos) { *colon_pos = '\0'; char* key = trimmed + 1; char* value = colon_pos + 1; while (*value == ' ') value++; char upper_key[MAX_LINE_LEN]; strcpy(upper_key, key); for (char* p = upper_key; *p; p++) *p = toupper(*p); int is_intrinsic = 0; for (int i = 0; i < NUM_PROPERTIES; i++) { if (strcmp(upper_key, PROPERTY_LIST[i]) == 0) { is_intrinsic = 1; break; } } if (is_intrinsic && org->heading_count > 0) { HeadingProps* hp = &org->headings[org->heading_count - 1]; if (hp->prop_count < MAX_PROPS_PER_HEADING) { hp->props[hp->prop_count].key = strdup(key); hp->props[hp->prop_count].value = strdup(value); hp->prop_count++; } } } } line = strtok(NULL, "\n"); } free(content_copy); if (current_heading) free(current_heading); } void orgfile_write(OrgFile* org, const char* new_content) { FILE* fp = fopen(org->filename, "w"); if (fp) { fprintf(fp, "%s", new_content); fclose(fp); } } void orgfile_print_properties(OrgFile* org) { if (org->heading_count == 0) { orgfile_decode_properties(org); } for (int i = 0; i < org->heading_count; i++) { printf("%s\n", org->headings[i].heading); for (int j = 0; j < org->headings[i].prop_count; j++) { printf("%s: %s\n", org->headings[i].props[j].key, org->headings[i].props[j].value); } printf("\n"); } } // ===== end task-483 .ORG ===== // ===== task-484 .OSB [C++] ===== #include #include #include #include #include #include #include class OsbFile { private: std::string filename; std::vector> events; std::map> properties; public: OsbFile(const std::string& fn) : filename(fn) {} void read() { std::ifstream file(filename); std::string line; bool inEvents = false; std::map currentObject; while (std::getline(file, line)) { line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); if (line == "[Events]") { inEvents = true; continue; } if (!inEvents || line.rfind("//", 0) == 0 || line.empty()) continue; if (line[0] == ' ' || line[0] == '\t') { // Command std::vector fields = split(line.substr(1), ','); if (!currentObject.empty()) { auto commands = any_cast>>(currentObject["commands"]); std::map command; command["type"] = fields[0]; command["easing"] = fields[1]; command["start_time"] = fields[2]; command["end_time"] = fields[3]; std::vector params(fields.begin() + 4, fields.end()); command["params"] = params; commands.push_back(command); currentObject["commands"] = commands; collectProperty("command_types", fields[0]); collectProperty("easings", fields[1]); } } else { // Event std::vector fields = split(line, ','); std::map event; event["type"] = fields[0]; std::vector params(fields.begin() + 1, fields.end()); event["params"] = params; events.push_back(event); currentObject = event; collectProperty("event_types", fields[0]); if (fields[0] == "Sprite" || fields[0] == "Animation") { collectProperty("layers", fields[1]); collectProperty("origins", fields[2]); } if (fields[0] == "Animation") { collectProperty("looptype", fields[8]); } if (fields[0] == "Sample") { collectProperty("layers", fields[2]); } } } file.close(); } void collectProperty(const std::string& key, const std::string& value) { properties[key].insert(value); } std::vector split(const std::string& s, char delimiter) { std::vector tokens; std::string token; std::istringstream tokenStream(s); while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; } void printProperties() { std::cout << "All collected properties:" << std::endl; for (const auto& p : properties) { std::cout << p.first << ": "; for (auto it = p.second.begin(); it != p.second.end(); ++it) { if (it != p.second.begin()) std::cout << ", "; std::cout << *it; } std::cout << std::endl; } std::cout << "\nFull events:" << std::endl; // Printing events would require casting and looping, omitted for brevity in this example } void write(const std::string& outputFilename) { std::ofstream file(outputFilename); file << "[Events]\n"; for (const auto& event : events) { file << any_cast(event.at("type")) << ","; auto params = any_cast>(event.at("params")); for (size_t i = 0; i < params.size(); ++i) { file << params[i]; if (i < params.size() - 1) file << ","; } file << "\n"; if (event.count("commands")) { auto commands = any_cast>>(event.at("commands")); for (const auto& command : commands) { file << " " << any_cast(command.at("type")) << "," << any_cast(command.at("easing")) << "," << any_cast(command.at("start_time")) << "," << any_cast(command.at("end_time")) << ","; auto cmdParams = any_cast>(command.at("params")); for (size_t i = 0; i < cmdParams.size(); ++i) { file << cmdParams[i]; if (i < cmdParams.size() - 1) file << ","; } file << "\n"; } } } file.close(); } }; // Example usage: // int main() { // OsbFile osb("example.osb"); // osb.read(); // osb.printProperties(); // osb.write("output.osb"); // return 0; // } // ===== end task-484 .OSB ===== // ===== task-485 .OSB [C] ===== #include #include #include typedef struct { const char* filename; xmlDocPtr doc; } OSCFile; OSCFile* OSCFile_create(const char* filename) { OSCFile* osc = (OSCFile*)malloc(sizeof(OSCFile)); osc->filename = filename; osc->doc = NULL; return osc; } void OSCFile_read(OSCFile* osc) { osc->doc = xmlReadFile(osc->filename, NULL, 0); if (osc->doc == NULL) { printf("Failed to parse %s\n", osc->filename); } } void traverse(xmlNode* node, const char* indent) { printf("%sElement: %s\n", indent, node->name); xmlAttr* attr = node->properties; while (attr) { printf("%s - %s: %s\n", indent, attr->name, xmlNodeGetContent(attr->children)); attr = attr->next; } xmlNode* child = node->children; char newIndent[256]; snprintf(newIndent, sizeof(newIndent), "%s ", indent); while (child) { if (child->type == XML_ELEMENT_NODE) { traverse(child, newIndent); } child = child->next; } } void OSCFile_print_properties(OSCFile* osc) { if (osc->doc == NULL) { printf("No file loaded. Call read first.\n"); return; } xmlNode* root = xmlDocGetRootElement(osc->doc); traverse(root, ""); } void OSCFile_write(OSCFile* osc, const char* newFilename) { if (osc->doc == NULL) { printf("No file loaded. Call read first.\n"); return; } xmlSaveFormatFileEnc(newFilename, osc->doc, "UTF-8", 1); } void OSCFile_destroy(OSCFile* osc) { if (osc->doc) xmlFreeDoc(osc->doc); free(osc); } // Example usage: // int main() { // OSCFile* osc = OSCFile_create("example.osc"); // OSCFile_read(osc); // OSCFile_print_properties(osc); // OSCFile_write(osc, "new.osc"); // OSCFile_destroy(osc); // return 0; // } // ===== end task-485 .OSB ===== // ===== task-486 .OSK [C] ===== #include #include #include #include // Assume libzip or minizip is installed and linked typedef struct { char* filepath; // Use a simple array of sections and key-value pairs for properties (limited to 100 sections, 100 props each) char sections[100][50]; char keys[100][100][50]; char values[100][100][256]; int section_count; int prop_counts[100]; } OSKHandler; void init_osk(OSKHandler* handler, const char* filepath) { handler->filepath = strdup(filepath); handler->section_count = 0; memset(handler->prop_counts, 0, sizeof(handler->prop_counts)); read_osk(handler); } void read_osk(OSKHandler* handler) { struct zip* z = zip_open(handler->filepath, ZIP_RDONLY, NULL); if (z == NULL) { printf("Failed to open ZIP\n"); return; } const char* ini_name = NULL; int num_entries = zip_get_num_entries(z, 0); for (int i = 0; i < num_entries; i++) { const char* name = zip_get_name(z, i, 0); if (strcasestr(name, "skin.ini")) { ini_name = name; break; } } if (ini_name) { struct zip_file* f = zip_fopen(z, ini_name, 0); if (f) { struct zip_stat st; zip_stat(z, ini_name, 0, &st); char* content = malloc(st.size + 1); zip_fread(f, content, st.size); content[st.size] = '\0'; zip_fclose(f); parse_ini(handler, content); free(content); } } else { printf("No skin.ini found\n"); } zip_close(z); } void parse_ini(OSKHandler* handler, const char* content) { char line[512]; int sec_idx = -1; const char* ptr = content; while (*ptr) { int len = 0; while (*ptr && *ptr != '\n' && len < 511) { line[len++] = *ptr++; } if (*ptr == '\n') ptr++; line[len] = '\0'; char* trim = strtok(line, " \t\r\n"); if (trim) { if (trim[0] == '[' && trim[strlen(trim)-1] == ']') { sec_idx++; strncpy(handler->sections[sec_idx], trim + 1, strlen(trim) - 2); handler->sections[sec_idx][strlen(trim) - 2] = '\0'; handler->section_count = sec_idx + 1; } else if (strchr(trim, ':')) { if (sec_idx >= 0) { char* key = strtok(trim, ":"); char* val = strtok(NULL, "\r\n"); strncpy(handler->keys[sec_idx][handler->prop_counts[sec_idx]], key, 49); strncpy(handler->values[sec_idx][handler->prop_counts[sec_idx]], val ? val : "", 255); handler->prop_counts[sec_idx]++; } } } } } void print_properties(OSKHandler* handler) { for (int i = 0; i < handler->section_count; i++) { printf("[%s]\n", handler->sections[i]); for (int j = 0; j < handler->prop_counts[i]; j++) { printf("%s: %s\n", handler->keys[i][j], handler->values[i][j]); } printf("\n"); } } // Write function (simplified: recreates ZIP with updated ini) void write_osk(OSKHandler* handler, const char* new_section, const char* new_key, const char* new_value) { // Find and update property (simplified for one update) for (int i = 0; i < handler->section_count; i++) { if (strcmp(handler->sections[i], new_section) == 0) { for (int j = 0; j < handler->prop_counts[i]; j++) { if (strcmp(handler->keys[i][j], new_key) == 0) { strncpy(handler->values[i][j], new_value, 255); break; } } break; } } // Rebuild ZIP (open old, copy all except ini, add new ini) struct zip* z_old = zip_open(handler->filepath, ZIP_RDONLY, NULL); char new_path[256]; snprintf(new_path, sizeof(new_path), "%s.new", handler->filepath); struct zip* z_new = zip_open(new_path, ZIP_CREATE, NULL); int num_entries = zip_get_num_entries(z_old, 0); for (int i = 0; i < num_entries; i++) { const char* name = zip_get_name(z_old, i, 0); if (strcasestr(name, "skin.ini")) { char* new_ini = generate_ini(handler); zip_source* src = zip_source_buffer(z_new, new_ini, strlen(new_ini), 1); zip_add(z_new, name, src); } else { zip_source* src = zip_source_zip(z_new, z_old, i, 0, 0, -1); zip_add(z_new, name, src); } } zip_close(z_new); zip_close(z_old); } char* generate_ini(OSKHandler* handler) { char* buf = malloc(1024 * 1024); // Assume enough char* ptr = buf; for (int i = 0; i < handler->section_count; i++) { ptr += sprintf(ptr, "[%s]\n", handler->sections[i]); for (int j = 0; j < handler->prop_counts[i]; j++) { ptr += sprintf(ptr, "%s: %s\n", handler->keys[i][j], handler->values[i][j]); } ptr += sprintf(ptr, "\n"); } return buf; } void free_osk(OSKHandler* handler) { free(handler->filepath); } // Example usage: // int main() { // OSKHandler handler; // init_osk(&handler, "example.osk"); // print_properties(&handler); // write_osk(&handler, "General", "Name", "New Name"); // free_osk(&handler); // return 0; // } // ===== end task-486 .OSK ===== // ===== task-487 .OSM [C++] ===== #include #include #include #include "tinyxml2.h" // Assume tinyxml2 library is included. using namespace tinyxml2; class OSMFileHandler { private: std::string filepath; XMLDocument doc; public: OSMFileHandler(const std::string& fp) : filepath(fp) {} void readAndDecode() { if (doc.LoadFile(filepath.c_str()) != XML_SUCCESS) { std::cerr << "Failed to load file." << std::endl; return; } XMLElement* root = doc.FirstChildElement("osm"); XMLElement* bounds = doc.FirstChildElement("bounds"); XMLElement* note = doc.FirstChildElement("note"); XMLElement* meta = doc.FirstChildElement("meta"); std::cout << "OSM File Properties:" << std::endl; std::cout << "XML Version: 1.0" << std::endl; // Assumed std::cout << "Encoding: UTF-8" << std::endl; // Assumed std::cout << "OSM Version: " << (root ? root->Attribute("version") : "N/A") << std::endl; std::cout << "Generator: " << (root ? root->Attribute("generator") : "N/A") << std::endl; if (bounds) { std::cout << "Bounds:" << std::endl; std::cout << " minlat: " << bounds->Attribute("minlat") << std::endl; std::cout << " minlon: " << bounds->Attribute("minlon") << std::endl; std::cout << " maxlat: " << bounds->Attribute("maxlat") << std::endl; std::cout << " maxlon: " << bounds->Attribute("maxlon") << std::endl; } else { std::cout << "Bounds: N/A" << std::endl; } std::cout << "Note: " << (note ? note->GetText() : "N/A") << std::endl; std::cout << "Meta osm_base: " << (meta ? meta->Attribute("osm_base") : "N/A") << std::endl; } void write(const std::string& outputFilepath, const std::string& updateGenerator = "") { XMLElement* root = doc.FirstChildElement("osm"); if (!root) { std::cerr << "No data to write." << std::endl; return; } if (!updateGenerator.empty()) { root->SetAttribute("generator", updateGenerator.c_str()); } doc.SaveFile(outputFilepath.empty() ? filepath.c_str() : outputFilepath.c_str()); } }; // Example usage: // int main() { // OSMFileHandler handler("sample.osm"); // handler.readAndDecode(); // handler.write("output.osm", "Custom Generator"); // return 0; // } // ===== end task-487 .OSM ===== // ===== task-488 .OSR [C++] ===== #include #include #include #include #include #include // For little-endian conversions if needed class OSRFile { private: uint8_t gameMode; int32_t gameVersion; std::string beatmapMD5; std::string playerName; std::string replayMD5; uint16_t num300s; uint16_t num100s; uint16_t num50s; uint16_t numGekis; uint16_t numKatus; uint16_t numMisses; int32_t totalScore; uint16_t maxCombo; uint8_t perfect; int32_t mods; std::string lifeBarGraph; int64_t timestamp; int32_t compressedLength; std::vector compressedData; int64_t onlineScoreID; double additionalModInfo; // Optional std::string readString(std::ifstream& ifs) { uint8_t flag; ifs.read(reinterpret_cast(&flag), 1); if (flag == 0x00) return ""; if (flag != 0x0b) throw std::runtime_error("Invalid string flag"); uint32_t length = 0; uint32_t shift = 0; while (true) { uint8_t byte; ifs.read(reinterpret_cast(&byte), 1); length += (byte & 0x7f) << shift; if ((byte & 0x80) == 0) break; shift += 7; } std::string s(length, '\0'); ifs.read(&s[0], length); return s; } void writeString(std::ofstream& ofs, const std::string& s) { if (s.empty()) { ofs.put(0x00); return; } ofs.put(0x0b); uint32_t length = s.size(); while (length > 0) { uint8_t byte = length & 0x7f; length >>= 7; if (length > 0) byte |= 0x80; ofs.put(byte); } ofs.write(s.data(), s.size()); } public: OSRFile(const std::string& filepath = "") { if (!filepath.empty()) read(filepath); } void read(const std::string& filepath) { std::ifstream ifs(filepath, std::ios::binary); if (!ifs) throw std::runtime_error("Cannot open file"); ifs.read(reinterpret_cast(&gameMode), 1); ifs.read(reinterpret_cast(&gameVersion), 4); gameVersion = le32toh(gameVersion); beatmapMD5 = readString(ifs); playerName = readString(ifs); replayMD5 = readString(ifs); ifs.read(reinterpret_cast(&num300s), 2); num300s = le16toh(num300s); ifs.read(reinterpret_cast(&num100s), 2); num100s = le16toh(num100s); ifs.read(reinterpret_cast(&num50s), 2); num50s = le16toh(num50s); ifs.read(reinterpret_cast(&numGekis), 2); numGekis = le16toh(numGekis); ifs.read(reinterpret_cast(&numKatus), 2); numKatus = le16toh(numKatus); ifs.read(reinterpret_cast(&numMisses), 2); numMisses = le16toh(numMisses); ifs.read(reinterpret_cast(&totalScore), 4); totalScore = le32toh(totalScore); ifs.read(reinterpret_cast(&maxCombo), 2); maxCombo = le16toh(maxCombo); ifs.read(reinterpret_cast(&perfect), 1); ifs.read(reinterpret_cast(&mods), 4); mods = le32toh(mods); lifeBarGraph = readString(ifs); ifs.read(reinterpret_cast(×tamp), 8); timestamp = le64toh(timestamp); ifs.read(reinterpret_cast(&compressedLength), 4); compressedLength = le32toh(compressedLength); compressedData.resize(compressedLength); ifs.read(reinterpret_cast(compressedData.data()), compressedLength); ifs.read(reinterpret_cast(&onlineScoreID), 8); onlineScoreID = le64toh(onlineScoreID); if (mods & (1 << 23)) { ifs.read(reinterpret_cast(&additionalModInfo), 8); uint64_t bits = le64toh(*reinterpret_cast(&additionalModInfo)); additionalModInfo = *reinterpret_cast(&bits); } } void printProperties() const { std::cout << "gameMode: " << static_cast(gameMode) << std::endl; std::cout << "gameVersion: " << gameVersion << std::endl; std::cout << "beatmapMD5: " << beatmapMD5 << std::endl; std::cout << "playerName: " << playerName << std::endl; std::cout << "replayMD5: " << replayMD5 << std::endl; std::cout << "num300s: " << num300s << std::endl; std::cout << "num100s: " << num100s << std::endl; std::cout << "num50s: " << num50s << std::endl; std::cout << "numGekis: " << numGekis << std::endl; std::cout << "numKatus: " << numKatus << std::endl; std::cout << "numMisses: " << numMisses << std::endl; std::cout << "totalScore: " << totalScore << std::endl; std::cout << "maxCombo: " << maxCombo << std::endl; std::cout << "perfect: " << static_cast(perfect) << std::endl; std::cout << "mods: " << mods << std::endl; std::cout << "lifeBarGraph: " << lifeBarGraph << std::endl; std::cout << "timestamp: " << timestamp << std::endl; std::cout << "compressedLength: " << compressedLength << std::endl; std::cout << "compressedData: Binary data (length " << compressedData.size() << ")" << std::endl; std::cout << "onlineScoreID: " << onlineScoreID << std::endl; if (mods & (1 << 23)) { std::cout << "additionalModInfo: " << additionalModInfo << std::endl; } } void write(const std::string& filepath) { std::ofstream ofs(filepath, std::ios::binary); if (!ofs) throw std::runtime_error("Cannot open file"); ofs.write(reinterpret_cast(&gameMode), 1); int32_t leGameVersion = htole32(gameVersion); ofs.write(reinterpret_cast(&leGameVersion), 4); writeString(ofs, beatmapMD5); writeString(ofs, playerName); writeString(ofs, replayMD5); uint16_t leNum300s = htole16(num300s); ofs.write(reinterpret_cast(&leNum300s), 2); uint16_t leNum100s = htole16(num100s); ofs.write(reinterpret_cast(&leNum100s), 2); uint16_t leNum50s = htole16(num50s); ofs.write(reinterpret_cast(&leNum50s), 2); uint16_t leNumGekis = htole16(numGekis); ofs.write(reinterpret_cast(&leNumGekis), 2); uint16_t leNumKatus = htole16(numKatus); ofs.write(reinterpret_cast(&leNumKatus), 2); uint16_t leNumMisses = htole16(numMisses); ofs.write(reinterpret_cast(&leNumMisses), 2); int32_t leTotalScore = htole32(totalScore); ofs.write(reinterpret_cast(&leTotalScore), 4); uint16_t leMaxCombo = htole16(maxCombo); ofs.write(reinterpret_cast(&leMaxCombo), 2); ofs.write(reinterpret_cast(&perfect), 1); int32_t leMods = htole32(mods); ofs.write(reinterpret_cast(&leMods), 4); writeString(ofs, lifeBarGraph); int64_t leTimestamp = htole64(timestamp); ofs.write(reinterpret_cast(&leTimestamp), 8); int32_t leCompressedLength = htole32(compressedData.size()); ofs.write(reinterpret_cast(&leCompressedLength), 4); ofs.write(reinterpret_cast(compressedData.data()), compressedData.size()); int64_t leOnlineScoreID = htole64(onlineScoreID); ofs.write(reinterpret_cast(&leOnlineScoreID), 8); if (mods & (1 << 23)) { uint64_t bits = htole64(*reinterpret_cast(&additionalModInfo)); ofs.write(reinterpret_cast(&bits), 8); } } }; // ===== end task-488 .OSR ===== // ===== task-489 .OST [C] ===== #include #include #include #include typedef struct { uint32_t dwMagic; // Add all fields as members... // For brevity, use array or union for ANSI/Unicode } OSTHeader; void parse_header(const char* filepath, OSTHeader* header) { FILE* f = fopen(filepath, "rb"); if (!f) return; uint8_t data[544]; fread(data, 1, 544, f); memcpy(&header->dwMagic, data, 4); if (header->dwMagic != 0x2142444E) { fprintf(stderr, "Invalid .OST file\n"); fclose(f); exit(1); } // Parse all fields similarly... // Close f } void print_properties(const OSTHeader* header) { printf("dwMagic: 0x%X\n", header->dwMagic); // Print all } void write_header(const char* filepath, OSTHeader* header) { FILE* f = fopen(filepath, "rb+"); if (!f) return; uint8_t data[544]; fread(data, 1, 544, f); // Modify e.g. dwUnique uint32_t offset = header->is_unicode ? 44 : 36; uint32_t dwUnique; memcpy(&dwUnique, data + offset, 4); dwUnique += 1; memcpy(data + offset, &dwUnique, 4); fseek(f, 0, SEEK_SET); fwrite(data, 1, 544, f); fclose(f); } // Example // int main() { // OSTHeader header; // parse_header("path/to/file.ost", &header); // print_properties(&header); // write_header("path/to/file.ost", &header); // parse_header("path/to/file.ost", &header); // print_properties(&header); // return 0; // } // ===== end task-489 .OST ===== // ===== task-490 .OSU [C] ===== #include #include #include #define MAX_SECTIONS 10 #define MAX_LINES 1000 #define MAX_LINE_LEN 256 typedef struct { char *filepath; char version[50]; char sections[MAX_SECTIONS][50]; char *lines[MAX_SECTIONS][MAX_LINES]; int lineCounts[MAX_SECTIONS]; int sectionCount; } OsuFileHandler; OsuFileHandler* createHandler(const char *filepath) { OsuFileHandler *handler = malloc(sizeof(OsuFileHandler)); handler->filepath = strdup(filepath); handler->sectionCount = 0; memset(handler->version, 0, 50); for (int i = 0; i < MAX_SECTIONS; i++) { handler->lineCounts[i] = 0; } return handler; } void read(OsuFileHandler *handler) { FILE *file = fopen(handler->filepath, "r"); if (!file) { printf("Error opening file\n"); return; } char line[MAX_LINE_LEN]; int currentSection = -1; while (fgets(line, sizeof(line), file)) { char *trimmed = strtok(line, "\r\n"); if (!trimmed || strlen(trimmed) == 0 || strncmp(trimmed, "//", 2) == 0) continue; if (strncmp(trimmed, "osu file format v", 17) == 0) { strcpy(handler->version, trimmed); } else if (trimmed[0] == '[' && trimmed[strlen(trimmed)-1] == ']') { currentSection++; strcpy(handler->sections[currentSection], trimmed); handler->sectionCount = currentSection + 1; } else if (currentSection >= 0) { int idx = handler->lineCounts[currentSection]++; handler->lines[currentSection][idx] = strdup(trimmed); } } fclose(file); } void printProperties(OsuFileHandler *handler) { printf("Version: %s\n", handler->version); for (int i = 0; i < handler->sectionCount; i++) { printf("\n%s\n", handler->sections[i]); for (int j = 0; j < handler->lineCounts[i]; j++) { printf(" %s\n", handler->lines[i][j]); } } } void write(OsuFileHandler *handler, const char *newFilepath) { const char *path = newFilepath ? newFilepath : handler->filepath; FILE *file = fopen(path, "w"); if (!file) { printf("Error writing file\n"); return; } fprintf(file, "%s\n", handler->version); for (int i = 0; i < handler->sectionCount; i++) { fprintf(file, "\n%s\n", handler->sections[i]); for (int j = 0; j < handler->lineCounts[i]; j++) { fprintf(file, "%s\n", handler->lines[i][j]); } } fclose(file); } void freeHandler(OsuFileHandler *handler) { free(handler->filepath); for (int i = 0; i < handler->sectionCount; i++) { for (int j = 0; j < handler->lineCounts[i]; j++) { free(handler->lines[i][j]); } } free(handler); } // Example usage: // int main() { // OsuFileHandler *handler = createHandler("example.osu"); // read(handler); // printProperties(handler); // // Modify: handler->lines[0][handler->lineCounts[0]++] = strdup("NewKey:Value"); // write(handler, "modified.osu"); // freeHandler(handler); // return 0; // } // ===== end task-490 .OSU ===== // ===== task-491 .OSZ [C++] ===== #include #include #include #include #include #include #include class OSZHandler { private: std::string filepath; std::vector buffer; std::map> properties; // Simplified, use variants for types std::vector> cd_headers; // Mix types for simplicity uint16_t read_uint16(size_t& pos) { uint16_t val = *reinterpret_cast(&buffer[pos]); pos += 2; return val; } uint32_t read_uint32(size_t& pos) { uint32_t val = *reinterpret_cast(&buffer[pos]); pos += 4; return val; } std::string read_string(size_t& pos, size_t len) { std::string s(reinterpret_cast(&buffer[pos]), len); pos += len; return s; } public: OSZHandler(const std::string& fp) : filepath(fp) { std::ifstream file(fp, std::ios::binary | std::ios::ate); size_t size = file.tellg(); file.seekg(0); buffer.resize(size); file.read(reinterpret_cast(buffer.data()), size); parse_properties(); } void parse_properties() { size_t pos = buffer.size() - 22; while (pos > 0) { if (memcmp(&buffer[pos], "\x50\x4B\x05\x06", 4) == 0) break; --pos; } if (pos == 0) throw std::runtime_error("Invalid .OSZ/ZIP"); auto& eocd = properties["eocd"]; pos += 4; eocd["this_disk"] = read_uint16(pos); eocd["cd_start_disk"] = read_uint16(pos); eocd["entries_this_disk"] = read_uint16(pos); eocd["total_entries"] = read_uint16(pos); eocd["cd_size"] = read_uint32(pos); uint32_t cd_offset = read_uint32(pos); eocd["cd_offset"] = cd_offset; uint16_t comment_len = read_uint16(pos); eocd["comment_len"] = comment_len; // eocd["comment"] = read_string(pos, comment_len); // Add as string if needed // ZIP64 check simplified properties["is_zip64"]["value"] = 0; // false // Parse CD pos = cd_offset; while (pos < buffer.size() - 4 && memcmp(&buffer[pos], "\x50\x4B\x01\x02", 4) == 0) { std::map header; pos += 4; header["version_made"] = std::to_string(read_uint16(pos)); header["version_needed"] = std::to_string(read_uint16(pos)); header["flags"] = std::to_string(read_uint16(pos)); header["compression"] = std::to_string(read_uint16(pos)); header["mod_time"] = std::to_string(read_uint16(pos)); header["mod_date"] = std::to_string(read_uint16(pos)); header["crc32"] = std::to_string(read_uint32(pos)); header["comp_size"] = std::to_string(read_uint32(pos)); header["uncomp_size"] = std::to_string(read_uint32(pos)); uint16_t name_len = read_uint16(pos); uint16_t extra_len = read_uint16(pos); uint16_t cmt_len = read_uint16(pos); header["disk_start"] = std::to_string(read_uint16(pos)); header["int_attrs"] = std::to_string(read_uint16(pos)); header["ext_attrs"] = std::to_string(read_uint32(pos)); header["local_offset"] = std::to_string(read_uint32(pos)); header["name"] = read_string(pos, name_len); pos += extra_len; header["comment"] = read_string(pos, cmt_len); cd_headers.push_back(header); } } void print_properties() { std::cout << ".OSZ Properties:" << std::endl; for (const auto& [key, val] : properties) { std::cout << key << ":" << std::endl; for (const auto& [k, v] : val) { std::cout << " - " << k << ": " << v << std::endl; } } for (size_t i = 0; i < cd_headers.size(); ++i) { std::cout << "CD Header " << i << ":" << std::endl; for (const auto& [k, v] : cd_headers[i]) { std::cout << " - " << k << ": " << v << std::endl; } } } void write(const std::string& new_filepath, const std::string& new_comment) { // Simple copy and modify; for full ZIP write, use libzip or similar std::ofstream out(new_filepath, std::ios::binary); out.write(reinterpret_cast(buffer.data()), buffer.size()); // To change comment, locate EOCD and overwrite // Omitted detailed impl for brevity } }; // Example usage // int main() { // OSZHandler handler("example.osz"); // handler.print_properties(); // handler.write("modified.osz", "Modified"); // return 0; // } // ===== end task-491 .OSZ ===== // ===== task-492 .OTB [C] ===== #include #include #include typedef struct { unsigned char infofield; unsigned char width; unsigned char height; unsigned char colours; unsigned char *pixel_data; size_t data_length; } OTBFile; void otb_read(OTBFile *otb, const char *filepath) { FILE *f = fopen(filepath, "rb"); if (!f) { perror("File opening failed"); return; } fseek(f, 0, SEEK_END); long length = ftell(f); fseek(f, 0, SEEK_SET); unsigned char *data = malloc(length); fread(data, 1, length, f); fclose(f); otb->infofield = data[0]; otb->width = data[1]; otb->height = data[2]; otb->colours = data[3]; otb->data_length = (size_t)ceil((otb->width * otb->height) / 8.0); otb->pixel_data = malloc(otb->data_length); memcpy(otb->pixel_data, data + 4, otb->data_length); free(data); otb_print(otb); } void otb_write(const OTBFile *otb, const char *filepath) { FILE *f = fopen(filepath, "wb"); if (!f) { perror("File opening failed"); return; } fwrite(&otb->infofield, 1, 1, f); fwrite(&otb->width, 1, 1, f); fwrite(&otb->height, 1, 1, f); fwrite(&otb->colours, 1, 1, f); fwrite(otb->pixel_data, 1, otb->data_length, f); fclose(f); } void otb_print(const OTBFile *otb) { printf("Infofield: 0x%02x\n", otb->infofield); printf("Width: %u\n", otb->width); printf("Height: %u\n", otb->height); printf("Number of colours: 0x%02x\n", otb->colours); printf("Pixel data (hex): "); for (size_t i = 0; i < otb->data_length; i++) { printf("%02x ", otb->pixel_data[i]); } printf("\n"); } void otb_free(OTBFile *otb) { free(otb->pixel_data); } // Example usage // int main() { // OTBFile otb = {.infofield = 0x00, .colours = 0x01}; // otb_read(&otb, "sample.otb"); // otb_write(&otb, "output.otb"); // otb_free(&otb); // return 0; // } // ===== end task-492 .OTB ===== // ===== task-493 .OTF [C++] ===== #include #include #include #include #include #include class OTFHandler { private: std::string filePath; std::vector data; uint32_t sfntVersion; uint16_t numTables; uint16_t searchRange; uint16_t entrySelector; uint16_t rangeShift; struct TableRecord { std::string tag; uint32_t checksum; uint32_t offset; uint32_t length; }; std::vector tableRecords; uint32_t readUint32(size_t pos) const { return (static_cast(data[pos]) << 24) | (static_cast(data[pos + 1]) << 16) | (static_cast(data[pos + 2]) << 8) | static_cast(data[pos + 3]); } uint16_t readUint16(size_t pos) const { return (static_cast(data[pos]) << 8) | static_cast(data[pos + 1]); } public: OTFHandler(const std::string& filePath) : filePath(filePath) {} void read() { std::ifstream file(filePath, std::ios::binary | std::ios::ate); if (!file) { throw std::runtime_error("Cannot open file"); } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); if (!file.read(data.data(), size)) { throw std::runtime_error("Error reading file"); } if (data.size() < 12) { throw std::runtime_error("Invalid OTF file: too short"); } sfntVersion = readUint32(0); numTables = readUint16(4); searchRange = readUint16(6); entrySelector = readUint16(8); rangeShift = readUint16(10); size_t offset = 12; tableRecords.reserve(numTables); for (uint16_t i = 0; i < numTables; ++i) { if (offset + 16 > data.size()) { throw std::runtime_error("Invalid OTF file: incomplete table record"); } std::string tag(data.begin() + offset, data.begin() + offset + 4); uint32_t checksum = readUint32(offset + 4); uint32_t tableOffset = readUint32(offset + 8); uint32_t length = readUint32(offset + 12); tableRecords.push_back({tag, checksum, tableOffset, length}); offset += 16; } } void printProperties() const { std::cout << "OTF Properties:" << std::endl; std::cout << "sfntVersion: 0x" << std::hex << std::setw(8) << std::setfill('0') << sfntVersion << std::dec << std::endl; std::cout << "numTables: " << numTables << std::endl; std::cout << "searchRange: " << searchRange << std::endl; std::cout << "entrySelector: " << entrySelector << std::endl; std::cout << "rangeShift: " << rangeShift << std::endl; std::cout << "\nTable Records:" << std::endl; for (size_t i = 0; i < tableRecords.size(); ++i) { const auto& record = tableRecords[i]; std::cout << "- Table " << (i + 1) << ":" << std::endl; std::cout << " tableTag: '" << record.tag << "'" << std::endl; std::cout << " checksum: 0x" << std::hex << std::setw(8) << std::setfill('0') << record.checksum << std::dec << std::endl; std::cout << " offset: " << record.offset << std::endl; std::cout << " length: " << record.length << std::endl; } } void write(const std::string& outputPath) const { if (data.empty()) { throw std::runtime_error("No data to write; call read() first"); } std::ofstream outFile(outputPath, std::ios::binary); if (!outFile) { throw std::runtime_error("Cannot open output file"); } outFile.write(data.data(), data.size()); } }; // Example usage: // int main() { // try { // OTFHandler handler("example.otf"); // handler.read(); // handler.printProperties(); // handler.write("output.otf"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-493 .OTF ===== // ===== task-494 .OTG [C++] ===== #include #include #include #include #include #include #include #include class OTGFile { private: std::string filepath; std::map properties; zip_t *zip; public: OTGFile(const std::string& fp) : filepath(fp), zip(nullptr) { int err = 0; zip = zip_open(filepath.c_str(), ZIP_RDONLY, &err); if (!zip) { std::cerr << "Error opening zip: " << err << std::endl; return; } readProperties(); } ~OTGFile() { if (zip) zip_close(zip); } void readProperties() { // File Signature std::ifstream file(filepath, std::ios::binary); char sig[4]; file.read(sig, 4); if (sig[0] == 'P' && sig[1] == 'K' && sig[2] == 3 && sig[3] == 4) { properties["File Signature"] = "PK\\003\\004 (ZIP)"; } else { properties["File Signature"] = "Invalid"; } file.close(); // MIME Type auto mime = readZipFile("mimetype"); properties["MIME Type"] = mime.empty() ? "N/A" : mime; // Parse meta.xml auto metaXml = readZipFile("meta.xml"); if (!metaXml.empty()) { xmlDocPtr doc = xmlReadMemory(metaXml.data(), metaXml.size(), nullptr, nullptr, 0); if (doc) { xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc); if (xpathCtx) { xmlXPathObjectPtr xpathObj; // Register namespaces xmlXPathRegisterNs(xpathCtx, BAD_CAST "meta", BAD_CAST "urn:oasis:names:tc:opendocument:xmlns:meta:1.0"); xmlXPathRegisterNs(xpathCtx, BAD_CAST "dc", BAD_CAST "http://purl.org/dc/elements/1.1/"); xmlXPathRegisterNs(xpathCtx, BAD_CAST "office", BAD_CAST "urn:oasis:names:tc:opendocument:xmlns:office:1.0"); xmlXPathRegisterNs(xpathCtx, BAD_CAST "xlink", BAD_CAST "http://www.w3.org/1999/xlink"); auto getText = [&](const char* path) -> std::string { xpathObj = xmlXPathEvalExpression(BAD_CAST path, xpathCtx); if (xpathObj && xpathObj->nodesetval && xpathObj->nodesetval->nodeNr > 0) { auto node = xpathObj->nodesetval->nodeTab[0]; std::string text = (char*)xmlNodeGetContent(node); xmlXPathFreeObject(xpathObj); return text; } xmlXPathFreeObject(xpathObj); return "N/A"; }; properties["Generator"] = getText("//meta:generator"); properties["Title"] = getText("//dc:title"); properties["Description"] = getText("//dc:description"); properties["Subject"] = getText("//dc:subject"); properties["Keywords"] = getText("//meta:keyword"); properties["Initial Creator"] = getText("//meta:initial-creator"); properties["Creator"] = getText("//dc:creator"); properties["Printed By"] = getText("//meta:printed-by"); properties["Creation Date and Time"] = getText("//meta:creation-date"); properties["Modification Date and Time"] = getText("//dc:date"); properties["Print Date and Time"] = getText("//meta:print-date"); properties["Language"] = getText("//dc:language"); properties["Editing Cycles"] = getText("//meta:editing-cycles"); properties["Editing Duration"] = getText("//meta:editing-duration"); xpathObj = xmlXPathEvalExpression(BAD_CAST "//meta:template", xpathCtx); if (xpathObj && xpathObj->nodesetval && xpathObj->nodesetval->nodeNr > 0) { auto node = xpathObj->nodesetval->nodeTab[0]; properties["Document Template"] = (char*)xmlGetProp(node, BAD_CAST "xlink:href"); } else { properties["Document Template"] = "N/A"; } xmlXPathFreeObject(xpathObj); xpathObj = xmlXPathEvalExpression(BAD_CAST "//meta:auto-reload", xpathCtx); if (xpathObj && xpathObj->nodesetval && xpathObj->nodesetval->nodeNr > 0) { auto node = xpathObj->nodesetval->nodeTab[0]; properties["Automatic Reload"] = (char*)xmlGetProp(node, BAD_CAST "meta:delay"); } else { properties["Automatic Reload"] = "N/A"; } xmlXPathFreeObject(xpathObj); xpathObj = xmlXPathEvalExpression(BAD_CAST "//meta:hyperlink-behaviour", xpathCtx); if (xpathObj && xpathObj->nodesetval && xpathObj->nodesetval->nodeNr > 0) { auto node = xpathObj->nodesetval->nodeTab[0]; properties["Hyperlink Behavior"] = (char*)xmlGetProp(node, BAD_CAST "office:target-frame-name"); } else { properties["Hyperlink Behavior"] = "N/A"; } xmlXPathFreeObject(xpathObj); xpathObj = xmlXPathEvalExpression(BAD_CAST "//meta:document-statistic", xpathCtx); if (xpathObj && xpathObj->nodesetval && xpathObj->nodesetval->nodeNr > 0) { auto node = xpathObj->nodesetval->nodeTab[0]; std::string pages = (char*)xmlGetProp(node, BAD_CAST "meta:page-count"); std::string objects = (char*)xmlGetProp(node, BAD_CAST "meta:object-count"); properties["Document Statistics"] = "Pages: " + (pages.empty() ? "0" : pages) + ", Objects: " + (objects.empty() ? "0" : objects); } else { properties["Document Statistics"] = "N/A"; } xmlXPathFreeObject(xpathObj); xmlXPathFreeContext(xpathCtx); } xmlFreeDoc(doc); } } // Office Version and Drawing Objects Count from content.xml auto contentXml = readZipFile("content.xml"); if (!contentXml.empty()) { xmlDocPtr doc = xmlReadMemory(contentXml.data(), contentXml.size(), nullptr, nullptr, 0); if (doc) { xmlChar* version = xmlGetProp(doc->children, BAD_CAST "office:version"); properties["Office Version"] = version ? (char*)version : "N/A"; xmlFree(version); xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc); xmlXPathRegisterNs(xpathCtx, BAD_CAST "draw", BAD_CAST "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"); auto xpathObj = xmlXPathEvalExpression(BAD_CAST "//draw:*", xpathCtx); properties["Drawing Objects Count"] = std::to_string(xpathObj->nodesetval ? xpathObj->nodesetval->nodeNr : 0); xmlXPathFreeObject(xpathObj); xmlXPathFreeContext(xpathCtx); xmlFreeDoc(doc); } } // Styles Count from styles.xml auto stylesXml = readZipFile("styles.xml"); if (!stylesXml.empty()) { xmlDocPtr doc = xmlReadMemory(stylesXml.data(), stylesXml.size(), nullptr, nullptr, 0); if (doc) { xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc); xmlXPathRegisterNs(xpathCtx, BAD_CAST "style", BAD_CAST "urn:oasis:names:tc:opendocument:xmlns:style:1.0"); auto xpathObj = xmlXPathEvalExpression(BAD_CAST "//style:style", xpathCtx); properties["Styles Count"] = std::to_string(xpathObj->nodesetval ? xpathObj->nodesetval->nodeNr : 0); xmlXPathFreeObject(xpathObj); xmlXPathFreeContext(xpathCtx); xmlFreeDoc(doc); } } // Encryption and Files List from manifest.xml auto manifestXml = readZipFile("META-INF/manifest.xml"); if (!manifestXml.empty()) { xmlDocPtr doc = xmlReadMemory(manifestXml.data(), manifestXml.size(), nullptr, nullptr, 0); if (doc) { xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc); xmlXPathRegisterNs(xpathCtx, BAD_CAST "manifest", BAD_CAST "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"); auto xpathObj = xmlXPathEvalExpression(BAD_CAST "//manifest:start-key-generation-name", xpathCtx); properties["Encryption Status"] = (xpathObj->nodesetval && xpathObj->nodesetval->nodeNr > 0) ? "Yes" : "No"; xmlXPathFreeObject(xpathObj); xpathObj = xmlXPathEvalExpression(BAD_CAST "//manifest:file-entry", xpathCtx); std::string files; if (xpathObj->nodesetval) { for (int i = 0; i < xpathObj->nodesetval->nodeNr; ++i) { auto node = xpathObj->nodesetval->nodeTab[i]; xmlChar* path = xmlGetProp(node, BAD_CAST "manifest:full-path"); if (path) { files += (char*)path + std::string(", "); xmlFree(path); } } } if (!files.empty()) files = files.substr(0, files.length() - 2); properties["Package Files List"] = files; xmlXPathFreeObject(xpathObj); xmlXPathFreeContext(xpathCtx); xmlFreeDoc(doc); } } } std::string readZipFile(const std::string& name) { zip_file_t *zf = zip_fopen(zip, name.c_str(), 0); if (!zf) return ""; std::string content; char buf[1024]; zip_int64_t len; while ((len = zip_fread(zf, buf, sizeof(buf))) > 0) { content.append(buf, len); } zip_fclose(zf); return content; } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& newFilepath, const std::string& newTitle = "") { zip_t *newZip = zip_open(newFilepath.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); if (!newZip) { std::cerr << "Error creating new zip" << std::endl; return; } zip_stat_t stat; zip_int64_t num = zip_get_num_entries(zip, 0); for (zip_int64_t i = 0; i < num; ++i) { zip_stat_index(zip, i, 0, &stat); std::string name(stat.name); auto content = readZipFile(name); if (name == "meta.xml" && !newTitle.empty()) { xmlDocPtr doc = xmlReadMemory(content.data(), content.size(), nullptr, nullptr, 0); if (doc) { xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc); xmlXPathRegisterNs(xpathCtx, BAD_CAST "dc", BAD_CAST "http://purl.org/dc/elements/1.1/"); auto xpathObj = xmlXPathEvalExpression(BAD_CAST "//dc:title", xpathCtx); if (xpathObj->nodesetval && xpathObj->nodesetval->nodeNr > 0) { xmlNodeSetContent(xpathObj->nodesetval->nodeTab[0], BAD_CAST newTitle.c_str()); } xmlXPathFreeObject(xpathObj); xmlXPathFreeContext(xpathCtx); xmlChar *mem; int size; xmlDocDumpMemoryEnc(doc, &mem, &size, "UTF-8"); content = std::string((char*)mem, size); xmlFree(mem); xmlFreeDoc(doc); } } zip_source_t *source = zip_source_buffer(newZip, content.data(), content.size(), 0); if (source) { zip_file_add(newZip, name.c_str(), source, ZIP_FL_OVERWRITE | ZIP_FL_ENC_UTF_8); } else { zip_source_free(source); } } zip_close(newZip); std::cout << "File written to " << newFilepath << std::endl; } }; // Example usage: // int main() { // OTGFile otg("example.otg"); // otg.printProperties(); // otg.write("modified.otg", "New Title"); // return 0; // } // ===== end task-494 .OTG ===== // ===== task-495 .OTL [C] ===== #include #include #include typedef struct Node { int level; char *type; char *content; struct Node **children; int children_count; } Node; Node* create_node(int level, const char* type, const char* content) { Node* node = (Node*)malloc(sizeof(Node)); node->level = level; node->type = strdup(type); node->content = strdup(content); node->children = NULL; node->children_count = 0; return node; } void add_child(Node* parent, Node* child) { parent->children = (Node**)realloc(parent->children, (parent->children_count + 1) * sizeof(Node*)); parent->children[parent->children_count++] = child; } void free_tree(Node** tree, int size) { for (int i = 0; i < size; i++) { free(tree[i]->type); free(tree[i]->content); if (tree[i]->children_count > 0) { free_tree(tree[i]->children, tree[i]->children_count); } free(tree[i]->children); free(tree[i]); } free(tree); } Node** parse_otl(const char* content, int* tree_size) { *tree_size = 0; char* content_copy = strdup(content); char* line = strtok(content_copy, "\n"); Node* root = create_node(-1, "root", ""); Node** stack = (Node**)malloc(100 * sizeof(Node*)); // Arbitrary max depth int stack_size = 1; stack[0] = root; while (line) { if (strlen(line) == 0 || strspn(line, " \t") == strlen(line)) { line = strtok(NULL, "\n"); continue; } int level = 0; while (line[level] == '\t') level++; char* trimmed = line + level; char* type = "headline"; char* node_content = trimmed; char temp[1024]; if (strncmp(trimmed, ": ", 2) == 0) { type = "body"; node_content = trimmed + 2; } else if (strstr(trimmed, " _exe_ ")) { type = "executable"; } strcpy(temp, node_content); Node* node = create_node(level, type, temp); while (stack[stack_size - 1]->level >= level) stack_size--; add_child(stack[stack_size - 1], node); stack[stack_size++] = node; line = strtok(NULL, "\n"); } free(content_copy); free(stack); *tree_size = root->children_count; Node** tree = root->children; free(root->type); free(root->content); free(root); return tree; } void print_properties(Node** nodes, int size, const char* indent) { for (int i = 0; i < size; i++) { Node* node = nodes[i]; printf("%sLevel: %d\n", indent, node->level); printf("%sType: %s\n", indent, node->type); printf("%sContent: %s\n", indent, node->content); printf("%sChildren Count: %d\n\n", indent, node->children_count); if (node->children_count > 0) { char new_indent[1024]; snprintf(new_indent, sizeof(new_indent), "%s ", indent); print_properties(node->children, node->children_count, new_indent); } } } void write_otl(FILE* fp, Node** nodes, int size, int level) { for (int i = 0; i < size; i++) { Node* node = nodes[i]; for (int j = 0; j < level; j++) fprintf(fp, "\t"); if (strcmp(node->type, "body") == 0) { fprintf(fp, ": %s\n", node->content); } else if (strcmp(node->type, "executable") == 0) { fprintf(fp, "%s\n", node->content); } else { fprintf(fp, "%s\n", node->content); } if (node->children_count > 0) { write_otl(fp, node->children, node->children_count, level + 1); } } } char* read_file(const char* filepath) { FILE* fp = fopen(filepath, "r"); if (!fp) return NULL; fseek(fp, 0, SEEK_END); long size = ftell(fp); fseek(fp, 0, SEEK_SET); char* content = (char*)malloc(size + 1); fread(content, 1, size, fp); content[size] = '\0'; fclose(fp); return content; } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s [output.otl]\n", argv[0]); return 1; } char* content = read_file(argv[1]); if (!content) { printf("Failed to read file.\n"); return 1; } int tree_size; Node** tree = parse_otl(content, &tree_size); free(content); print_properties(tree, tree_size, ""); if (argc > 2) { FILE* out_fp = fopen(argv[2], "w"); if (out_fp) { write_otl(out_fp, tree, tree_size, 0); fclose(out_fp); } } free_tree(tree, tree_size); return 0; } // ===== end task-495 .OTL ===== // ===== task-496 .OTP [C++] ===== #include #include #include #include #include #include class OTPFile { private: std::string filepath; zip_t* zip; std::map properties; // Simple properties std::vector> manifestFiles; void decodeProperties() { int err = 0; zip = zip_open(filepath.c_str(), ZIP_RDONLY, &err); if (zip == nullptr) { std::cerr << "Error opening ZIP" << std::endl; return; } // MIME type zip_file_t* mimeFile = zip_fopen(zip, "mimetype", 0); if (mimeFile) { char buf[100]; zip_int64_t len = zip_fread(mimeFile, buf, 99); buf[len] = '\0'; properties["MIME Type"] = std::string(buf); zip_fclose(mimeFile); } // Manifest zip_file_t* manifestFile = zip_fopen(zip, "META-INF/manifest.xml", 0); if (manifestFile) { zip_stat_t stat; zip_stat(zip, "META-INF/manifest.xml", 0, &stat); char* xml = new char[stat.size + 1]; zip_fread(manifestFile, xml, stat.size); xml[stat.size] = '\0'; zip_fclose(manifestFile); tinyxml2::XMLDocument doc; doc.Parse(xml); tinyxml2::XMLElement* manifest = doc.FirstChildElement("manifest:manifest"); if (manifest) { properties["Manifest Version"] = manifest->Attribute("manifest:version"); tinyxml2::XMLElement* entry = manifest->FirstChildElement("manifest:file-entry"); while (entry) { std::map fileInfo; fileInfo["path"] = entry->Attribute("manifest:full-path"); fileInfo["media_type"] = entry->Attribute("manifest:media-type"); manifestFiles.push_back(fileInfo); if (fileInfo["path"] == "/") { properties["Document MIME Type"] = fileInfo["media_type"]; properties["Document Version"] = entry->Attribute("manifest:version") ? entry->Attribute("manifest:version") : "N/A"; } if (entry->FirstChildElement("manifest:encryption-data")) { properties["Encrypted"] = "Yes"; } entry = entry->NextSiblingElement("manifest:file-entry"); } if (properties.find("Encrypted") == properties.end()) { properties["Encrypted"] = "No"; } } delete[] xml; } // Thumbnail properties["Thumbnail Present"] = (zip_name_locate(zip, "Thumbnails/thumbnail.png", 0) >= 0) ? "Yes" : "No"; // Meta zip_file_t* metaFile = zip_fopen(zip, "meta.xml", 0); if (metaFile) { zip_stat_t stat; zip_stat(zip, "meta.xml", 0, &stat); char* xml = new char[stat.size + 1]; zip_fread(metaFile, xml, stat.size); xml[stat.size] = '\0'; zip_fclose(metaFile); tinyxml2::XMLDocument doc; doc.Parse(xml); tinyxml2::XMLElement* title = doc.FirstChildElement("office:document-meta")->FirstChildElement("office:meta")->FirstChildElement("dc:title"); properties["Title"] = title ? title->GetText() : "N/A"; tinyxml2::XMLElement* creator = doc.FirstChildElement("office:document-meta")->FirstChildElement("office:meta")->FirstChildElement("dc:creator"); properties["Creator"] = creator ? creator->GetText() : "N/A"; tinyxml2::XMLElement* creationDate = doc.FirstChildElement("office:document-meta")->FirstChildElement("office:meta")->FirstChildElement("meta:creation-date"); properties["Creation Date"] = creationDate ? creationDate->GetText() : "N/A"; delete[] xml; } // Content - Number of pages zip_file_t* contentFile = zip_fopen(zip, "content.xml", 0); if (contentFile) { zip_stat_t stat; zip_stat(zip, "content.xml", 0, &stat); char* xml = new char[stat.size + 1]; zip_fread(contentFile, xml, stat.size); xml[stat.size] = '\0'; zip_fclose(contentFile); tinyxml2::XMLDocument doc; doc.Parse(xml); int count = 0; tinyxml2::XMLElement* page = doc.FirstChildElement("office:document-content")->FirstChildElement("office:body")->FirstChildElement("office:presentation")->FirstChildElement("draw:page"); while (page) { count++; page = page->NextSiblingElement("draw:page"); } properties["Number of Presentation Pages"] = std::to_string(count); delete[] xml; } // Signatures bool signed = false; int num = zip_get_num_entries(zip, 0); for (int i = 0; i < num; i++) { const char* name = zip_get_name(zip, i, 0); if (std::string(name).find("META-INF/") == 0 && std::string(name).find("signatures") != std::string::npos) { signed = true; break; } } properties["Signed"] = signed ? "Yes" : "No"; } public: OTPFile(const std::string& fp) : filepath(fp) { decodeProperties(); } ~OTPFile() { if (zip) zip_close(zip); } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } std::cout << "Files in Manifest:" << std::endl; for (const auto& file : manifestFiles) { std::cout << " - " << file.at("path") << " (" << file.at("media_type") << ")" << std::endl; } } void write(const std::string& newFilepath) { // Simple copy for write zip_t* newZip = zip_open(newFilepath.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); if (newZip) { int num = zip_get_num_entries(zip, 0); for (int i = 0; i < num; i++) { const char* name = zip_get_name(zip, i, 0); zip_file_t* f = zip_fopen_index(zip, i, 0); zip_stat_t stat; zip_stat_index(zip, i, 0, &stat); char* buf = new char[stat.size]; zip_fread(f, buf, stat.size); zip_file_add(newZip, name, zip_buffer_create(buf, stat.size), ZIP_FL_ENC_UTF_8); zip_fclose(f); } zip_close(newZip); } } }; // Example usage: // int main() { // OTPFile otp("example.otp"); // otp.printProperties(); // otp.write("modified.otp"); // return 0; // } // ===== end task-496 .OTP ===== // ===== task-497 .OTS [C++] ===== #include #include #include #include #include #include class OtsFile { private: std::string magicHeader; uint64_t version; std::string digestType; std::string digestValue; std::vector operations; std::vector attestations; const unsigned char MAGIC[29] = {0x00, 'O', 'p', 'e', 'n', 'T', 'i', 'm', 'e', 's', 't', 'a', 'm', 'p', 's', 0x00, 0x00, 'P', 'r', 'o', 'o', 'f', 0x00, 0xbf, 0x89, 0xe2, 0xe8, 0x84, 0xe8, 0x92, 0x94}; public: OtsFile(const std::string& filename = "") { if (!filename.empty()) open(filename); } uint64_t readVarint(std::istream& stream) { uint64_t value = 0; int shift = 0; unsigned char byte; while (true) { stream.read((char*)&byte, 1); value |= static_cast(byte & 0x7f) << shift; shift += 7; if ((byte & 0x80) == 0) break; } return value; } std::string hexString(const unsigned char* data, size_t len) { std::stringstream ss; ss << std::hex << std::setfill('0'); for (size_t i = 0; i < len; ++i) { ss << std::setw(2) << static_cast(data[i]); } return ss.str(); } std::string getDigestType(unsigned char tag) { if (tag == 0x02) return "SHA1"; if (tag == 0x03) return "RIPEMD160"; if (tag == 0x05) return "HASH160"; if (tag == 0x08) return "SHA256"; return "unknown"; } size_t getDigestLength(unsigned char tag) { if (tag == 0x02 || tag == 0x03 || tag == 0x05) return 20; if (tag == 0x08) return 32; return 32; } void open(const std::string& filename) { std::ifstream file(filename, std::ios::binary); if (!file) throw std::runtime_error("Cannot open file"); file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read((char*)data.data(), size); decode(data.data(), size); } void decode(const unsigned char* data, size_t size) { size_t offset = 0; unsigned char magic[29]; memcpy(magic, data + offset, 29); offset += 29; magicHeader = hexString(magic, 29); if (memcmp(magic, MAGIC, 29) != 0) { throw std::runtime_error("Invalid magic header"); } std::istringstream stream(std::string((char*)data + offset, size - offset)); version = readVarint(stream); offset = stream.tellg() + 29; // Adjust offset unsigned char digestTag; stream.read((char*)&digestTag, 1); digestType = getDigestType(digestTag); size_t digestLen = getDigestLength(digestTag); unsigned char* digest = new unsigned char[digestLen]; stream.read((char*)digest, digestLen); digestValue = hexString(digest, digestLen); delete[] digest; std::vector stack; stack.push_back(digestValue); while (stream.good()) { unsigned char tag; stream.read((char*)&tag, 1); if (stream.eof()) break; if (tag == 0) { if (stack.size() < 2) throw std::runtime_error("Invalid fork"); std::string right = stack.back(); stack.pop_back(); std::string left = stack.back(); stack.pop_back(); stack.push_back("fork(" + left + ", " + right + ")"); operations.push_back("fork"); } else if (tag >= 0xf0) { std::string opName = (tag == 0xf1) ? "append" : (tag == 0xf2) ? "prepend" : "unknown binary"; uint64_t argLen = readVarint(stream); unsigned char* arg = new unsigned char[argLen]; stream.read((char*)arg, argLen); std::string argHex = hexString(arg, argLen); delete[] arg; std::string top = stack.back(); stack.back() = opName + "(" + top + ", " + argHex + ")"; operations.push_back(opName + " " + argHex); } else if (tag == 0x83) { stream.seekg(-1, std::ios::cur); unsigned char attTag[8]; stream.read((char*)attTag, 8); if (hexString(attTag, 8) == "83dfe30d2ef90c8e") { uint64_t urlLen = readVarint(stream); char* url = new char[urlLen]; stream.read(url, urlLen); attestations.push_back("PendingAttestation: " + std::string(url, urlLen)); delete[] url; } else if (hexString(attTag, 8) == "05f50a8285caa978") { uint64_t height = readVarint(stream); attestations.push_back("BitcoinBlockHeaderAttestation: height " + std::to_string(height)); } } else { std::string opName = getDigestType(tag); std::string top = stack.back(); stack.back() = opName + "(" + top + ")"; operations.push_back(opName); } } } void printProperties() { std::cout << "Magic Header: " << magicHeader << std::endl; std::cout << "Version: " << version << std::endl; std::cout << "Digest Type: " << digestType << std::endl; std::cout << "Digest Value: " << digestValue << std::endl; std::cout << "Operations: " << std::endl; for (const auto& op : operations) std::cout << " " << op << std::endl; std::cout << "Attestations: " << std::endl; for (const auto& att : attestations) std::cout << " " << att << std::endl; } void write(const std::string& filename) { std::ofstream file(filename, std::ios::binary); if (!file) throw std::runtime_error("Cannot write file"); // Write magic file.write((char*)MAGIC, 29); // Write version as varint writeVarint(file, version); // Write digest tag unsigned char digestTag = getTagForType(digestType); file.write((char*)&digestTag, 1); // Write digest auto digestBytes = hexToBytes(digestValue); file.write((char*)digestBytes.data(), digestBytes.size()); // Full ops/atts write omitted for brevity } unsigned char getTagForType(const std::string& type) { if (type == "SHA1") return 0x02; if (type == "RIPEMD160") return 0x03; if (type == "HASH160") return 0x05; if (type == "SHA256") return 0x08; return 0x08; } void writeVarint(std::ostream& stream, uint64_t value) { while (value > 0x7f) { unsigned char byte = (value & 0x7f) | 0x80; stream.write((char*)&byte, 1); value >>= 7; } unsigned char byte = value; stream.write((char*)&byte, 1); } std::vector hexToBytes(const std::string& hex) { std::vector bytes; for (size_t i = 0; i < hex.length(); i += 2) { unsigned char byte; std::stringstream ss; ss << std::hex << hex.substr(i, 2); ss >> byte; bytes.push_back(byte); } return bytes; } }; // ===== end task-497 .OTS ===== // ===== task-498 .OTS [C++] ===== #include #include #include #include #include #include #include class OTTFile { private: std::string filepath; std::map properties; // Simplified; use variants for complex types zip_t* zip = nullptr; public: OTTFile(const std::string& fp) : filepath(fp) {} ~OTTFile() { close(); } bool open() { int err = 0; zip = zip_open(filepath.c_str(), 0, &err); if (!zip) return false; decodeProperties(); return true; } void decodeProperties() { // MIME Type zip_file_t* mimeFile = zip_fopen(zip, "mimetype", 0); if (mimeFile) { char buf[100]; zip_ssize_t len = zip_fread(mimeFile, buf, sizeof(buf) - 1); if (len > 0) { buf[len] = '\0'; properties["MIME Type"] = std::string(buf).substr(0, len); } zip_fclose(mimeFile); } // Meta.xml parsing zip_file_t* metaFile = zip_fopen(zip, "meta.xml", 0); if (metaFile) { zip_stat_t sb; zip_stat(zip, "meta.xml", 0, &sb); char* buf = new char[sb.size + 1]; zip_ssize_t len = zip_fread(metaFile, buf, sb.size); buf[len] = '\0'; xmlDocPtr doc = xmlReadMemory(buf, len, "meta.xml", NULL, 0); if (doc) { xmlNodePtr root = xmlDocGetRootElement(doc); // ODF Version xmlChar* version = xmlGetNsProp(root, (const xmlChar*)"version", (const xmlChar*)"urn:oasis:names:tc:opendocument:xmlns:office:1.0"); properties["ODF Version"] = version ? (char*)version : "Not specified"; xmlFree(version); // Helper to get text content auto getText = [&](const char* ns, const char* name) -> std::string { xmlNodePtr node = root->children; while (node) { if (node->type == XML_ELEMENT_NODE && xmlStrcmp(node->name, (const xmlChar*)name) == 0 && xmlStrcmp(node->ns->href, (const xmlChar*)ns) == 0) { return (char*)xmlNodeGetContent(node); } node = node->next; } return "Not found"; }; properties["Generator"] = getText("urn:oasis:names:tc:opendocument:xmlns:meta:1.0", "generator"); properties["Initial Creator"] = getText("urn:oasis:names:tc:opendocument:xmlns:meta:1.0", "initial-creator"); properties["Creation Date"] = getText("urn:oasis:names:tc:opendocument:xmlns:meta:1.0", "creation-date"); properties["Creator"] = getText("http://purl.org/dc/elements/1.1/", "creator"); properties["Modification Date"] = getText("http://purl.org/dc/elements/1.1/", "date"); properties["Editing Cycles"] = getText("urn:oasis:names:tc:opendocument:xmlns:meta:1.0", "editing-cycles"); properties["Editing Duration"] = getText("urn:oasis:names:tc:opendocument:xmlns:meta:1.0", "editing-duration"); properties["Printed By"] = getText("urn:oasis:names:tc:opendocument:xmlns:meta:1.0", "printed-by"); properties["Print Date"] = getText("urn:oasis:names:tc:opendocument:xmlns:meta:1.0", "print-date"); properties["Title"] = getText("http://purl.org/dc/elements/1.1/", "title"); properties["Description"] = getText("http://purl.org/dc/elements/1.1/", "description"); properties["Subject"] = getText("http://purl.org/dc/elements/1.1/", "subject"); properties["Language"] = getText("http://purl.org/dc/elements/1.1/", "language"); // Keywords (simplified, collect all) std::string keywords; xmlNodePtr node = root->children; while (node) { if (node->type == XML_ELEMENT_NODE && xmlStrcmp(node->name, (const xmlChar*)"keyword") == 0 && xmlStrcmp(node->ns->href, (const xmlChar*)"urn:oasis:names:tc:opendocument:xmlns:meta:1.0") == 0) { if (!keywords.empty()) keywords += ", "; keywords += (char*)xmlNodeGetContent(node); } node = node->next; } properties["Keywords"] = !keywords.empty() ? keywords : "None"; // Document Statistics (attributes) node = root->children; std::string stats; while (node) { if (node->type == XML_ELEMENT_NODE && xmlStrcmp(node->name, (const xmlChar*)"document-statistic") == 0 && xmlStrcmp(node->ns->href, (const xmlChar*)"urn:oasis:names:tc:opendocument:xmlns:meta:1.0") == 0) { xmlAttrPtr attr = node->properties; while (attr) { if (xmlStrcmp(attr->ns->href, (const xmlChar*)"urn:oasis:names:tc:opendocument:xmlns:meta:1.0") == 0) { std::string name = (char*)attr->name; std::replace(name.begin(), name.end(), '-', ' '); name[0] = std::toupper(name[0]); stats += name + " Count: " + (char*)xmlNodeGetContent(attr->children) + "\n"; } attr = attr->next; } } node = node->next; } properties["Document Statistics"] = !stats.empty() ? stats : "Not found"; // User-Defined Metadata std::string userDefined; node = root->children; while (node) { if (node->type == XML_ELEMENT_NODE && xmlStrcmp(node->name, (const xmlChar*)"user-defined") == 0 && xmlStrcmp(node->ns->href, (const xmlChar*)"urn:oasis:names:tc:opendocument:xmlns:meta:1.0") == 0) { xmlChar* name = xmlGetNsProp(node, (const xmlChar*)"name", (const xmlChar*)"urn:oasis:names:tc:opendocument:xmlns:meta:1.0"); xmlChar* vtype = xmlGetNsProp(node, (const xmlChar*)"value-type", (const xmlChar*)"urn:oasis:names:tc:opendocument:xmlns:meta:1.0"); std::string value = (char*)xmlNodeGetContent(node); userDefined += (char*)name + ": " + value + " (Type: " + (vtype ? (char*)vtype : "string") + ")\n"; xmlFree(name); xmlFree(vtype); } node = node->next; } properties["User-Defined Metadata"] = !userDefined.empty() ? userDefined : "None"; xmlFreeDoc(doc); } delete[] buf; zip_fclose(metaFile); } } void printProperties() { for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } void writeProperty(const std::string& key, const std::string& value) { properties[key] = value; // Full write requires updating XML and re-zipping } void save(const std::string& newFilepath) { // Placeholder: Implement by creating new zip, copying files, updating meta.xml std::cout << "Save not fully implemented." << std::endl; } void close() { if (zip) zip_close(zip); zip = nullptr; } }; // Usage example: // int main() { // OTTFile ott("example.ott"); // if (ott.open()) { // ott.printProperties(); // ott.writeProperty("Title", "New Title"); // ott.save("new.ott"); // } // return 0; // } // ===== end task-498 .OTS ===== // ===== task-499 .OV2 [C] ===== #include #include #include #include typedef struct { uint8_t type; int32_t length; // for type 0,2,3 double lon; double lat; char** strings; // array of strings int num_strings; int32_t block_length; // for type 1 double ne_lon; double ne_lat; double sw_lon; double sw_lat; } OV2Record; typedef struct { char* filepath; OV2Record* records; int num_records; } OV2Handler; OV2Handler* ov2_create(const char* filepath) { OV2Handler* handler = malloc(sizeof(OV2Handler)); handler->filepath = strdup(filepath); handler->records = NULL; handler->num_records = 0; if (filepath) { ov2_read(handler); } return handler; } void ov2_read(OV2Handler* handler) { FILE* f = fopen(handler->filepath, "rb"); if (!f) return; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); int offset = 0; while (offset < size) { uint8_t type = data[offset]; offset += 1; handler->records = realloc(handler->records, (handler->num_records + 1) * sizeof(OV2Record)); OV2Record* rec = &handler->records[handler->num_records]; memset(rec, 0, sizeof(OV2Record)); rec->type = type; if (type == 1) { memcpy(&rec->block_length, data + offset, 4); offset += 4; int32_t ne_lon_int; memcpy(&ne_lon_int, data + offset, 4); rec->ne_lon = ne_lon_int / 100000.0; offset += 4; int32_t ne_lat_int; memcpy(&ne_lat_int, data + offset, 4); rec->ne_lat = ne_lat_int / 100000.0; offset += 4; int32_t sw_lon_int; memcpy(&sw_lon_int, data + offset, 4); rec->sw_lon = sw_lon_int / 100000.0; offset += 4; int32_t sw_lat_int; memcpy(&sw_lat_int, data + offset, 4); rec->sw_lat = sw_lat_int / 100000.0; offset += 4; } else if (type == 0 || type == 2 || type == 3) { memcpy(&rec->length, data + offset, 4); offset += 4; int32_t lon_int; memcpy(&lon_int, data + offset, 4); rec->lon = lon_int / 100000.0; offset += 4; int32_t lat_int; memcpy(&lat_int, data + offset, 4); rec->lat = lat_int / 100000.0; offset += 4; int str_offset = offset; rec->num_strings = 0; rec->strings = NULL; while (str_offset < offset + (rec->length - 13)) { int str_start = str_offset; while (str_offset < size && data[str_offset] != 0) str_offset += 1; int str_len = str_offset - str_start; rec->strings = realloc(rec->strings, (rec->num_strings + 1) * sizeof(char*)); rec->strings[rec->num_strings] = malloc(str_len + 1); memcpy(rec->strings[rec->num_strings], data + str_start, str_len); rec->strings[rec->num_strings][str_len] = '\0'; rec->num_strings += 1; str_offset += 1; } offset += rec->length - 13; } else { break; } handler->num_records += 1; } free(data); } void ov2_print_properties(OV2Handler* handler) { for (int i = 0; i < handler->num_records; i++) { OV2Record rec = handler->records[i]; printf("Type: %d\n", rec.type); if (rec.type == 1) { printf("Block Length: %d\n", rec.block_length); printf("NE Longitude: %f\n", rec.ne_lon); printf("NE Latitude: %f\n", rec.ne_lat); printf("SW Longitude: %f\n", rec.sw_lon); printf("SW Latitude: %f\n", rec.sw_lat); } else { printf("Length: %d\n", rec.length); printf("Longitude: %f\n", rec.lon); printf("Latitude: %f\n", rec.lat); printf("Strings: "); for (int j = 0; j < rec.num_strings; j++) { printf("%s ", rec.strings[j]); } printf("\n"); } printf("---\n"); } } void ov2_write(OV2Handler* handler, const char* filepath) { FILE* f = fopen(filepath ? filepath : handler->filepath, "wb"); if (!f) return; for (int i = 0; i < handler->num_records; i++) { OV2Record rec = handler->records[i]; fwrite(&rec.type, 1, 1, f); if (rec.type == 1) { fwrite(&rec.block_length, 4, 1, f); int32_t ne_lon_int = (int32_t)(rec.ne_lon * 100000); fwrite(&ne_lon_int, 4, 1, f); int32_t ne_lat_int = (int32_t)(rec.ne_lat * 100000); fwrite(&ne_lat_int, 4, 1, f); int32_t sw_lon_int = (int32_t)(rec.sw_lon * 100000); fwrite(&sw_lon_int, 4, 1, f); int32_t sw_lat_int = (int32_t)(rec.sw_lat * 100000); fwrite(&sw_lat_int, 4, 1, f); } else { int32_t length = rec.length; fwrite(&length, 4, 1, f); int32_t lon_int = (int32_t)(rec.lon * 100000); fwrite(&lon_int, 4, 1, f); int32_t lat_int = (int32_t)(rec.lat * 100000); fwrite(&lat_int, 4, 1, f); for (int j = 0; j < rec.num_strings; j++) { fwrite(rec.strings[j], strlen(rec.strings[j]), 1, f); uint8_t null_byte = 0; fwrite(&null_byte, 1, 1, f); } } } fclose(f); } void ov2_destroy(OV2Handler* handler) { for (int i = 0; i < handler->num_records; i++) { for (int j = 0; j < handler->records[i].num_strings; j++) { free(handler->records[i].strings[j]); } free(handler->records[i].strings); } free(handler->records); free(handler->filepath); free(handler); } // ===== end task-499 .OV2 ===== // ===== task-500 .OWL [C++] ===== #include #include #include #include "tinyxml2.h" // Assume tinyxml2 library is linked using namespace tinyxml2; class OwlFileHandler { private: std::string filepath; XMLDocument doc; public: OwlFileHandler(const std::string& fp) : filepath(fp) { parseOwl(); } void parseOwl() { doc.LoadFile(filepath.c_str()); } void printProperties() { std::cout << "OWL Properties Dump:" << std::endl; // Namespaces (simulated) XMLElement* ontology = doc.FirstChildElement("rdf:RDF")->FirstChildElement("owl:Ontology"); // Ontology IRI and Version IRI std::cout << "Ontology IRI: " << (ontology ? ontology->Attribute("rdf:about") : "N/A") << std::endl; std::cout << "Version IRI: " << (ontology ? ontology->Attribute("owl:versionIRI") : "N/A") << std::endl; // Imports std::string imports; for (XMLElement* imp = ontology ? ontology->FirstChildElement("owl:imports") : nullptr; imp; imp = imp->NextSiblingElement("owl:imports")) { if (!imports.empty()) imports += ", "; imports += imp->GetText(); } std::cout << "Imports: " << (imports.empty() ? "None" : imports) << std::endl; // Annotations (example for label/comment) std::string annotations; for (XMLElement* ann = doc.FirstChildElement("rdf:RDF")->FirstChildElement(); ann; ann = ann->NextSiblingElement()) { XMLElement* label = ann->FirstChildElement("rdfs:label"); if (label) { if (!annotations.empty()) annotations += "\n"; annotations += "rdfs:label: " + std::string(label->GetText()); } XMLElement* comment = ann->FirstChildElement("rdfs:comment"); if (comment) { if (!annotations.empty()) annotations += "\n"; annotations += "rdfs:comment: " + std::string(comment->GetText()); } } std::cout << "Annotations: " << (annotations.empty() ? "None" : annotations) << std::endl; // Entities std::string classes; for (XMLElement* cls = doc.FirstChildElement("rdf:RDF")->FirstChildElement("owl:Class"); cls; cls = cls->NextSiblingElement("owl:Class")) { if (!classes.empty()) classes += ", "; classes += cls->Attribute("rdf:about"); } std::cout << "Classes: " << (classes.empty() ? "None" : classes) << std::endl; // Similar for other entities (abbreviated for brevity; add loops for datatypes, props, etc.) // ... // Axioms, Expressions, etc. (add similar loops) // Literals and Anonymous (count) int literals = 0; for (XMLElement* el = doc.FirstChildElement(); el; el = el->NextSiblingElement()) { if (el->Attribute("rdf:datatype")) literals++; } std::cout << "Literals: " << literals << std::endl; // Note: Full implementation would extend loops for all properties. } void writeOwl(const std::string& newFilepath) { doc.SaveFile(newFilepath.c_str()); } }; // Example usage: // int main() { // OwlFileHandler handler("example.owl"); // handler.printProperties(); // handler.writeOwl("modified.owl"); // return 0; // } // ===== end task-500 .OWL ===== // ===== task-501 .OXT [C++] ===== #include #include #include #include // minizip or libzip #include // For XML class OXTHandler { private: std::string filepath; std::map properties; // Simplified; use structs for lists public: OXTHandler(const std::string& fp) : filepath(fp) { decode(); } void decode() { zip_t* za = zip_open(filepath.c_str(), ZIP_RDONLY, nullptr); if (!za) return; // ZIP-level properties["zip_magic"] = "PK\x03\x04"; int num = zip_get_num_entries(za, 0); properties["num_entries"] = std::to_string(num); // description.xml zip_file_t* descFile = zip_fopen(za, "description.xml", 0); if (descFile) { // Read buffer, parse with tinyxml2 char buffer[1024*1024]; // Assume size zip_int64_t len = zip_fread(descFile, buffer, sizeof(buffer)); buffer[len] = '\0'; tinyxml2::XMLDocument doc; doc.Parse(buffer); auto elem = doc.FirstChildElement("description")->FirstChildElement("identifier"); if (elem) properties["identifier"] = elem->Attribute("value"); // Add others similarly zip_fclose(descFile); } // manifest.xml (similar) zip_close(za); } void printProperties() { for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } void write(const std::string& newFilepath, const std::map& modProps) { // Similar to decode, but create new ZIP, rebuild XML strings zip_t* zaOut = zip_open(newFilepath.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); // Add files, with rebuilt XML std::string descXml = buildDescriptionXml(); zip_source_t* src = zip_source_buffer(zaOut, descXml.c_str(), descXml.size(), 0); zip_add(zaOut, "description.xml", src); // Etc. zip_close(zaOut); } std::string buildDescriptionXml() { return ""; } // Similar for manifest }; // Example: // int main() { // OXTHandler handler("example.oxt"); // handler.printProperties(); // handler.write("new.oxt", {{"version", "2.0"}}); // return 0; // } // ===== end task-501 .OXT ===== // ===== task-502 .P [C] ===== #include #include #include #include #include #include #include typedef struct { char *filepath; } PFileHandler; PFileHandler* createPFileHandler(const char *filepath) { if (strstr(filepath, ".p") == NULL && strstr(filepath, ".P") == NULL) { fprintf(stderr, "File must have .p extension\n"); exit(1); } PFileHandler *handler = malloc(sizeof(PFileHandler)); handler->filepath = strdup(filepath); return handler; } void destroyPFileHandler(PFileHandler *handler) { free(handler->filepath); free(handler); } void printProperties(PFileHandler *handler) { struct stat st; if (stat(handler->filepath, &st) != 0) { perror("stat"); return; } printf("Properties of %s\n", handler->filepath); printf("File size: %ld bytes\n", st.st_size); printf("Creation time: %s", ctime(&st.st_ctime)); printf("Modification time: %s", ctime(&st.st_mtime)); printf("Access time: %s", ctime(&st.st_atime)); printf("Permissions: %o\n", st.st_mode & 0777); printf("Owner UID: %d\n", st.st_uid); printf("Group GID: %d\n", st.st_gid); printf("Inode number: %ld\n", st.st_ino); printf("Number of hard links: %ld\n", st.st_nlink); } void writeFile(PFileHandler *handler, const char *content) { if (content == NULL) { content = "(* Sample Pascal code *)\nBEGIN\n Writeln('Hello, World!');\nEND."; } FILE *f = fopen(handler->filepath, "w"); if (f == NULL) { perror("fopen"); return; } fprintf(f, "%s", content); fclose(f); printf("Written to %s\n", handler->filepath); } // Example usage: // int main() { // PFileHandler *handler = createPFileHandler("example.p"); // printProperties(handler); // writeFile(handler, NULL); // destroyPFileHandler(handler); // return 0; // } // ===== end task-502 .P ===== // ===== task-504 .P12 [C++] ===== #include #include #include #include class P12Handler { private: std::string filepath; const char* password; PKCS12* p12; public: P12Handler(const std::string& filepath, const char* password = nullptr) : filepath(filepath), password(password), p12(nullptr) { OpenSSL_add_all_algorithms(); load(); } ~P12Handler() { if (p12) PKCS12_free(p12); } void load() { FILE* fp = fopen(filepath.c_str(), "rb"); if (!fp) { std::cerr << "Error opening file" << std::endl; return; } p12 = d2i_PKCS12_fp(fp, nullptr); fclose(fp); if (!p12) { std::cerr << "Error loading P12" << std::endl; } } void printProperties() { if (!p12) return; EVP_PKEY* pkey = nullptr; X509* cert = nullptr; STACK_OF(X509)* ca = nullptr; if (PKCS12_parse(p12, password, &pkey, &cert, &ca)) { std::cout << "Version: " << PKCS12_get_attr_gen(p12, NID_pkcs9_contentType) << std::endl; // Approx version via attrs if (cert) { char subj[256], issuer[256]; X509_NAME_oneline(X509_get_subject_name(cert), subj, sizeof(subj)); X509_NAME_oneline(X509_get_issuer_name(cert), issuer, sizeof(issuer)); std::cout << "Cert Subject: " << subj << std::endl; std::cout << "Cert Issuer: " << issuer << std::endl; std::cout << "Cert Serial: " << ASN1_INTEGER_get(X509_get0_serialNumber(cert)) << std::endl; } std::cout << "Additional Certs Count: " << sk_X509_num(ca) << std::endl; if (pkey) { std::cout << "Private Key Present: Yes" << std::endl; } // MacData via low-level access if needed EVP_PKEY_free(pkey); X509_free(cert); sk_X509_pop_free(ca, X509_free); } else { std::cerr << "Error parsing (wrong password?)" << std::endl; ERR_print_errors_fp(stderr); } } void write(const std::string& newFilepath, const char* newPassword = nullptr) { if (!p12) return; FILE* fp = fopen(newFilepath.c_str(), "wb"); if (!fp) { std::cerr << "Error opening output file" << std::endl; return; } i2d_PKCS12_fp(fp, p12); // Writes existing; for new, rebuild with PKCS12_create fclose(fp); } }; // Example usage: // int main() { // P12Handler handler("example.p12", "badssl.com"); // handler.printProperties(); // handler.write("new.p12", "newpass"); // return 0; // } // ===== end task-504 .P12 ===== // ===== task-505 .P8 [C] ===== #include #include #include #define MAX_LINES 10000 // Arbitrary max for simplicity #define MAX_LINE_LEN 512 typedef struct { char *filepath; char **header; int header_count; char **lua; int lua_count; char **gfx; int gfx_count; char **gff; int gff_count; char **label; int label_count; char **map; int map_count; char **sfx; int sfx_count; char **music; int music_count; } P8File; P8File* p8file_new(const char *filepath) { P8File *p8 = malloc(sizeof(P8File)); p8->filepath = strdup(filepath); p8->header = malloc(MAX_LINES * sizeof(char*)); p8->lua = malloc(MAX_LINES * sizeof(char*)); p8->gfx = malloc(MAX_LINES * sizeof(char*)); p8->gff = malloc(MAX_LINES * sizeof(char*)); p8->label = malloc(MAX_LINES * sizeof(char*)); p8->map = malloc(MAX_LINES * sizeof(char*)); p8->sfx = malloc(MAX_LINES * sizeof(char*)); p8->music = malloc(MAX_LINES * sizeof(char*)); p8->header_count = p8->lua_count = p8->gfx_count = p8->gff_count = 0; p8->label_count = p8->map_count = p8->sfx_count = p8->music_count = 0; return p8; } void p8file_read(P8File *p8) { FILE *f = fopen(p8->filepath, "r"); if (!f) return; char line[MAX_LINE_LEN]; char *current_section = NULL; while (fgets(line, sizeof(line), f)) { char *trimmed = strtok(line, "\r\n"); if (trimmed == NULL) trimmed = ""; char *dup = strdup(trimmed); if (strcmp(dup, "__lua__") == 0) { current_section = "lua"; } else if (strcmp(dup, "__gfx__") == 0) { current_section = "gfx"; } else if (strcmp(dup, "__gff__") == 0) { current_section = "gff"; } else if (strcmp(dup, "__label__") == 0) { current_section = "label"; } else if (strcmp(dup, "__map__") == 0) { current_section = "map"; } else if (strcmp(dup, "__sfx__") == 0) { current_section = "sfx"; } else if (strcmp(dup, "__music__") == 0) { current_section = "music"; } else if (current_section) { if (strcmp(current_section, "lua") == 0) p8->lua[p8->lua_count++] = dup; else if (strcmp(current_section, "gfx") == 0) p8->gfx[p8->gfx_count++] = dup; else if (strcmp(current_section, "gff") == 0) p8->gff[p8->gff_count++] = dup; else if (strcmp(current_section, "label") == 0) p8->label[p8->label_count++] = dup; else if (strcmp(current_section, "map") == 0) p8->map[p8->map_count++] = dup; else if (strcmp(current_section, "sfx") == 0) p8->sfx[p8->sfx_count++] = dup; else if (strcmp(current_section, "music") == 0) p8->music[p8->music_count++] = dup; } else { p8->header[p8->header_count++] = dup; } } fclose(f); } void p8file_print_properties(P8File *p8) { if (p8->header_count > 0) { printf("HEADER:\n"); for (int i = 0; i < p8->header_count; i++) printf("%s\n", p8->header[i]); printf("---\n"); } if (p8->lua_count > 0) { printf("LUA:\n"); for (int i = 0; i < p8->lua_count; i++) printf("%s\n", p8->lua[i]); printf("---\n"); } // Similarly for other sections... if (p8->gfx_count > 0) { printf("GFX:\n"); for (int i = 0; i < p8->gfx_count; i++) printf("%s\n", p8->gfx[i]); printf("---\n"); } if (p8->gff_count > 0) { printf("GFF:\n"); for (int i = 0; i < p8->gff_count; i++) printf("%s\n", p8->gff[i]); printf("---\n"); } if (p8->label_count > 0) { printf("LABEL:\n"); for (int i = 0; i < p8->label_count; i++) printf("%s\n", p8->label[i]); printf("---\n"); } if (p8->map_count > 0) { printf("MAP:\n"); for (int i = 0; i < p8->map_count; i++) printf("%s\n", p8->map[i]); printf("---\n"); } if (p8->sfx_count > 0) { printf("SFX:\n"); for (int i = 0; i < p8->sfx_count; i++) printf("%s\n", p8->sfx[i]); printf("---\n"); } if (p8->music_count > 0) { printf("MUSIC:\n"); for (int i = 0; i < p8->music_count; i++) printf("%s\n", p8->music[i]); printf("---\n"); } } void p8file_write(P8File *p8, const char *new_filepath) { const char *fp = new_filepath ? new_filepath : p8->filepath; FILE *f = fopen(fp, "w"); if (!f) return; for (int i = 0; i < p8->header_count; i++) fprintf(f, "%s\n", p8->header[i]); if (p8->lua_count > 0) { fprintf(f, "__lua__\n"); for (int i = 0; i < p8->lua_count; i++) fprintf(f, "%s\n", p8->lua[i]); } // Similarly for other sections... if (p8->gfx_count > 0) { fprintf(f, "__gfx__\n"); for (int i = 0; i < p8->gfx_count; i++) fprintf(f, "%s\n", p8->gfx[i]); } if (p8->gff_count > 0) { fprintf(f, "__gff__\n"); for (int i = 0; i < p8->gff_count; i++) fprintf(f, "%s\n", p8->gff[i]); } if (p8->label_count > 0) { fprintf(f, "__label__\n"); for (int i = 0; i < p8->label_count; i++) fprintf(f, "%s\n", p8->label[i]); } if (p8->map_count > 0) { fprintf(f, "__map__\n"); for (int i = 0; i < p8->map_count; i++) fprintf(f, "%s\n", p8->map[i]); } if (p8->sfx_count > 0) { fprintf(f, "__sfx__\n"); for (int i = 0; i < p8->sfx_count; i++) fprintf(f, "%s\n", p8->sfx[i]); } if (p8->music_count > 0) { fprintf(f, "__music__\n"); for (int i = 0; i < p8->music_count; i++) fprintf(f, "%s\n", p8->music[i]); } fclose(f); } void p8file_free(P8File *p8) { // Free all allocated lines and arrays for (int i = 0; i < p8->header_count; i++) free(p8->header[i]); free(p8->header); // Similarly for other sections... free(p8->lua); free(p8->gfx); free(p8->gff); free(p8->label); free(p8->map); free(p8->sfx); free(p8->music); free(p8->filepath); free(p8); } // Example usage: // int main() { // P8File *p8 = p8file_new("example.p8"); // p8file_read(p8); // p8file_print_properties(p8); // // Add to lua: p8->lua[p8->lua_count++] = strdup("-- new comment"); // p8file_write(p8, "modified.p8"); // p8file_free(p8); // return 0; // } // ===== end task-505 .P8 ===== // ===== task-506 .PACK [C++] ===== #include #include #include #include #include struct ObjectEntry { int type; long size; std::string baseId; long baseOffset; int dataOffset; int compressedLength; }; class PackFile { private: std::string filename; std::vector data; size_t offset = 0; std::string signature; uint32_t version; uint32_t numObjects; std::vector objects; std::string checksum; public: PackFile(const std::string& fn) : filename(fn) {} void open() { std::ifstream file(filename, std::ios::binary | std::ios::ate); size_t size = file.tellg(); data.resize(size); file.seekg(0); file.read(data.data(), size); } void decode() { // Signature signature = std::string(&data[offset], 4); offset += 4; // Version version = readBigUInt32(); // Number of objects numObjects = readBigUInt32(); // Objects for (uint32_t i = 0; i < numObjects; i++) { ObjectEntry obj; unsigned char byte = data[offset]; obj.type = (byte >> 4) & 0x07; long size = byte & 0x0F; long shift = 4; offset += 1; while (byte & 0x80) { byte = data[offset]; size |= (long)(byte & 0x7F) << shift; shift += 7; offset += 1; } obj.size = size; // Base if (obj.type == 6 || obj.type == 7) { if (obj.type == 7) { obj.baseId = ""; for (int j = 0; j < 20; j++) { std::stringstream ss; ss << std::hex << std::setfill('0') << std::setw(2) << (int)(unsigned char)data[offset + j]; obj.baseId += ss.str(); } offset += 20; } else { byte = data[offset]; long ofs = byte & 0x7F; long add = 1; offset += 1; while (byte & 0x80) { byte = data[offset]; ofs += add * (byte & 0x7F); add <<= 7; offset += 1; } obj.baseOffset = -(ofs + 1); } } // Compressed data obj.dataOffset = offset; z_stream strm; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = data.size() - offset; strm.next_in = (Bytef*)&data[offset]; inflateInit(&strm); char temp[1024]; int compressed = 0; while (true) { strm.avail_out = 1024; strm.next_out = (Bytef*)temp; int ret = inflate(&strm, Z_NO_FLUSH); if (ret == Z_STREAM_END) break; compressed += strm.total_in; } obj.compressedLength = strm.total_in; offset += obj.compressedLength; inflateEnd(&strm); objects.push_back(obj); } // Trailer checksum = ""; for (size_t j = offset; j < data.size(); j++) { std::stringstream ss; ss << std::hex << std::setfill('0') << std::setw(2) << (int)(unsigned char)data[j]; checksum += ss.str(); } } uint32_t readBigUInt32() { uint32_t val = ( (uint32_t)(unsigned char)data[offset] << 24 ) | ( (uint32_t)(unsigned char)data[offset+1] << 16 ) | ( (uint32_t)(unsigned char)data[offset+2] << 8 ) | (uint32_t)(unsigned char)data[offset+3]; offset += 4; return val; } void printProperties() { std::cout << "Signature: " << signature << std::endl; std::cout << "Version: " << version << std::endl; std::cout << "Number of Objects: " << numObjects << std::endl; for (size_t i = 0; i < objects.size(); i++) { const auto& obj = objects[i]; std::cout << "Object " << i << ":" << std::endl; std::cout << " Type: " << obj.type << " (" << getTypeName(obj.type) << ")" << std::endl; std::cout << " Size: " << obj.size << std::endl; if (!obj.baseId.empty()) std::cout << " Base ID: " << obj.baseId << std::endl; if (obj.baseOffset != 0) std::cout << " Base Offset: " << obj.baseOffset << std::endl; std::cout << " Data Offset: " << obj.dataOffset << std::endl; std::cout << " Compressed Length: " << obj.compressedLength << std::endl; } std::cout << "Checksum: " << checksum << std::endl; } void write(const std::string& newFilename) { std::ofstream file(newFilename, std::ios::binary); file.write(data.data(), data.size()); } std::string getTypeName(int type) { switch (type) { case 1: return "commit"; case 2: return "tree"; case 3: return "blob"; case 4: return "tag"; case 6: return "ofs_delta"; case 7: return "ref_delta"; default: return "unknown"; } } }; int main() { PackFile pack("example.pack"); pack.open(); pack.decode(); pack.printProperties(); pack.write("copy.pack"); return 0; } // ===== end task-506 .PACK ===== // ===== task-507 .PAGES [C++] ===== #include #include #include #include #include #include // Assume snappy lib #include // Assume libplist class PagesFile { private: std::string filepath; zip_t* zip; std::map properties; // Use std::any or variant for mixed types public: PagesFile(const std::string& filepath) : filepath(filepath) { int err = 0; zip = zip_open(filepath.c_str(), ZIP_RDONLY, &err); if (!zip) { throw std::runtime_error("Failed to open ZIP"); } properties = readProperties(); } ~PagesFile() { zip_close(zip); } std::map readProperties() { std::map props; props["File Extension"] = std::string(".pages"); props["MIME Type"] = std::string("application/x-iwork-pages-sffpages"); props["Container Type"] = std::string("ZIP archive"); std::set dirs; std::vector iwaFiles, metadataFiles, previewFiles, dataFiles; props["Compression Method"] = std::string("Snappy for .iwa, ZIP for package"); zip_int64_t num_entries = zip_get_num_entries(zip, 0); for (zip_int64_t i = 0; i < num_entries; ++i) { const char* name = zip_get_name(zip, i, 0); std::string sname(name); size_t pos = sname.find('/'); std::string dir = (pos != std::string::npos) ? sname.substr(0, pos) : ""; if (!dir.empty()) dirs.insert(dir); if (sname.ends_with(".iwa")) { iwaFiles.push_back(sname); } else if (sname.find("Metadata/") == 0) { metadataFiles.push_back(sname); } else if (sname.find("preview") != std::string::npos || sname.find("Thumbnail") != std::string::npos) { previewFiles.push_back(sname); } else if (sname.find("Data/") == 0) { dataFiles.push_back(sname); } } std::vector dirVec(dirs.begin(), dirs.end()); props["Internal Directories"] = dirVec; props[".iwa Files"] = iwaFiles; props["Metadata Files"] = metadataFiles; props["Preview Files"] = previewFiles; props["Data Files"] = dataFiles; return props; } std::vector decodeIwa(const std::string& iwaPath) { zip_file_t* file = zip_fopen(zip, iwaPath.c_str(), 0); if (!file) throw std::runtime_error("Failed to open iwa"); zip_stat_t stat; zip_stat(zip, iwaPath.c_str(), 0, &stat); std::vector compressed(stat.size); zip_fread(file, compressed.data(), stat.size); zip_fclose(file); size_t offset = (compressed[0] == 0) ? 1 : 0; std::string decompressed; snappy::Uncompress(compressed.data() + offset, compressed.size() - offset, &decompressed); return std::vector(decompressed.begin(), decompressed.end()); } void printProperties() { for (const auto& [key, value] : properties) { if (value.type() == typeid(std::string)) { std::cout << key << ": " << std::any_cast(value) << std::endl; } else if (value.type() == typeid(std::vector)) { auto vec = std::any_cast>(value); std::cout << key << ": "; for (size_t i = 0; i < vec.size(); ++i) { std::cout << vec[i] << (i < vec.size() - 1 ? ", " : ""); } std::cout << std::endl; } } auto iwaAny = properties[".iwa Files"]; if (iwaAny.type() == typeid(std::vector) && !std::any_cast>(iwaAny).empty()) { std::string firstIwa = std::any_cast>(iwaAny)[0]; auto decompressed = decodeIwa(firstIwa); std::cout << "Decompressed size of " << firstIwa << ": " << decompressed.size() << " bytes" << std::endl; } } void write(const std::string& outputPath, bool modifyExample) { zip_t* newZip = zip_open(outputPath.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); if (!newZip) throw std::runtime_error("Failed to create ZIP"); zip_int64_t num_entries = zip_get_num_entries(zip, 0); for (zip_int64_t i = 0; i < num_entries; ++i) { const char* name = zip_get_name(zip, i, 0); zip_file_t* file = zip_fopen(zip, name, 0); zip_stat_t stat; zip_stat(zip, name, 0, &stat); std::vector data(stat.size); zip_fread(file, data.data(), stat.size); zip_fclose(file); if (modifyExample && std::string(name) == "Metadata/Properties.plist") { // Simple plist modify using libplist plist_t root = nullptr; plist_from_xml(data.data(), data.size(), &root); plist_dict_set_item(root, "Modified", plist_new_bool(1)); char* newPlist = nullptr; uint32_t len = 0; plist_to_xml(root, &newPlist, &len); data.assign(newPlist, newPlist + len); free(newPlist); plist_free(root); } zip_source_t* src = zip_source_buffer(newZip, data.data(), data.size(), 0); zip_file_add(newZip, name, src, ZIP_FL_OVERWRITE); } zip_close(newZip); } }; // Usage example: // int main() { // try { // PagesFile pages("sample.pages"); // pages.printProperties(); // pages.write("modified.pages", true); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-507 .PAGES ===== // ===== task-508 .PAK [C] ===== #include #include #include #include #define PAK_MAGIC "PACK" #define ENTRY_SIZE 64 #define NAME_SIZE 56 typedef struct { char name[NAME_SIZE]; uint32_t offset; uint32_t size; uint8_t *data; } PakEntry; typedef struct { char magic[5]; uint32_t dir_offset; uint32_t dir_size; uint32_t num_files; PakEntry *entries; } PakFile; PakFile* pak_create() { PakFile* pak = (PakFile*)malloc(sizeof(PakFile)); memset(pak, 0, sizeof(PakFile)); return pak; } void pak_free(PakFile* pak) { if (pak->entries) { for (uint32_t i = 0; i < pak->num_files; i++) { free(pak->entries[i].data); } free(pak->entries); } free(pak); } int pak_read(PakFile* pak, const char* filepath) { FILE* f = fopen(filepath, "rb"); if (!f) return -1; fseek(f, 0, SEEK_END); long file_size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = (uint8_t*)malloc(file_size); fread(data, 1, file_size, f); fclose(f); memcpy(pak->magic, data, 4); pak->magic[4] = '\0'; if (strcmp(pak->magic, PAK_MAGIC) != 0) { free(data); return -1; } memcpy(&pak->dir_offset, data + 4, 4); memcpy(&pak->dir_size, data + 8, 4); pak->num_files = pak->dir_size / ENTRY_SIZE; pak->entries = (PakEntry*)malloc(pak->num_files * sizeof(PakEntry)); for (uint32_t i = 0; i < pak->num_files; i++) { uint32_t entry_offset = pak->dir_offset + i * ENTRY_SIZE; strncpy(pak->entries[i].name, (char*)(data + entry_offset), NAME_SIZE); pak->entries[i].name[NAME_SIZE - 1] = '\0'; for (int j = strlen(pak->entries[i].name) - 1; j >= 0; j--) { if (pak->entries[i].name[j] == '\0') pak->entries[i].name[j] = '\0'; else break; } memcpy(&pak->entries[i].offset, data + entry_offset + NAME_SIZE, 4); memcpy(&pak->entries[i].size, data + entry_offset + NAME_SIZE + 4, 4); pak->entries[i].data = (uint8_t*)malloc(pak->entries[i].size); memcpy(pak->entries[i].data, data + pak->entries[i].offset, pak->entries[i].size); } free(data); return 0; } void pak_print_properties(const PakFile* pak) { printf("Magic Signature: %s\n", pak->magic); printf("Directory Offset: %u\n", pak->dir_offset); printf("Directory Size: %u\n", pak->dir_size); printf("Number of Files: %u\n", pak->num_files); printf("File Entries:\n"); for (uint32_t i = 0; i < pak->num_files; i++) { printf("- Filename: %s\n", pak->entries[i].name); printf(" Offset: %u\n", pak->entries[i].offset); printf(" Size: %u\n", pak->entries[i].size); } } int pak_write(const PakFile* pak, const char* filepath) { if (pak->num_files == 0) return -1; FILE* f = fopen(filepath, "wb"); if (!f) return -1; uint32_t current_offset = 12; for (uint32_t i = 0; i < pak->num_files; i++) { if (!pak->entries[i].data) { fclose(f); return -1; } current_offset += pak->entries[i].size; } uint32_t dir_offset = 12 + (current_offset - 12); uint32_t dir_size = pak->num_files * ENTRY_SIZE; fwrite(PAK_MAGIC, 1, 4, f); fwrite(&dir_offset, 4, 1, f); fwrite(&dir_size, 4, 1, f); current_offset = 12; for (uint32_t i = 0; i < pak->num_files; i++) { fwrite(pak->entries[i].data, 1, pak->entries[i].size, f); } for (uint32_t i = 0; i < pak->num_files; i++) { char name_padded[NAME_SIZE] = {0}; strncpy(name_padded, pak->entries[i].name, NAME_SIZE - 1); fwrite(name_padded, 1, NAME_SIZE, f); fwrite(¤t_offset, 4, 1, f); fwrite(&pak->entries[i].size, 4, 1, f); current_offset += pak->entries[i].size; } fclose(f); return 0; } // Example usage: // int main() { // PakFile* pak = pak_create(); // if (pak_read(pak, "example.pak") == 0) { // pak_print_properties(pak); // pak_write(pak, "new.pak"); // } // pak_free(pak); // return 0; // } // ===== end task-508 .PAK ===== // ===== task-509 .PAL [C++] ===== #include #include #include #include #include struct PaletteEntry { uint8_t r, g, b, flags; }; class PalFile { public: char riffSig[5]; uint32_t fileSize; char formType[5]; char chunkId[5]; uint32_t chunkSize; uint16_t palVersion; uint16_t numEntries; std::vector entries; PalFile(const std::string& filename) { read(filename); } void read(const std::string& filename) { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) { std::cerr << "Error opening file" << std::endl; return; } size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(data.data(), size); size_t offset = 0; memcpy(riffSig, data.data() + offset, 4); riffSig[4] = '\0'; offset += 4; memcpy(&fileSize, data.data() + offset, 4); #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ fileSize = __builtin_bswap32(fileSize); #endif offset += 4; memcpy(formType, data.data() + offset, 4); formType[4] = '\0'; offset += 4; memcpy(chunkId, data.data() + offset, 4); chunkId[4] = '\0'; offset += 4; memcpy(&chunkSize, data.data() + offset, 4); #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ chunkSize = __builtin_bswap32(chunkSize); #endif offset += 4; memcpy(&palVersion, data.data() + offset, 2); #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ palVersion = __builtin_bswap16(palVersion); #endif offset += 2; memcpy(&numEntries, data.data() + offset, 2); #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ numEntries = __builtin_bswap16(numEntries); #endif offset += 2; entries.resize(numEntries); for (uint16_t i = 0; i < numEntries; ++i) { entries[i].r = static_cast(data[offset++]); entries[i].g = static_cast(data[offset++]); entries[i].b = static_cast(data[offset++]); entries[i].flags = static_cast(data[offset++]); } } void printProperties() const { std::cout << "RIFF Signature: " << riffSig << std::endl; std::cout << "File Size: " << fileSize << std::endl; std::cout << "Form Type: " << formType << std::endl; std::cout << "Chunk ID: " << chunkId << std::endl; std::cout << "Chunk Size: " << chunkSize << std::endl; std::cout << "Palette Version: 0x" << std::hex << palVersion << " (" << std::dec << palVersion << ")" << std::endl; std::cout << "Number of Palette Entries: " << numEntries << std::endl; std::cout << "Palette Entries:" << std::endl; for (uint16_t i = 0; i < numEntries; ++i) { std::cout << "Entry " << i << ": R=" << static_cast(entries[i].r) << ", G=" << static_cast(entries[i].g) << ", B=" << static_cast(entries[i].b) << ", Flags=0x" << std::hex << static_cast(entries[i].flags) << std::dec << std::endl; } } void write(const std::string& filename) const { std::ofstream file(filename, std::ios::binary); if (!file) { std::cerr << "Error opening file for write" << std::endl; return; } file.write(riffSig, 4); uint32_t leFileSize = fileSize; #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ leFileSize = __builtin_bswap32(leFileSize); #endif file.write(reinterpret_cast(&leFileSize), 4); file.write(formType, 4); file.write(chunkId, 4); uint32_t leChunkSize = chunkSize; #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ leChunkSize = __builtin_bswap32(leChunkSize); #endif file.write(reinterpret_cast(&leChunkSize), 4); uint16_t lePalVersion = palVersion; #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ lePalVersion = __builtin_bswap16(lePalVersion); #endif file.write(reinterpret_cast(&lePalVersion), 2); uint16_t leNumEntries = numEntries; #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ leNumEntries = __builtin_bswap16(leNumEntries); #endif file.write(reinterpret_cast(&leNumEntries), 2); for (const auto& entry : entries) { file.put(static_cast(entry.r)); file.put(static_cast(entry.g)); file.put(static_cast(entry.b)); file.put(static_cast(entry.flags)); } } }; // Example usage: ./program input.pal int main(int argc, char* argv[]) { if (argc > 1) { PalFile pal(argv[1]); pal.printProperties(); } return 0; } // ===== end task-509 .PAL ===== // ===== task-510 .PAM [C++] ===== #include #include #include #include #include #include #include class PamFile { private: std::map properties; std::vector raster; public: PamFile(const std::string& filename = "") { properties["WIDTH"] = ""; properties["HEIGHT"] = ""; properties["DEPTH"] = ""; properties["MAXVAL"] = ""; properties["TUPLTYPE"] = ""; if (!filename.empty()) { read(filename); } } void read(const std::string& filename) { std::ifstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file"); } std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); auto it = std::search(data.begin(), data.end(), {'E','N','D','H','D','R','\n'}); if (it == data.end()) { throw std::runtime_error("Invalid .PAM: No ENDHDR"); } size_t headerEnd = std::distance(data.begin(), it) + 7; std::string header(data.begin(), data.begin() + headerEnd); std::istringstream headerStream(header); std::string line; std::getline(headerStream, line); if (line != "P7") { throw std::runtime_error("Invalid .PAM: Missing P7 magic"); } while (std::getline(headerStream, line)) { line.erase(0, line.find_first_not_of(" \t")); // Trim left if (line.empty() || line[0] == '#') continue; std::istringstream lineStream(line); std::string key; lineStream >> key; if (key == "ENDHDR") break; if (key == "TUPLTYPE") { std::string value; std::getline(lineStream, value); value.erase(0, value.find_first_not_of(" \t")); properties["TUPLTYPE"] += (properties["TUPLTYPE"].empty() ? "" : " ") + value; } else if (key == "WIDTH" || key == "HEIGHT" || key == "DEPTH" || key == "MAXVAL") { std::string value; lineStream >> value; properties[key] = value; } } if (properties["WIDTH"].empty() || properties["HEIGHT"].empty() || properties["DEPTH"].empty() || properties["MAXVAL"].empty()) { throw std::runtime_error("Missing required .PAM properties"); } raster.assign(data.begin() + headerEnd, data.end()); int width = std::stoi(properties["WIDTH"]); int height = std::stoi(properties["HEIGHT"]); int depth = std::stoi(properties["DEPTH"]); int maxval = std::stoi(properties["MAXVAL"]); int sampleSize = (maxval <= 255) ? 1 : 2; size_t expectedSize = static_cast(width) * height * depth * sampleSize; if (raster.size() != expectedSize) { throw std::runtime_error("Invalid raster size"); } } void printProperties() const { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& filename, const std::vector& newRaster = {}) const { if (properties.at("WIDTH").empty() || properties.at("HEIGHT").empty() || properties.at("DEPTH").empty() || properties.at("MAXVAL").empty()) { throw std::runtime_error("Missing properties for writing"); } std::ofstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file for writing"); } file << "P7\n"; file << "WIDTH " << properties.at("WIDTH") << "\n"; file << "HEIGHT " << properties.at("HEIGHT") << "\n"; file << "DEPTH " << properties.at("DEPTH") << "\n"; file << "MAXVAL " << properties.at("MAXVAL") << "\n"; if (!properties.at("TUPLTYPE").empty()) { file << "TUPLTYPE " << properties.at("TUPLTYPE") << "\n"; } file << "ENDHDR\n"; const auto& rasterToWrite = newRaster.empty() ? raster : newRaster; file.write(reinterpret_cast(rasterToWrite.data()), rasterToWrite.size()); } }; // Example usage: // int main() { // try { // PamFile pam("sample.pam"); // pam.printProperties(); // pam.write("output.pam"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-510 .PAM ===== // ===== task-511 .PAPA [C] ===== #include #include #include #include struct PapaHeader { char magic[5]; uint32_t version; uint16_t num_strings; uint16_t num_textures; uint16_t num_vertex_buffers; uint16_t num_index_buffers; uint16_t num_materials; uint16_t num_meshes; uint16_t num_skeletons; uint16_t num_models; uint16_t num_animations; uint64_t string_table_offset; uint64_t texture_table_offset; uint64_t vertex_buffer_table_offset; uint64_t index_buffer_table_offset; uint64_t material_table_offset; uint64_t mesh_table_offset; uint64_t skeleton_table_offset; uint64_t model_table_offset; uint64_t animation_table_offset; }; struct PapaFile { char* data; long size; struct PapaHeader header; }; void read_papa(struct PapaFile* pf, const char* filepath) { FILE* file = fopen(filepath, "rb"); if (!file) { perror("Failed to open file"); exit(1); } fseek(file, 0, SEEK_END); pf->size = ftell(file); fseek(file, 0, SEEK_SET); pf->data = malloc(pf->size); fread(pf->data, 1, pf->size, file); fclose(file); memcpy(pf->header.magic, pf->data, 4); pf->header.magic[4] = '\0'; if (strcmp(pf->header.magic, "Papa") != 0) { fprintf(stderr, "Invalid .PAPA file\n"); exit(1); } long offset = 4; memcpy(&pf->header.version, pf->data + offset, sizeof(uint32_t)); offset += sizeof(uint32_t); memcpy(&pf->header.num_strings, pf->data + offset, sizeof(uint16_t)); offset += sizeof(uint16_t); memcpy(&pf->header.num_textures, pf->data + offset, sizeof(uint16_t)); offset += sizeof(uint16_t); memcpy(&pf->header.num_vertex_buffers, pf->data + offset, sizeof(uint16_t)); offset += sizeof(uint16_t); memcpy(&pf->header.num_index_buffers, pf->data + offset, sizeof(uint16_t)); offset += sizeof(uint16_t); memcpy(&pf->header.num_materials, pf->data + offset, sizeof(uint16_t)); offset += sizeof(uint16_t); memcpy(&pf->header.num_meshes, pf->data + offset, sizeof(uint16_t)); offset += sizeof(uint16_t); memcpy(&pf->header.num_skeletons, pf->data + offset, sizeof(uint16_t)); offset += sizeof(uint16_t); memcpy(&pf->header.num_models, pf->data + offset, sizeof(uint16_t)); offset += sizeof(uint16_t); memcpy(&pf->header.num_animations, pf->data + offset, sizeof(uint16_t)); offset += sizeof(uint16_t); offset += 6; // padding memcpy(&pf->header.string_table_offset, pf->data + offset, sizeof(uint64_t)); offset += sizeof(uint64_t); memcpy(&pf->header.texture_table_offset, pf->data + offset, sizeof(uint64_t)); offset += sizeof(uint64_t); memcpy(&pf->header.vertex_buffer_table_offset, pf->data + offset, sizeof(uint64_t)); offset += sizeof(uint64_t); memcpy(&pf->header.index_buffer_table_offset, pf->data + offset, sizeof(uint64_t)); offset += sizeof(uint64_t); memcpy(&pf->header.material_table_offset, pf->data + offset, sizeof(uint64_t)); offset += sizeof(uint64_t); memcpy(&pf->header.mesh_table_offset, pf->data + offset, sizeof(uint64_t)); offset += sizeof(uint64_t); memcpy(&pf->header.skeleton_table_offset, pf->data + offset, sizeof(uint64_t)); offset += sizeof(uint64_t); memcpy(&pf->header.model_table_offset, pf->data + offset, sizeof(uint64_t)); offset += sizeof(uint64_t); memcpy(&pf->header.animation_table_offset, pf->data + offset, sizeof(uint64_t)); } void print_properties(const struct PapaFile* pf) { printf("magic: %s\n", pf->header.magic); printf("version: %u\n", pf->header.version); printf("num_strings: %hu\n", pf->header.num_strings); printf("num_textures: %hu\n", pf->header.num_textures); printf("num_vertex_buffers: %hu\n", pf->header.num_vertex_buffers); printf("num_index_buffers: %hu\n", pf->header.num_index_buffers); printf("num_materials: %hu\n", pf->header.num_materials); printf("num_meshes: %hu\n", pf->header.num_meshes); printf("num_skeletons: %hu\n", pf->header.num_skeletons); printf("num_models: %hu\n", pf->header.num_models); printf("num_animations: %hu\n", pf->header.num_animations); printf("string_table_offset: %llu\n", pf->header.string_table_offset); printf("texture_table_offset: %llu\n", pf->header.texture_table_offset); printf("vertex_buffer_table_offset: %llu\n", pf->header.vertex_buffer_table_offset); printf("index_buffer_table_offset: %llu\n", pf->header.index_buffer_table_offset); printf("material_table_offset: %llu\n", pf->header.material_table_offset); printf("mesh_table_offset: %llu\n", pf->header.mesh_table_offset); printf("skeleton_table_offset: %llu\n", pf->header.skeleton_table_offset); printf("model_table_offset: %llu\n", pf->header.model_table_offset); printf("animation_table_offset: %llu\n", pf->header.animation_table_offset); } void write_papa(const struct PapaFile* pf, const char* filepath) { FILE* file = fopen(filepath, "wb"); if (!file) { perror("Failed to open file for writing"); exit(1); } fwrite(pf->data, 1, pf->size, file); fclose(file); } int main(int argc, char** argv) { if (argc < 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } struct PapaFile pf; read_papa(&pf, argv[1]); print_properties(&pf); free(pf.data); return 0; } // ===== end task-511 .PAPA ===== // ===== task-512 .PAR [C++] ===== #include #include #include #include #include #include class ParFileHandler { private: std::string filepath; std::map headers; std::map> enums; std::map>> structs; std::vector>> data; void parse() { std::ifstream file(filepath); std::string line; std::string currentMode = "header"; std::string currentStruct; while (std::getline(file, line)) { std::istringstream iss(line); line.erase(0, line.find_first_not_of(" \t")); if (line.empty() || line[0] == '#') continue; if (line.find("typedef enum") != std::string::npos) { currentMode = "enum"; size_t bracePos = line.find('{'); size_t endBracePos = line.find('}'); std::string enumName = line.substr(endBracePos + 1); enumName = enumName.substr(0, enumName.find(';')); enumName.erase(remove_if(enumName.begin(), enumName.end(), isspace), enumName.end()); std::string valuesStr = line.substr(bracePos + 1, endBracePos - bracePos - 1); std::vector values; std::istringstream valuesIss(valuesStr); std::string value; while (std::getline(valuesIss, value, ',')) { value.erase(remove_if(value.begin(), value.end(), isspace), value.end()); values.push_back(value); } enums[enumName] = values; } else if (line.find("typedef struct") != std::string::npos) { currentMode = "struct"; size_t endBracePos = line.find('}'); std::string structName = line.substr(endBracePos + 1); structName = structName.substr(0, structName.find(';')); structName.erase(remove_if(structName.begin(), structName.end(), isspace), structName.end()); structs[structName] = {}; currentStruct = structName; } else if (currentMode == "struct" && line.find(';') != std::string::npos) { line = line.substr(0, line.find(';')); std::istringstream fieldIss(line); std::string type, name; fieldIss >> type >> name; std::string arraySize; if (name.find('[') != std::string::npos) { size_t bracketPos = name.find('['); arraySize = name.substr(bracketPos + 1, name.find(']') - bracketPos - 1); name = name.substr(0, bracketPos); } std::map field; field["type"] = type; field["name"] = name; if (!arraySize.empty()) field["array_size"] = arraySize; structs[currentStruct].push_back(field); } else { std::istringstream partsIss(line); std::string key; partsIss >> key; key = std::string(toupper(key[0])) + key.substr(1); // Approximate upper std::string rest; std::getline(partsIss, rest); if (structs.find(key) != structs.end()) { currentMode = "data"; rest.erase(remove(rest.begin(), rest.end(), '{'), rest.end()); rest.erase(remove(rest.begin(), rest.end(), '}'), rest.end()); rest.erase(remove(rest.begin(), rest.end(), '"'), rest.end()); std::istringstream valuesIss(rest); std::vector values; std::string val; while (valuesIss >> val) values.push_back(val); std::map> entry; entry["table"] = key; entry["values"] = values; data.push_back(entry); } else { headers[key] = rest; } } } } public: ParFileHandler(std::string fp) : filepath(fp) { parse(); } void printProperties() { std::cout << "Headers:" << std::endl; for (auto& h : headers) std::cout << h.first << ": " << h.second << std::endl; std::cout << "Enums:" << std::endl; for (auto& e : enums) { std::cout << e.first << ": "; for (auto& v : e.second) std::cout << v << " "; std::cout << std::endl; } std::cout << "Structs:" << std::endl; for (auto& s : structs) { std::cout << s.first << ":" << std::endl; for (auto& f : s.second) { std::cout << " type: " << f.at("type") << ", name: " << f.at("name"); if (f.count("array_size")) std::cout << ", array_size: " << f.at("array_size"); std::cout << std::endl; } } std::cout << "Data:" << std::endl; for (auto& d : data) { std::cout << d.at("table") << ": "; for (auto& v : d.at("values")) std::cout << v << " "; std::cout << std::endl; } } void write(std::string newFilepath) { std::ofstream file(newFilepath); for (auto& h : headers) file << h.first << " " << h.second << "\n"; for (auto& e : enums) { file << "typedef enum { " ; for (size_t i = 0; i < e.second.size(); ++i) { file << e.second[i]; if (i < e.second.size() - 1) file << ", "; } file << " } " << e.first << ";\n"; } for (auto& s : structs) { file << "typedef struct {\n"; for (auto& f : s.second) { file << " " << f.at("type") << " " << f.at("name"); if (f.count("array_size")) file << "[" << f.at("array_size") << "]"; file << ";\n"; } file << "} " << s.first << ";\n"; } for (auto& d : data) { file << d.at("table") << " { "; for (auto& v : d.at("values")) file << v << " "; file << "}\n"; } file.close(); } }; // Example usage: // int main() { // ParFileHandler handler("example.par"); // handler.printProperties(); // handler.write("new.par"); // return 0; // } // ===== end task-512 .PAR ===== // ===== task-513 .PAR2 [C++] ===== #include #include #include #include #include #include #include // Need OpenSSL for MD5 class Par2File { private: std::string filepath; std::vector> packets; std::string bytesToHex(const unsigned char* bytes, size_t len) { std::stringstream ss; for (size_t i = 0; i < len; ++i) { ss << std::hex << std::setw(2) << std::setfill('0') << (int)bytes[i]; } return ss.str(); } void hexToBytes(const std::string& hex, unsigned char* bytes) { for (size_t i = 0; i < hex.length() / 2; ++i) { std::sscanf(hex.substr(i * 2, 2).c_str(), "%hhx", &bytes[i]); } } public: Par2File(const std::string& fp = "") : filepath(fp) { if (!fp.empty()) read(); } void read() { std::ifstream file(filepath, std::ios::binary); file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(data.data(), size); size_t offset = 0; while (offset < size) { if (size - offset < 64) break; std::string magic(data.begin() + offset, data.begin() + offset + 8); if (magic != "PAR2\0PKT") { ++offset; continue; } offset += 8; uint64_t length = *(uint64_t*)(data.data() + offset); offset += 8; unsigned char hash[16]; std::memcpy(hash, data.data() + offset, 16); std::string hashStr = bytesToHex(hash, 16); offset += 16; unsigned char setId[16]; std::memcpy(setId, data.data() + offset, 16); std::string setIdStr = bytesToHex(setId, 16); offset += 16; std::string type(data.begin() + offset, data.begin() + offset + 16); type.erase(std::remove(type.begin(), type.end(), '\0'), type.end()); offset += 16; size_t bodyLength = length - 64; std::vector body(data.begin() + offset, data.begin() + offset + bodyLength); std::map packet; packet["magic"] = magic; packet["length"] = std::to_string(length); packet["hash"] = hashStr; packet["set_id"] = setIdStr; packet["type"] = type; size_t bodyOffset = 0; if (type.find("Main") != std::string::npos) { uint64_t sliceSize = *(uint64_t*)(body.data() + bodyOffset); packet["slice_size"] = std::to_string(sliceSize); bodyOffset += 8; uint32_t numRecovery = *(uint32_t*)(body.data() + bodyOffset); packet["num_recovery_files"] = std::to_string(numRecovery); bodyOffset += 4; packet["recovery_file_ids"] = ""; for (uint32_t i = 0; i < numRecovery; ++i) { unsigned char id[16]; std::memcpy(id, body.data() + bodyOffset, 16); packet["recovery_file_ids"] += bytesToHex(id, 16) + " "; bodyOffset += 16; } packet["non_recovery_file_ids"] = ""; while (bodyOffset < bodyLength) { unsigned char id[16]; std::memcpy(id, body.data() + bodyOffset, 16); packet["non_recovery_file_ids"] += bytesToHex(id, 16) + " "; bodyOffset += 16; } } else if (type.find("FileDesc") != std::string::npos) { unsigned char fid[16]; std::memcpy(fid, body.data(), 16); packet["file_id"] = bytesToHex(fid, 16); unsigned char fhash[16]; std::memcpy(fhash, body.data() + 16, 16); packet["file_hash"] = bytesToHex(fhash, 16); unsigned char h16k[16]; std::memcpy(h16k, body.data() + 32, 16); packet["hash_16k"] = bytesToHex(h16k, 16); uint64_t flen = *(uint64_t*)(body.data() + 48); packet["file_length"] = std::to_string(flen); std::string fname(body.begin() + 56, body.end()); fname.erase(std::remove(fname.begin(), fname.end(), '\0'), fname.end()); packet["file_name"] = fname; } // Add more... packets.push_back(packet); offset += bodyLength; } } void printProperties() { for (const auto& packet : packets) { for (const auto& kv : packet) { std::cout << kv.first << ": " << kv.second << std::endl; } std::cout << "-------------------" << std::endl; } } void write(const std::string& outputPath) { std::ofstream out(outputPath, std::ios::binary); for (const auto& packet : packets) { std::vector body; if (packet.at("type").find("Main") != std::string::npos) { uint64_t sliceSize = std::stoull(packet.at("slice_size")); body.resize(body.size() + 8); std::memcpy(body.data() + body.size() - 8, &sliceSize, 8); uint32_t numRecovery = std::stoul(packet.at("num_recovery_files")); body.resize(body.size() + 4); std::memcpy(body.data() + body.size() - 4, &numRecovery, 4); std::istringstream iss(packet.at("recovery_file_ids")); std::string id; while (iss >> id) { unsigned char bytes[16]; hexToBytes(id, bytes); body.insert(body.end(), bytes, bytes + 16); } iss.str(packet.at("non_recovery_file_ids")); iss.clear(); while (iss >> id) { unsigned char bytes[16]; hexToBytes(id, bytes); body.insert(body.end(), bytes, bytes + 16); } } else if (packet.at("type").find("FileDesc") != std::string::npos) { unsigned char fid[16]; hexToBytes(packet.at("file_id"), fid); body.insert(body.end(), fid, fid + 16); unsigned char fhash[16]; hexToBytes(packet.at("file_hash"), fhash); body.insert(body.end(), fhash, fhash + 16); unsigned char h16k[16]; hexToBytes(packet.at("hash_16k"), h16k); body.insert(body.end(), h16k, h16k + 16); uint64_t flen = std::stoull(packet.at("file_length")); body.resize(body.size() + 8); std::memcpy(body.data() + body.size() - 8, &flen, 8); std::string name = packet.at("file_name"); body.insert(body.end(), name.begin(), name.end()); int pad = (4 - name.length() % 4) % 4; body.insert(body.end(), pad, '\0'); } // Add more... uint64_t length = 64 + body.size(); unsigned char setId[16]; hexToBytes(packet.at("set_id"), setId); std::vector tempForHash; tempForHash.insert(tempForHash.end(), setId, setId + 16); tempForHash.insert(tempForHash.end(), body.begin(), body.end()); unsigned char hash[MD5_DIGEST_LENGTH]; MD5(tempForHash.data(), tempForHash.size(), hash); std::vector header; header.insert(header.end(), "PAR2\0PKT", "PAR2\0PKT" + 8); header.resize(header.size() + 8); std::memcpy(header.data() + header.size() - 8, &length, 8); header.insert(header.end(), hash, hash + 16); header.insert(header.end(), setId, setId + 16); std::string type = packet.at("type"); header.insert(header.end(), type.begin(), type.end()); header.insert(header.end(), 16 - type.length(), '\0'); out.write(header.data(), header.size()); out.write(body.data(), body.size()); } } }; // ===== end task-513 .PAR2 ===== // ===== task-514 .PARAMS [C] ===== #include #include #include #define MAX_LINE 256 #define MAX_PARAMS 1000 // Arbitrary max typedef struct { char *vehicleId; char *componentId; char *name; char *value; char *type; } ParamEntry; typedef struct { char *filename; ParamEntry *parameters; int count; } ParamsFile; ParamsFile* params_file_create(const char *filename) { ParamsFile *pf = malloc(sizeof(ParamsFile)); pf->filename = strdup(filename); pf->parameters = malloc(sizeof(ParamEntry) * MAX_PARAMS); pf->count = 0; FILE *f = fopen(filename, "r"); if (!f) return pf; char line[MAX_LINE]; while (fgets(line, MAX_LINE, f)) { if (line[0] == '#' || line[0] == '\n') continue; char *fields[5]; int i = 0; char *token = strtok(line, "\t\n"); while (token && i < 5) { fields[i++] = token; token = strtok(NULL, "\t\n"); } if (i == 5) { ParamEntry *p = &pf->parameters[pf->count++]; p->vehicleId = strdup(fields[0]); p->componentId = strdup(fields[1]); p->name = strdup(fields[2]); p->value = strdup(fields[3]); p->type = strdup(fields[4]); } } fclose(f); return pf; } void params_file_print_properties(ParamsFile *pf) { for (int i = 0; i < pf->count; i++) { ParamEntry p = pf->parameters[i]; printf("Vehicle-Id: %s\n", p.vehicleId); printf("Component-Id: %s\n", p.componentId); printf("Name: %s\n", p.name); printf("Value: %s\n", p.value); printf("Type: %s\n", p.type); printf("\n"); } } void params_file_write(ParamsFile *pf, const char *output_filename) { const char *fname = output_filename ? output_filename : pf->filename; FILE *f = fopen(fname, "w"); if (!f) return; fprintf(f, "# Onboard parameters for Vehicle 1\n"); fprintf(f, "# Vehicle-Id Component-Id Name Value Type\n"); for (int i = 0; i < pf->count; i++) { ParamEntry p = pf->parameters[i]; fprintf(f, "%s\t%s\t%s\t%s\t%s\n", p.vehicleId, p.componentId, p.name, p.value, p.type); } fclose(f); } void params_file_destroy(ParamsFile *pf) { for (int i = 0; i < pf->count; i++) { free(pf->parameters[i].vehicleId); free(pf->parameters[i].componentId); free(pf->parameters[i].name); free(pf->parameters[i].value); free(pf->parameters[i].type); } free(pf->parameters); free(pf->filename); free(pf); } // ===== end task-514 .PARAMS ===== // ===== task-515 .PAS [C++] ===== #include #include #include #include #include #include class PasFileHandler { private: std::string filename; public: PasFileHandler(const std::string& fn) : filename(fn) {} std::string read() { std::ifstream file(filename); if (!file) return ""; std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); return content; } void write(const std::string& content) { std::ofstream file(filename); if (file) file << content; } void printProperties() { struct stat st; if (stat(filename.c_str(), &st) == 0) { std::cout << "File Name: " << filename << std::endl; std::cout << "File Path: " << realpath(filename.c_str(), nullptr) << std::endl; std::cout << "File Size (bytes): " << st.st_size << std::endl; std::cout << "Creation Time: " << std::ctime(&st.st_ctime); std::cout << "Modification Time: " << std::ctime(&st.st_mtime); std::cout << "Access Time: " << std::ctime(&st.st_atime); std::cout << "Permissions: " << std::oct << (st.st_mode & 0777) << std::endl; std::cout << "Owner User ID: " << st.st_uid << std::endl; std::cout << "Group ID: " << st.st_gid << std::endl; std::cout << "Inode Number: " << st.st_ino << std::endl; std::cout << "Number of Hard Links: " << st.st_nlink << std::endl; std::cout << "Device ID: " << st.st_dev << std::endl; } else { std::cerr << "Error getting properties." << std::endl; } } }; // Example usage: // int main() { // PasFileHandler handler("example.pas"); // std::cout << handler.read() << std::endl; // handler.write("program Hello; begin writeln('Hello'); end."); // handler.printProperties(); // return 0; // } // ===== end task-515 .PAS ===== // ===== task-516 .PAX [C] ===== #include #include #include #include typedef struct { FILE *file; char *filename; char mode; // Global ext map would require a dict; simplified as empty for brevity } PaxFile; PaxFile* pax_open(const char *filename, char mode) { PaxFile *p = malloc(sizeof(PaxFile)); p->filename = strdup(filename); p->mode = mode; p->file = fopen(filename, mode == 'r' ? "rb" : "wb"); return p; } void pax_close(PaxFile *p) { fclose(p->file); free(p->filename); free(p); } struct Header { char name[100]; int mode; int uid; int gid; long size; long mtime; int chksum; char typeflag; char linkname[100]; char uname[32]; char gname[32]; int devmajor; int devminor; char prefix[155]; char path[256]; // ext as dict; simplified }; int parse_oct(const char *s, int len) { char buf[13]; strncpy(buf, s, len); buf[len] = '\0'; return (int)strtol(buf, NULL, 8); } struct Header* parse_ustar_header(char *data) { char magic[7]; strncpy(magic, data + 257, 6); magic[6] = '\0'; if (strcmp(magic, "ustar") != 0) return NULL; struct Header *h = malloc(sizeof(struct Header)); strncpy(h->name, data, 100); h->name[99] = '\0'; h->mode = parse_oct(data + 100, 8); h->uid = parse_oct(data + 108, 8); h->gid = parse_oct(data + 116, 8); h->size = parse_oct(data + 124, 12); h->mtime = parse_oct(data + 136, 12); h->chksum = parse_oct(data + 148, 8); h->typeflag = data[156]; strncpy(h->linkname, data + 157, 100); h->linkname[99] = '\0'; strncpy(h->uname, data + 265, 32); h->uname[31] = '\0'; strncpy(h->gname, data + 297, 32); h->gname[31] = '\0'; h->devmajor = parse_oct(data + 329, 8); h->devminor = parse_oct(data + 337, 8); strncpy(h->prefix, data + 345, 155); h->prefix[154] = '\0'; strcpy(h->path, h->prefix); if (strlen(h->prefix) > 0) strcat(h->path, "/"); strcat(h->path, h->name); return h; } // Parse extended; simplified, assume no ext for print void print_properties(struct Header *h) { printf("Path: %s\n", h->path); printf("Mode/Permissions: %o\n", h->mode); printf("UID: %d\n", h->uid); printf("GID: %d\n", h->gid); printf("Uname: %s\n", h->uname); printf("Gname: %s\n", h->gname); printf("Mtime: %ld\n", h->mtime); printf("Atime: N/A\n"); printf("Size: %ld\n", h->size); printf("Type: %c\n", h->typeflag); printf("Linkname: %s\n", h->linkname); printf("Devmajor: %d\n", h->devmajor); printf("Devminor: %d\n", h->devminor); printf("Charset: UTF-8\n"); printf("Comment: N/A\n"); printf("Checksum: %d\n\n", h->chksum); } void pax_read_properties(PaxFile *p) { long offset = 0; while (1) { fseek(p->file, offset, SEEK_SET); char header_data[512]; if (fread(header_data, 512, 1, p->file) < 1) break; if (header_data[0] == 0 && header_data[1] == 0) break; struct Header *h = parse_ustar_header(header_data); if (!h) break; if (h->typeflag == 'g' || h->typeflag == 'x') { // Read ext data, parse; simplified skip offset += 512 + ((h->size + 511) / 512 * 512); free(h); continue; } print_properties(h); offset += 512 + ((h->size + 511) / 512 * 512); free(h); } } // Write simplified void pax_write_simple_archive(PaxFile *p, const char *path, const char *content) { // Create header, write; simplified } // Example // PaxFile *pax = pax_open("example.pax", 'r'); // pax_read_properties(pax); // pax_close(pax); // ===== end task-516 .PAX ===== // ===== task-517 .PBLIB [C] ===== #include #include #include #include #include typedef struct { char* filepath; } PBLIBHandler; void init(PBLIBHandler* handler, char* filepath) { handler->filepath = filepath; } void open_and_read(PBLIBHandler* handler) { FILE* f = fopen(handler->filepath, "rb"); if (!f) { printf("File not found.\n"); return; } fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); unsigned char* content = malloc(size); fread(content, 1, size, f); fclose(f); struct stat st; stat(handler->filepath, &st); char* filename = strrchr(handler->filepath, '/') ? strrchr(handler->filepath, '/') + 1 : handler->filepath; printf("File Name: %s\n", filename); printf("File Size: %ld bytes\n", size); char timebuf[26]; ctime_r(&st.st_mtime, timebuf); printf("Last Modified: %s", timebuf); printf("File Type: PowerBASIC Library (proprietary binary)\n"); // Placeholder: No specs printf("Contained SLL Modules: Unknown (no format specs available)\n"); printf("Binary Preview (first 100 bytes): "); for (int i = 0; i < 100 && i < size; i++) { printf("%02X ", content[i]); } printf("\n"); free(content); } void write(PBLIBHandler* handler, unsigned char* new_content, long new_size) { FILE* f = fopen(handler->filepath, "wb"); if (f) { fwrite(new_content, 1, new_size, f); fclose(f); printf("File overwritten (no .PBLIB-specific encoding applied).\n"); } } // Example usage: // int main() { // PBLIBHandler handler; // init(&handler, "example.pblib"); // open_and_read(&handler); // return 0; // } // ===== end task-517 .PBLIB ===== // ===== task-518 .PBM [C++] ===== #include #include #include #include #include class PBMFile { private: std::string magic; std::vector comments; int width; int height; std::vector data; // For pixel data public: PBMFile() : width(0), height(0) {} PBMFile(const std::string& filepath) : PBMFile() { read(filepath); } void read(const std::string& filepath) { std::ifstream file(filepath, std::ios::binary); if (!file) throw std::runtime_error("Cannot open file"); std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); std::istringstream iss(content); std::string line; std::getline(iss, line); magic = line; while (std::getline(iss, line)) { if (line[0] == '#') { comments.push_back(line.substr(1)); } else { std::istringstream dimiss(line); dimiss >> width >> height; break; } } // Data is remaining content auto pos = iss.tellg(); data.assign(content.begin() + pos, content.end()); } void printProperties() const { std::cout << "Magic Number: " << magic << std::endl; std::cout << "Comments: "; if (comments.empty()) { std::cout << "None" << std::endl; } else { for (const auto& comment : comments) { std::cout << comment << std::endl; } } std::cout << "Width: " << width << std::endl; std::cout << "Height: " << height << std::endl; } void write(const std::string& filepath) const { if (magic.empty() || width == 0 || height == 0 || data.empty()) { throw std::runtime_error("Missing properties or data"); } std::ofstream file(filepath, std::ios::binary); file << magic << "\n"; for (const auto& comment : comments) { file << "#" << comment << "\n"; } file << width << " " << height << "\n"; file.write(data.data(), data.size()); } }; // Example usage: // int main() { // PBMFile pbm("sample.pbm"); // pbm.printProperties(); // pbm.write("output.pbm"); // return 0; // } // ===== end task-518 .PBM ===== // ===== task-519 .PBO [C] ===== #include #include #include #include #include typedef struct { char* key; char* value; } Extension; typedef struct { char* filename; uint32_t packing_method; uint32_t original_size; uint32_t reserved; uint32_t timestamp; uint32_t data_size; uint8_t* data; } PBOFile; typedef struct { Extension* extensions; size_t ext_count; PBOFile* files; size_t file_count; } PBOHandler; PBOHandler* pbo_create() { PBOHandler* pbo = malloc(sizeof(PBOHandler)); pbo->extensions = NULL; pbo->ext_count = 0; pbo->files = NULL; pbo->file_count = 0; return pbo; } void pbo_destroy(PBOHandler* pbo) { for (size_t i = 0; i < pbo->ext_count; i++) { free(pbo->extensions[i].key); free(pbo->extensions[i].value); } free(pbo->extensions); for (size_t i = 0; i < pbo->file_count; i++) { free(pbo->files[i].filename); free(pbo->files[i].data); } free(pbo->files); free(pbo); } char* read_asciiz(const uint8_t* data, size_t* offset) { size_t start = *offset; while (data[*offset] != 0) (*offset)++; char* str = strndup((char*)&data[start], *offset - start); (*offset)++; return str; } uint32_t unpack_ulong(const uint8_t* data, size_t* offset) { uint32_t val = *(uint32_t*)&data[*offset]; *offset += 4; return val; } void pbo_open(PBOHandler* pbo, const char* filepath) { FILE* f = fopen(filepath, "rb"); fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); size_t offset = 0; int is_header_extension = 0; while (1) { char* filename = read_asciiz(data, &offset); uint32_t packing_method = unpack_ulong(data, &offset); uint32_t original_size = unpack_ulong(data, &offset); uint32_t reserved = unpack_ulong(data, &offset); uint32_t timestamp = unpack_ulong(data, &offset); uint32_t data_size = unpack_ulong(data, &offset); if (strlen(filename) == 0 && packing_method == 0 && original_size == 0 && reserved == 0 && timestamp == 0 && data_size == 0) { free(filename); break; } if (packing_method == 0x56657273) { is_header_extension = 1; free(filename); continue; } if (is_header_extension) { while (1) { char* key = read_asciiz(data, &offset); if (strlen(key) == 0) { free(key); break; } char* value = read_asciiz(data, &offset); pbo->extensions = realloc(pbo->extensions, sizeof(Extension) * (pbo->ext_count + 1)); pbo->extensions[pbo->ext_count].key = key; pbo->extensions[pbo->ext_count].value = value; pbo->ext_count++; } is_header_extension = 0; free(filename); continue; } uint8_t* file_data = malloc(data_size); memcpy(file_data, &data[offset], data_size); offset += data_size; pbo->files = realloc(pbo->files, sizeof(PBOFile) * (pbo->file_count + 1)); pbo->files[pbo->file_count].filename = filename; pbo->files[pbo->file_count].packing_method = packing_method; pbo->files[pbo->file_count].original_size = original_size; pbo->files[pbo->file_count].reserved = reserved; pbo->files[pbo->file_count].timestamp = timestamp; pbo->files[pbo->file_count].data_size = data_size; pbo->files[pbo->file_count].data = file_data; pbo->file_count++; } free(data); } void pbo_print_properties(const PBOHandler* pbo) { printf("Header Extensions:\n"); for (size_t i = 0; i < pbo->ext_count; i++) { printf("%s: %s\n", pbo->extensions[i].key, pbo->extensions[i].value); } printf("\nFiles:\n"); for (size_t i = 0; i < pbo->file_count; i++) { PBOFile f = pbo->files[i]; time_t ts = f.timestamp; char timebuf[80]; strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M:%S", gmtime(&ts)); printf("Filename: %s\n", f.filename); printf("Packing Method: 0x%08x\n", f.packing_method); printf("Original Size: %u\n", f.original_size); printf("Reserved: %u\n", f.reserved); printf("Timestamp: %s\n", timebuf); printf("Data Size: %u\n\n", f.data_size); } } void pbo_write(const PBOHandler* pbo, const char* filepath) { FILE* f = fopen(filepath, "wb"); // Product entry if (pbo->ext_count > 0) { fputc(0, f); fwrite(&(uint32_t){0x56657273}, 4, 1, f); uint32_t zero = 0; fwrite(&zero, 4, 1, f); fwrite(&zero, 4, 1, f); fwrite(&zero, 4, 1, f); fwrite(&zero, 4, 1, f); for (size_t i = 0; i < pbo->ext_count; i++) { fwrite(pbo->extensions[i].key, strlen(pbo->extensions[i].key) + 1, 1, f); fwrite(pbo->extensions[i].value, strlen(pbo->extensions[i].value) + 1, 1, f); } fputc(0, f); } // File entries for (size_t i = 0; i < pbo->file_count; i++) { PBOFile file = pbo->files[i]; fwrite(file.filename, strlen(file.filename) + 1, 1, f); fwrite(&file.packing_method, 4, 1, f); fwrite(&file.original_size, 4, 1, f); fwrite(&file.reserved, 4, 1, f); fwrite(&file.timestamp, 4, 1, f); fwrite(&file.data_size, 4, 1, f); } // Terminating fputc(0, f); uint32_t zero = 0; fwrite(&zero, 4, 1, f); fwrite(&zero, 4, 1, f); fwrite(&zero, 4, 1, f); fwrite(&zero, 4, 1, f); fwrite(&zero, 4, 1, f); // Data for (size_t i = 0; i < pbo->file_count; i++) { fwrite(pbo->files[i].data, pbo->files[i].data_size, 1, f); } fclose(f); } // Example int main() { PBOHandler* pbo = pbo_create(); pbo_open(pbo, "example.pbo"); pbo_print_properties(pbo); pbo_write(pbo, "new.pbo"); pbo_destroy(pbo); return 0; } // ===== end task-519 .PBO ===== // ===== task-520 .PBO [C] ===== #include #include #include #include #include // For SHA1, link with -lssl -lcrypto typedef struct { char* filename; unsigned int packing; unsigned int origSize; unsigned int reserved; unsigned int timestamp; unsigned int dataSize; } FileEntry; typedef struct { char** keys; char** values; int propCount; FileEntry* files; int fileCount; unsigned char* signature; // 20 bytes or NULL } PBOHandler; PBOHandler* pbo_create() { PBOHandler* pbo = malloc(sizeof(PBOHandler)); pbo->propCount = 0; pbo->keys = NULL; pbo->values = NULL; pbo->fileCount = 0; pbo->files = NULL; pbo->signature = NULL; return pbo; } void pbo_free(PBOHandler* pbo) { for (int i = 0; i < pbo->propCount; i++) { free(pbo->keys[i]); free(pbo->values[i]); } free(pbo->keys); free(pbo->values); for (int i = 0; i < pbo->fileCount; i++) { free(pbo->files[i].filename); } free(pbo->files); free(pbo->signature); free(pbo); } char* read_null_string(FILE* f) { char* str = malloc(256); int len = 0; char c; while (fread(&c, 1, 1, f) && c != 0) { str[len++] = c; } str[len] = 0; return realloc(str, len + 1); } void pbo_open(PBOHandler* pbo, const char* filepath) { FILE* f = fopen(filepath, "rb"); fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); while (true) { char* filename = read_null_string(f); unsigned int packing, origSize, reserved, timestamp, dataSize; fread(&packing, 4, 1, f); fread(&origSize, 4, 1, f); fread(&reserved, 4, 1, f); fread(×tamp, 4, 1, f); fread(&dataSize, 4, 1, f); if (strlen(filename) == 0 && packing == 0 && origSize == 0 && reserved == 0 && timestamp == 0 && dataSize == 0) { free(filename); break; } if (packing == 0x56657273) { while (true) { char* key = read_null_string(f); if (strlen(key) == 0) { free(key); break; } char* value = read_null_string(f); pbo->keys = realloc(pbo->keys, sizeof(char*) * (pbo->propCount + 1)); pbo->values = realloc(pbo->values, sizeof(char*) * (pbo->propCount + 1)); pbo->keys[pbo->propCount] = key; pbo->values[pbo->propCount] = value; pbo->propCount++; } } else { pbo->files = realloc(pbo->files, sizeof(FileEntry) * (pbo->fileCount + 1)); pbo->files[pbo->fileCount].filename = filename; pbo->files[pbo->fileCount].packing = packing; pbo->files[pbo->fileCount].origSize = origSize; pbo->files[pbo->fileCount].reserved = reserved; pbo->files[pbo->fileCount].timestamp = timestamp; pbo->files[pbo->fileCount].dataSize = dataSize; pbo->fileCount++; } } // Signature fseek(f, -21, SEEK_END); unsigned char zero; fread(&zero, 1, 1, f); if (zero == 0) { pbo->signature = malloc(20); fread(pbo->signature, 20, 1, f); } fclose(f); } void pbo_print_properties(PBOHandler* pbo) { printf("Package Properties:\n"); for (int i = 0; i < pbo->propCount; i++) { printf("%s: %s\n", pbo->keys[i], pbo->values[i]); } printf("\nFile Properties:\n"); for (int i = 0; i < pbo->fileCount; i++) { FileEntry fe = pbo->files[i]; printf("Filename: %s\n", fe.filename); printf("PackingMethod: 0x%08X\n", fe.packing); printf("OriginalSize: %u\n", fe.origSize); printf("Reserved: %u\n", fe.reserved); time_t ts = fe.timestamp; printf("Timestamp: %s", ctime(&ts)); printf("DataSize: %u\n", fe.dataSize); printf("---\n"); } printf("Signature: "); if (pbo->signature) { for (int i = 0; i < 20; i++) { printf("%02x", pbo->signature[i]); } printf("\n"); } else { printf("None\n"); } } typedef struct { char* filename; unsigned char* data; size_t dataLen; unsigned int timestamp; int compress; } WriteFileData; void pbo_write(PBOHandler* pbo, const char* filepath, WriteFileData* filesData, int numFiles, int addSignature) { FILE* f = fopen(filepath, "wb"); if (pbo->propCount > 0) { fputc(0, f); unsigned int vers = 0x56657273; fwrite(&vers, 4, 1, f); unsigned int zero = 0; fwrite(&zero, 4, 1, f); fwrite(&zero, 4, 1, f); fwrite(&zero, 4, 1, f); fwrite(&zero, 4, 1, f); for (int i = 0; i < pbo->propCount; i++) { fwrite(pbo->keys[i], strlen(pbo->keys[i]), 1, f); fputc(0, f); fwrite(pbo->values[i], strlen(pbo->values[i]), 1, f); fputc(0, f); } fputc(0, f); } pbo->fileCount = numFiles; pbo->files = malloc(sizeof(FileEntry) * numFiles); for (int i = 0; i < numFiles; i++) { WriteFileData fd = filesData[i]; fwrite(fd.filename, strlen(fd.filename), 1, f); fputc(0, f); unsigned int packing = fd.compress ? 0x43707273 : 0; unsigned int origSize = fd.dataLen; unsigned int reserved = 0; unsigned int timestamp = fd.timestamp; unsigned int dataSize = fd.dataLen; // Compress if needed fwrite(&packing, 4, 1, f); fwrite(&origSize, 4, 1, f); fwrite(&reserved, 4, 1, f); fwrite(×tamp, 4, 1, f); fwrite(&dataSize, 4, 1, f); pbo->files[i].filename = strdup(fd.filename); pbo->files[i].packing = packing; pbo->files[i].origSize = origSize; pbo->files[i].reserved = reserved; pbo->files[i].timestamp = timestamp; pbo->files[i].dataSize = dataSize; } unsigned int zero = 0; fputc(0, f); fwrite(&zero, 4, 1, f); fwrite(&zero, 4, 1, f); fwrite(&zero, 4, 1, f); fwrite(&zero, 4, 1, f); fwrite(&zero, 4, 1, f); // Write data for (int i = 0; i < numFiles; i++) { fwrite(filesData[i].data, filesData[i].dataLen, 1, f); } if (addSignature) { // To compute SHA1, need to hash the content up to here, then append // For simplicity, close, read back, hash, append fclose(f); f = fopen(filepath, "rb"); fseek(f, 0, SEEK_END); long contentSize = ftell(f); fseek(f, 0, SEEK_SET); unsigned char* content = malloc(contentSize); fread(content, contentSize, 1, f); fclose(f); unsigned char hash[SHA_DIGEST_LENGTH]; SHA1(content, contentSize, hash); free(content); f = fopen(filepath, "ab"); fputc(0, f); fwrite(hash, SHA_DIGEST_LENGTH, 1, f); pbo->signature = malloc(SHA_DIGEST_LENGTH); memcpy(pbo->signature, hash, SHA_DIGEST_LENGTH); fclose(f); } else { fclose(f); } } // Example int main() { PBOHandler* pbo = pbo_create(); pbo_open(pbo, "example.pbo"); pbo_print_properties(pbo); // Add properties for write pbo->propCount = 1; pbo->keys = malloc(sizeof(char*)); pbo->values = malloc(sizeof(char*)); pbo->keys[0] = strdup("prefix"); pbo->values[0] = strdup("test"); WriteFileData fd = { .filename = "test.txt", .data = (unsigned char*)"content", .dataLen = 7, .timestamp = time(NULL), .compress = 0 }; pbo_write(pbo, "new.pbo", &fd, 1, 1); pbo_free(pbo); return 0; } // ===== end task-520 .PBO ===== // ===== task-521 .PCD [C++] ===== #include #include #include #include #include #include class PCLParser { private: std::map properties; std::string data; public: PCLParser(const std::string& filepath = "") { if (!filepath.empty()) { read(filepath); } } void read(const std::string& filepath) { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file" << std::endl; return; } std::string line; std::vector header_lines; while (std::getline(file, line)) { if (line.find("DATA") == 0) { header_lines.push_back(line); break; } if (!line.empty() && line[0] != '#') { header_lines.push_back(line); } } for (const auto& hline : header_lines) { std::istringstream iss(hline); std::string key; iss >> key; std::string value; std::getline(iss, value); properties[key] = value.erase(0, 1); // Remove leading space } std::ostringstream data_ss; while (std::getline(file, line)) { data_ss << line << "\n"; } data = data_ss.str(); file.close(); } void printProperties() const { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& output_filepath, const std::map& new_properties = {}) { if (!new_properties.empty()) { for (const auto& np : new_properties) { properties[np.first] = np.second; } } std::ofstream file(output_filepath); if (!file.is_open()) { std::cerr << "Error opening output file" << std::endl; return; } std::vector keys = {"VERSION", "FIELDS", "SIZE", "TYPE", "COUNT", "WIDTH", "HEIGHT", "VIEWPOINT", "POINTS", "DATA"}; for (const auto& key : keys) { if (properties.find(key) != properties.end()) { file << key << " " << properties.at(key) << "\n"; } } file << data; file.close(); } }; // Example usage: // int main() { // PCLParser parser("example.pcl"); // parser.printProperties(); // parser.write("new.pcl"); // return 0; // } // ===== end task-521 .PCD ===== // ===== task-522 .PCS [C] ===== #include #include #include #include #define MAX_LINE 1024 #define MAX_SAMPLES 1000 // Arbitrary max per line struct PcsEntry { int channel; double delta_t; double *samples; int num_samples; }; struct PcsFile { char *filename; struct PcsEntry *entries; int num_entries; }; struct PcsFile *pcs_create(const char *filename) { struct PcsFile *pcs = malloc(sizeof(struct PcsFile)); pcs->filename = strdup(filename); pcs->entries = NULL; pcs->num_entries = 0; return pcs; } void pcs_read(struct PcsFile *pcs) { FILE *f = fopen(pcs->filename, "r"); if (!f) return; char line[MAX_LINE]; while (fgets(line, MAX_LINE, f)) { char *token = strtok(line, " \t\n"); if (token) { double first = atof(token); int channel = floor(first); double delta_t = first - channel; struct PcsEntry entry; entry.channel = channel; entry.delta_t = delta_t; entry.samples = malloc(sizeof(double) * MAX_SAMPLES); entry.num_samples = 0; while ((token = strtok(NULL, " \t\n")) && entry.num_samples < MAX_SAMPLES) { entry.samples[entry.num_samples++] = atof(token); } pcs->entries = realloc(pcs->entries, sizeof(struct PcsEntry) * (pcs->num_entries + 1)); pcs->entries[pcs->num_entries++] = entry; } } fclose(f); } void pcs_print_properties(struct PcsFile *pcs) { for (int i = 0; i < pcs->num_entries; i++) { struct PcsEntry entry = pcs->entries[i]; printf("Channel: %d, Delta-T: %.2f ns, Samples: [", entry.channel, entry.delta_t); for (int j = 0; j < entry.num_samples; j++) { printf("%.6f", entry.samples[j]); if (j < entry.num_samples - 1) printf(", "); } printf("]\n"); } } void pcs_write(struct PcsFile *pcs) { FILE *f = fopen(pcs->filename, "w"); if (!f) return; for (int i = 0; i < pcs->num_entries; i++) { struct PcsEntry entry = pcs->entries[i]; double first = entry.channel + entry.delta_t; fprintf(f, "%.2f ", first); for (int j = 0; j < entry.num_samples; j++) { fprintf(f, "%.6f ", entry.samples[j]); } fprintf(f, "\n"); } fclose(f); } void pcs_destroy(struct PcsFile *pcs) { for (int i = 0; i < pcs->num_entries; i++) { free(pcs->entries[i].samples); } free(pcs->entries); free(pcs->filename); free(pcs); } // Example usage: // int main() { // struct PcsFile *pcs = pcs_create("example.pcs"); // pcs_read(pcs); // pcs_print_properties(pcs); // // To write, modify pcs->entries and call pcs_write(pcs); // pcs_destroy(pcs); // return 0; // } // ===== end task-522 .PCS ===== // ===== task-523 .PCX [C] ===== #include #include #include #include typedef struct { uint8_t manufacturer; uint8_t version; uint8_t encoding; uint8_t bits_per_plane; uint16_t x_min; uint16_t y_min; uint16_t x_max; uint16_t y_max; uint16_t horz_dpi; uint16_t vert_dpi; uint8_t palette[48]; uint8_t reserved; uint8_t color_planes; uint16_t bytes_per_plane_line; uint16_t palette_info; uint16_t hor_scr_size; uint16_t ver_scr_size; uint8_t padding[54]; } PCXHeader; void read_pcx(const char* filename, PCXHeader* header, uint8_t** image_data, size_t* image_size) { FILE* file = fopen(filename, "rb"); if (!file) { perror("Failed to open file"); exit(1); } if (fread(header, sizeof(PCXHeader), 1, file) != 1) { fprintf(stderr, "Invalid PCX file: header too short\n"); fclose(file); exit(1); } // Adjust for little-endian if needed (assuming host is little-endian) fseek(file, 0, SEEK_END); long total_size = ftell(file); *image_size = total_size - 128; rewind(file); fseek(file, 128, SEEK_SET); *image_data = malloc(*image_size); if (*image_data && fread(*image_data, 1, *image_size, file) != *image_size) { free(*image_data); *image_data = NULL; } fclose(file); } void print_properties(const PCXHeader* header) { printf("Manufacturer: %u\n", header->manufacturer); printf("Version: %u\n", header->version); printf("Encoding: %u\n", header->encoding); printf("BitsPerPlane: %u\n", header->bits_per_plane); printf("WindowXmin: %u\n", header->x_min); printf("WindowYmin: %u\n", header->y_min); printf("WindowXmax: %u\n", header->x_max); printf("WindowYmax: %u\n", header->y_max); printf("HorzDPI: %u\n", header->horz_dpi); printf("VertDPI: %u\n", header->vert_dpi); printf("Palette: "); for (int i = 0; i < 48; i++) printf("%u ", header->palette[i]); printf("\n"); printf("Reserved: %u\n", header->reserved); printf("ColorPlanes: %u\n", header->color_planes); printf("BytesPerPlaneLine: %u\n", header->bytes_per_plane_line); printf("PaletteInfo: %u\n", header->palette_info); printf("HorScrSize: %u\n", header->hor_scr_size); printf("VerScrSize: %u\n", header->ver_scr_size); // Derived uint16_t width = header->x_max - header->x_min + 1; uint16_t height = header->y_max - header->y_min + 1; uint16_t color_depth = header->color_planes * header->bits_per_plane; printf("Width (derived): %u\n", width); printf("Height (derived): %u\n", height); printf("ColorDepth (derived): %u\n", color_depth); } void write_pcx(const char* output_filename, const PCXHeader* header, const uint8_t* image_data, size_t image_size) { FILE* file = fopen(output_filename, "wb"); if (!file) { perror("Failed to open output file"); exit(1); } fwrite(header, sizeof(PCXHeader), 1, file); if (image_data) { fwrite(image_data, 1, image_size, file); } fclose(file); } // Example usage: // int main() { // PCXHeader header; // uint8_t* image_data = NULL; // size_t image_size = 0; // read_pcx("input.pcx", &header, &image_data, &image_size); // print_properties(&header); // write_pcx("output.pcx", &header, image_data, image_size); // free(image_data); // return 0; // } // ===== end task-523 .PCX ===== // ===== task-524 .PDB [C] ===== #include #include #include #include typedef struct { char fileMagic[32]; uint32_t blockSize; uint32_t freeBlockMapBlock; uint32_t numBlocks; uint32_t numDirectoryBytes; uint32_t unknown; uint32_t blockMapAddr; } PDBProperties; typedef struct { char* filename; PDBProperties properties; } PDBHandler; PDBHandler* createPDBHandler(const char* filename) { PDBHandler* handler = (PDBHandler*)malloc(sizeof(PDBHandler)); handler->filename = strdup(filename); return handler; } void readAndDecode(PDBHandler* handler) { FILE* fp = fopen(handler->filename, "rb"); if (!fp) { perror("Failed to open file"); return; } fread(handler->properties.fileMagic, 1, 32, fp); fread(&handler->properties.blockSize, sizeof(uint32_t), 1, fp); fread(&handler->properties.freeBlockMapBlock, sizeof(uint32_t), 1, fp); fread(&handler->properties.numBlocks, sizeof(uint32_t), 1, fp); fread(&handler->properties.numDirectoryBytes, sizeof(uint32_t), 1, fp); fread(&handler->properties.unknown, sizeof(uint32_t), 1, fp); fread(&handler->properties.blockMapAddr, sizeof(uint32_t), 1, fp); fclose(fp); } void printProperties(PDBHandler* handler) { printf("FileMagic: %.32s\n", handler->properties.fileMagic); printf("BlockSize: %u\n", handler->properties.blockSize); printf("FreeBlockMapBlock: %u\n", handler->properties.freeBlockMapBlock); printf("NumBlocks: %u\n", handler->properties.numBlocks); printf("NumDirectoryBytes: %u\n", handler->properties.numDirectoryBytes); printf("Unknown: %u\n", handler->properties.unknown); printf("BlockMapAddr: %u\n", handler->properties.blockMapAddr); } void writeProperties(PDBHandler* handler, const char* outputFilename) { if (!outputFilename) { outputFilename = "modified.pdb"; // Default } FILE* inFp = fopen(handler->filename, "rb"); if (!inFp) { perror("Failed to open input file"); return; } fseek(inFp, 0, SEEK_END); long fileSize = ftell(inFp); fseek(inFp, 0, SEEK_SET); char* data = (char*)malloc(fileSize); fread(data, 1, fileSize, inFp); fclose(inFp); memcpy(data, handler->properties.fileMagic, 32); memcpy(data + 32, &handler->properties.blockSize, sizeof(uint32_t)); memcpy(data + 36, &handler->properties.freeBlockMapBlock, sizeof(uint32_t)); memcpy(data + 40, &handler->properties.numBlocks, sizeof(uint32_t)); memcpy(data + 44, &handler->properties.numDirectoryBytes, sizeof(uint32_t)); memcpy(data + 48, &handler->properties.unknown, sizeof(uint32_t)); memcpy(data + 52, &handler->properties.blockMapAddr, sizeof(uint32_t)); FILE* outFp = fopen(outputFilename, "wb"); if (!outFp) { perror("Failed to open output file"); free(data); return; } fwrite(data, 1, fileSize, outFp); fclose(outFp); free(data); printf("Properties written to %s\n", outputFilename); } void destroyPDBHandler(PDBHandler* handler) { free(handler->filename); free(handler); } // Example usage: // int main() { // PDBHandler* handler = createPDBHandler("example.pdb"); // readAndDecode(handler); // printProperties(handler); // handler->properties.unknown = 42; // Modify // writeProperties(handler, NULL); // destroyPDBHandler(handler); // return 0; // } // ===== end task-524 .PDB ===== // ===== task-525 .PDE [C++] ===== #include #include #include #include #include #include class PdeFileHandler { public: char* filepath; struct stat fileStat; PdeFileHandler(const char* fp) { filepath = strdup(fp); if (stat(filepath, &fileStat) != 0) { perror("stat failed"); exit(1); } } ~PdeFileHandler() { free(filepath); } void printProperties() { printf("File Name: %s\n", strrchr(filepath, '/') ? strrchr(filepath, '/') + 1 : filepath); printf("File Path: %s\n", filepath); printf("File Size: %ld bytes\n", fileStat.st_size); printf("Creation Time: %s", ctime(&fileStat.st_ctime)); printf("Modification Time: %s", ctime(&fileStat.st_mtime)); printf("Access Time: %s", ctime(&fileStat.st_atime)); printf("Permissions: %o\n", fileStat.st_mode & 0777); printf("Owner UID: %d\n", fileStat.st_uid); printf("Group GID: %d\n", fileStat.st_gid); printf("Inode Number: %ld\n", fileStat.st_ino); printf("Number of Hard Links: %ld\n", fileStat.st_nlink); printf("Device ID: %ld\n", fileStat.st_dev); } char* readContent() { FILE* file = fopen(filepath, "r"); if (!file) { perror("fopen failed"); return NULL; } fseek(file, 0, SEEK_END); long size = ftell(file); fseek(file, 0, SEEK_SET); char* content = (char*)malloc(size + 1); fread(content, 1, size, file); content[size] = '\0'; fclose(file); return content; } void writeContent(const char* content) { FILE* file = fopen(filepath, "w"); if (!file) { perror("fopen failed"); return; } fprintf(file, "%s", content); fclose(file); } }; // Example usage // int main() { // PdeFileHandler handler("example.pde"); // handler.printProperties(); // char* content = handler.readContent(); // if (content) { // handler.writeContent("void setup() {}"); // free(content); // } // return 0; // } // ===== end task-525 .PDE ===== // ===== task-526 .PDF [C++] ===== #include #include #include #include #include #include class PDFHandler { private: std::string filepath; std::string data; std::map properties; // Simplified to string values for demo public: PDFHandler(const std::string& fp) : filepath(fp) { load(); } void load() { std::ifstream file(filepath, std::ios::binary); if (file) { std::ostringstream oss; oss << file.rdbuf(); data = oss.str(); parseProperties(); } } void parseProperties() { // Header std::regex headerRegex(R"(%PDF-(\d\.\d))"); std::smatch match; if (std::regex_search(data, match, headerRegex)) { properties["Magic Signature"] = "%PDF-"; properties["Version"] = match[1].str(); } else { properties["Version"] = "Unknown"; } // Startxref size_t startxrefPos = data.rfind("startxref"); if (startxrefPos != std::string::npos) { std::regex numRegex(R"(\d+)"); std::sregex_iterator iter(data.begin() + startxrefPos + 9, data.end(), numRegex); if (iter != std::sregex_iterator()) { properties["Startxref"] = (*iter)[0].str(); } } // Trailer size_t trailerStart = data.rfind("trailer"); size_t eofPos = data.rfind("%%EOF"); if (trailerStart != std::string::npos && eofPos != std::string::npos) { std::string trailerText = data.substr(trailerStart + 7, eofPos - trailerStart - 7); std::regex dictRegex(R"(<<\s*(.*?)>>\s*)", std::regex::dotall); if (std::regex_search(trailerText, match, dictRegex)) { std::string dictContent = match[1].str(); std::regex entryRegex(R"(/(\w+)\s+([^\s/]+))"); std::sregex_iterator entryIter(dictContent.begin(), dictContent.end(), entryRegex); std::string trailerProps; for (; entryIter != std::sregex_iterator(); ++entryIter) { trailerProps += (*entryIter)[1].str() + ": " + (*entryIter)[2].str() + ", "; } properties["Trailer Properties"] = trailerProps; } } // Xref type properties["Xref Type"] = (data.find("xref") != std::string::npos) ? "Table" : ((data.find("/XRef") != std::string::npos) ? "Stream" : "Unknown"); } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& newFilepath, const std::map& updates) { std::string modifiedData = data; if (updates.find("version") != updates.end()) { std::regex versionRegex(R"(%PDF-\d\.\d)"); modifiedData = std::regex_replace(modifiedData, versionRegex, "%PDF-" + updates.at("version"), std::regex_constants::format_first_only); } std::ofstream outFile(newFilepath, std::ios::binary); outFile << modifiedData; } }; // Example usage: // int main() { // PDFHandler handler("sample.pdf"); // handler.printProperties(); // std::map updates = {{"version", "1.5"}}; // handler.write("modified.pdf", updates); // return 0; // } // ===== end task-526 .PDF ===== // ===== task-527 .PDI [C] ===== #include #include #include #define MAX_LINE 1024 #define MAX_PROPS 10 #define MAX_PAGES 100 #define MAX_FIELDS 100 typedef struct { char *keys[MAX_PROPS]; char *values[MAX_PROPS]; int prop_count; char *page_numbers[MAX_PAGES]; char **fields[MAX_PAGES]; int field_counts[MAX_PAGES]; int page_count; } PDIHandler; void init_PDIHandler(PDIHandler *handler) { handler->prop_count = 0; handler->page_count = 0; memset(handler->field_counts, 0, sizeof(handler->field_counts)); } void read_PDI(PDIHandler *handler, const char *filepath) { FILE *f = fopen(filepath, "r"); if (!f) { printf("Error opening file.\n"); return; } char line[MAX_LINE]; char *current_page = NULL; while (fgets(line, MAX_LINE, f)) { if (line[0] == '~') { char *key = strtok(line + 1, "="); char *value = strtok(NULL, "\n"); if (key && value) { key = strdup(key); value = strdup(value); if (strcmp(key, "Page") == 0) { current_page = value; handler->page_numbers[handler->page_count] = current_page; handler->fields[handler->page_count] = malloc(MAX_FIELDS * sizeof(char*)); handler->field_counts[handler->page_count] = 0; handler->page_count++; } else if (strstr(key, "FieldName")) { if (current_page) { char *field = malloc(strlen(key) + strlen(value) + 3); sprintf(field, "%s: %s", key, value); handler->fields[handler->page_count - 1][handler->field_counts[handler->page_count - 1]] = field; handler->field_counts[handler->page_count - 1]++; } free(key); free(value); } else { handler->keys[handler->prop_count] = key; handler->values[handler->prop_count] = value; handler->prop_count++; } } } } fclose(f); } void print_PDI(PDIHandler *handler) { printf("PDI Properties:\n"); for (int i = 0; i < handler->prop_count; i++) { printf("%s: %s\n", handler->keys[i], handler->values[i]); } for (int p = 0; p < handler->page_count; p++) { printf("Page %s:\n", handler->page_numbers[p]); for (int f = 0; f < handler->field_counts[p]; f++) { printf(" %s\n", handler->fields[p][f]); } } } void write_PDI(PDIHandler *handler, const char *filepath) { FILE *f = fopen(filepath, "w"); if (!f) { printf("Error writing file.\n"); return; } for (int i = 0; i < handler->prop_count; i++) { fprintf(f, "~%s=%s\n", handler->keys[i], handler->values[i]); } for (int p = 0; p < handler->page_count; p++) { fprintf(f, "~Page=%s\n", handler->page_numbers[p]); for (int f = 0; f < handler->field_counts[p]; f++) { fprintf(f, "~%s\n", handler->fields[p][f]); } } fclose(f); } void free_PDIHandler(PDIHandler *handler) { for (int i = 0; i < handler->prop_count; i++) { free(handler->keys[i]); free(handler->values[i]); } for (int p = 0; p < handler->page_count; p++) { for (int f = 0; f < handler->field_counts[p]; f++) { free(handler->fields[p][f]); } free(handler->fields[p]); free(handler->page_numbers[p]); } } int main() { PDIHandler handler; init_PDIHandler(&handler); read_PDI(&handler, "example.pdi"); print_PDI(&handler); // To write: write_PDI(&handler, "new.pdi"); free_PDIHandler(&handler); return 0; } // ===== end task-527 .PDI ===== // ===== task-528 .PDM [C] ===== #include #include #include #include typedef struct { char *magic; char **comments; size_t num_comments; uint32_t width; uint32_t height; float *depths; } PdmImage; typedef struct { char *filepath; PdmImage *images; size_t num_images; } PdmFile; PdmFile* pdm_create(const char *filepath) { PdmFile *pdm = malloc(sizeof(PdmFile)); pdm->filepath = strdup(filepath); pdm->images = NULL; pdm->num_images = 0; return pdm; } void pdm_destroy(PdmFile *pdm) { for (size_t i = 0; i < pdm->num_images; i++) { free(pdm->images[i].magic); for (size_t j = 0; j < pdm->images[i].num_comments; j++) { free(pdm->images[i].comments[j]); } free(pdm->images[i].comments); free(pdm->images[i].depths); } free(pdm->images); free(pdm->filepath); free(pdm); } int pdm_read(PdmFile *pdm) { FILE *f = fopen(pdm->filepath, "rb"); if (!f) return -1; fseek(f, 0, SEEK_END); long file_size = ftell(f); fseek(f, 0, SEEK_SET); char *data = malloc(file_size); fread(data, 1, file_size, f); fclose(f); size_t offset = 0; while (offset < (size_t) file_size) { pdm->images = realloc(pdm->images, (pdm->num_images + 1) * sizeof(PdmImage)); PdmImage *image = &pdm->images[pdm->num_images]; image->comments = NULL; image->num_comments = 0; image->depths = NULL; // Read magic char *magic_start = data + offset; char *magic_end = strchr(magic_start, '\n'); if (!magic_end) { free(data); return -1; } size_t magic_len = magic_end - magic_start; image->magic = malloc(magic_len + 1); strncpy(image->magic, magic_start, magic_len); image->magic[magic_len] = '\0'; offset += magic_len + 1; if (strcmp(image->magic, "PDM32") != 0) { free(data); return -1; } // Read comments while (offset < (size_t) file_size && data[offset] == '#') { char *comment_start = data + offset + 1; char *comment_end = strchr(comment_start, '\n'); if (!comment_end) { free(data); return -1; } size_t comment_len = comment_end - comment_start; char *comment = malloc(comment_len + 1); strncpy(comment, comment_start, comment_len); comment[comment_len] = '\0'; image->comments = realloc(image->comments, (image->num_comments + 1) * sizeof(char*)); image->comments[image->num_comments] = comment; image->num_comments++; offset += comment_len + 2; // # and \n } // Read dimensions char *dim_start = data + offset; char *dim_end = strchr(dim_start, '\n'); if (!dim_end) { free(data); return -1; } char dim_str[256]; strncpy(dim_str, dim_start, dim_end - dim_start); dim_str[dim_end - dim_start] = '\0'; sscanf(dim_str, "%u %u", &image->width, &image->height); offset += (dim_end - dim_start) + 1; // Read depths size_t num_floats = (size_t)image->width * image->height; size_t data_size = num_floats * sizeof(float); if (offset + data_size > (size_t) file_size) { free(data); return -1; } image->depths = malloc(data_size); memcpy(image->depths, data + offset, data_size); offset += data_size; pdm->num_images++; } free(data); return 0; } void pdm_print_properties(PdmFile *pdm) { for (size_t i = 0; i < pdm->num_images; i++) { PdmImage *image = &pdm->images[i]; printf("Image %zu:\n", i + 1); printf(" Magic number: %s\n", image->magic); printf(" Comments: "); if (image->num_comments == 0) { printf("None\n"); } else { for (size_t j = 0; j < image->num_comments; j++) { printf("%s%s", image->comments[j], j < image->num_comments - 1 ? ", " : "\n"); } } printf(" Width: %u\n", image->width); printf(" Height: %u\n", image->height); printf(" Depth data: "); for (size_t j = 0; j < (size_t)image->width * image->height; j++) { printf("%f%s", image->depths[j], j < (size_t)image->width * image->height - 1 ? ", " : "\n"); } printf("\n"); } } int pdm_write(PdmFile *pdm, PdmImage *images, size_t num_images) { FILE *f = fopen(pdm->filepath, "wb"); if (!f) return -1; for (size_t i = 0; i < num_images; i++) { PdmImage *image = &images[i]; fprintf(f, "PDM32\n"); for (size_t j = 0; j < image->num_comments; j++) { fprintf(f, "#%s\n", image->comments[j]); } fprintf(f, "%u %u\n", image->width, image->height); fwrite(image->depths, sizeof(float), (size_t)image->width * image->height, f); } fclose(f); return 0; } // Example usage: // PdmFile *pdm = pdm_create("example.pdm"); // pdm_read(pdm); // pdm_print_properties(pdm); // pdm_destroy(pdm); // ===== end task-528 .PDM ===== // ===== task-530 .PDS [C++] ===== #include #include #include #include #include #include #include #include using PropertyMap = std::map>>; class PDSFile { private: std::string filepath; PropertyMap properties; std::vector data; public: PDSFile(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary); if (!file) throw std::runtime_error("Failed to open file."); std::vector content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); auto it = std::search(content.begin(), content.end(), {'E', 'N', 'D'}); if (it != content.end()) { std::string label(content.begin(), it + 3); data.assign(it + 3, content.end()); properties = parseODL(label); } else { throw std::runtime_error("No 'END' found in label."); } } PropertyMap parseODL(const std::string& label) { PropertyMap props; std::vector stack = {&props}; PropertyMap* current = &props; std::istringstream iss(label); std::string line; while (std::getline(iss, line)) { line = std::regex_replace(line, "^\\s+|\\s+$", ""); if (line.empty() || line.rfind("/*", 0) == 0) continue; if (std::regex_match(line, std::regex("OBJECT\\s*=\\s*.*"))) { size_t pos = line.find('='); std::string objName = std::regex_replace(line.substr(pos + 1), "^\\s+|\\s+$", ""); auto newObj = std::make_shared(); (*current)[objName] = newObj; stack.push_back(newObj.get()); current = newObj.get(); } else if (line == "END_OBJECT") { stack.pop_back(); current = stack.back(); } else if (line.find('=') != std::string::npos && line != "END") { size_t pos = line.find('='); std::string key = std::regex_replace(line.substr(0, pos), "^\\s+|\\s+$", ""); std::string value = std::regex_replace(line.substr(pos + 1), "^\\s+|\\s+$", ""); (*current)[key] = value; } else if (line == "END") { break; } } return props; } void printProperties(const PropertyMap& props, int indent = 0) const { for (const auto& [key, value] : props) { std::cout << std::string(indent * 2, ' ') << key << ": "; if (std::holds_alternative(value)) { std::cout << std::get(value) << std::endl; } else { std::cout << "{\n"; printProperties(*std::get>(value), indent + 1); std::cout << std::string(indent * 2, ' ') << "}\n"; } } } void printProperties() const { printProperties(properties); } void write(const std::string& newFilepath, const PropertyMap& newProps = {}, const std::vector& newData = {}) { PropertyMap writeProps = newProps.empty() ? properties : newProps; std::vector writeData = newData.empty() ? data : newData; std::ofstream file(newFilepath, std::ios::binary); if (!file) throw std::runtime_error("Failed to write file."); file << buildODL(writeProps, 0); file.write(writeData.data(), writeData.size()); } std::string buildODL(const PropertyMap& props, int indent) const { std::ostringstream oss; for (const auto& [key, value] : props) { oss << std::string(indent * 2, ' '); if (std::holds_alternative(value)) { oss << key << " = " << std::get(value) << "\n"; } else { oss << "OBJECT = " << key << "\n"; oss << buildODL(*std::get>(value), indent + 1); oss << std::string(indent * 2, ' ') << "END_OBJECT\n"; } } if (indent == 0) oss << "END\n"; return oss.str(); } }; // Example usage: // int main() { // PDSFile pds("example.pds"); // pds.read(); // pds.printProperties(); // pds.write("new.pds"); // return 0; // } // ===== end task-530 .PDS ===== // ===== task-531 .PEM [C++] ===== #include #include #include #include #include #include #include class PemHandler { private: std::string filepath; struct PemSection { std::string label; std::vector headers; std::string base64; std::vector decoded; }; std::vector sections; std::map properties; // Simple base64 decode function std::vector base64Decode(const std::string& input) { std::vector output; const std::string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; int val = 0, valb = -8; for (char c : input) { if (c == '=') break; size_t pos = chars.find(c); if (pos == std::string::npos) continue; val = (val << 6) + pos; valb += 6; if (valb >= 0) { output.push_back(char((val >> valb) & 0xFF)); valb -= 8; } } return output; } public: PemHandler(const std::string& fp = "") : filepath(fp) { if (!fp.empty()) { read(); } } void read() { std::ifstream file(filepath); if (!file) { std::cerr << "Error opening file" << std::endl; return; } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); parse(content); printProperties(); } void parse(const std::string& content) { sections.clear(); std::regex pattern(R"(-----BEGIN ([A-Z0-9 ]+)-----(.*?)-----END ([A-Z0-9 ]+)-----)", std::regex::dotall); auto begin = std::sregex_iterator(content.begin(), content.end(), pattern); auto end = std::sregex_iterator(); for (std::sregex_iterator i = begin; i != end; ++i) { std::smatch match = *i; std::string label = match[1].str(); std::string data = match[2].str(); std::vector lines; std::string line; for (char c : data) { if (c == '\n' || c == '\r') { if (!line.empty()) lines.push_back(line); line.clear(); } else { line += c; } } if (!line.empty()) lines.push_back(line); std::vector headers; std::string base64Data; for (const std::string& l : lines) { std::string trimmed = l; trimmed.erase(0, trimmed.find_first_not_of(" \t")); trimmed.erase(trimmed.find_last_not_of(" \t") + 1); if (trimmed.find(':') != std::string::npos && !std::regex_match(trimmed, std::regex("^[A-Za-z0-9+/=]+$"))) { headers.push_back(trimmed); } else if (!trimmed.empty()) { base64Data += trimmed; } } auto decoded = base64Decode(base64Data); sections.push_back({label, headers, base64Data, decoded}); } size_t dotPos = filepath.rfind('.'); properties["extension"] = (dotPos != std::string::npos) ? filepath.substr(dotPos) : ".pem"; properties["mimeType"] = (content.find("CERTIFICATE") != std::string::npos) ? "application/pkix-cert" : "text/plain"; properties["encoding"] = "US-ASCII with Base64"; std::string labelsStr; for (const auto& s : sections) { if (!labelsStr.empty()) labelsStr += ", "; labelsStr += s.label; } properties["labels"] = labelsStr; properties["numObjects"] = std::to_string(sections.size()); properties["multipleObjects"] = (sections.size() > 1) ? "true" : "false"; bool lineLengthsValid = true; for (const auto& s : sections) { size_t pos = 0; while (pos < s.base64.size()) { size_t len = std::min(64, s.base64.size() - pos); if (len > 64) { lineLengthsValid = false; break; } pos += 64; } } properties["lineLengthsValid"] = lineLengthsValid ? "true" : "false"; properties["whitespaceFlexible"] = "true"; std::regex expText(R"(^[^-].*?-----BEGIN)", std::regex::dotall); properties["hasExplanatoryText"] = std::regex_search(content, expText) ? "true" : "false"; bool noHeaders = true; for (const auto& s : sections) { if (!s.headers.empty()) { noHeaders = false; break; } } properties["noHeaders"] = noHeaders ? "true" : "false"; properties["asn1Compliant"] = "true"; // Assume std::string eolType = (content.find("\r\n") != std::string::npos) ? "CRLF" : ((content.find('\r') != std::string::npos) ? "CR" : "LF"); properties["eolType"] = eolType; } std::vector> decode() { std::vector> decodedList; for (const auto& s : sections) { decodedList.push_back(s.decoded); } return decodedList; } void write(const std::string& outputPath, const std::vector>& dataList, const std::vector& labels) { if (dataList.size() != labels.size()) { std::cerr << "Data and labels must match in length" << std::endl; return; } std::ofstream out(outputPath); if (!out) { std::cerr << "Error opening output file" << std::endl; return; } for (size_t i = 0; i < dataList.size(); ++i) { const auto& data = dataList[i]; const std::string& label = labels[i]; // Simple base64 encode std::string base64; const std::string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; int val = 0, valb = -6; for (char c : data) { val = (val << 8) + static_cast(c); valb += 8; while (valb >= 0) { base64 += chars[(val >> valb) & 0x3F]; valb -= 6; } } if (valb > -6) base64 += chars[((val << 8) >> (valb + 8)) & 0x3F]; while (base64.size() % 4) base64 += '='; // Wrap at 64 std::string wrapped; for (size_t j = 0; j < base64.size(); j += 64) { wrapped += base64.substr(j, 64) + "\n"; } out << "-----BEGIN " << label << "-----\n" << wrapped << "-----END " << label << "-----\n"; } } void printProperties() { std::cout << "PEM File Properties:" << std::endl; for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } }; // Example usage: // int main() { // PemHandler handler("example.pem"); // auto decoded = handler.decode(); // std::vector labels; // // Populate labels from sections... // handler.write("new.pem", decoded, labels); // return 0; // } // ===== end task-531 .PEM ===== // ===== task-533 .PFA [C++] ===== #include #include #include #include #include #include #include #include class PFAManager { private: std::string data; std::string cleartext; std::string decrypted; std::string fullText; std::map properties; std::vector hexToBytes(const std::string& hex) { std::vector bytes; for (size_t i = 0; i < hex.length(); i += 2) { std::string byteString = hex.substr(i, 2); unsigned char byte = static_cast(std::stoi(byteString, nullptr, 16)); bytes.push_back(byte); } return bytes; } std::string decryptEexec(const std::string& encryptedHex) { auto encryptedBytes = hexToBytes(encryptedHex); unsigned int c1 = 52845, c2 = 22719; unsigned int r = 55665; std::string plain; for (auto byte : encryptedBytes) { unsigned int p = byte ^ (r >> 8); r = ((static_cast(byte) + r) * c1 + c2) % 65536; plain += static_cast(p); } return plain.substr(4); // Discard first 4 } void parse() { size_t eexecPos = data.find("eexec"); if (eexecPos != std::string::npos) { cleartext = data.substr(0, eexecPos + 5); // Include 'eexec' std::string remaining = data.substr(eexecPos + 5); size_t clearToMarkPos = remaining.find("cleartomark"); std::string encryptedPart = remaining.substr(0, clearToMarkPos); encryptedPart.erase(std::remove_if(encryptedPart.begin(), encryptedPart.end(), isspace), encryptedPart.end()); decrypted = decryptEexec(encryptedPart); } else { decrypted = ""; } fullText = cleartext + decrypted; properties = extractProperties(); } std::map extractProperties() { std::map props; // Example regex (extend for all) std::map patterns = { {"FontName", std::regex(R"(/FontName\s+/(\w+)\s+def)")}, {"version", std::regex(R"(/version\s+\(([^)]+)\)\s+readonly\s+def)")}, {"BlueValues", std::regex(R"(/BlueValues\s+\[([\s\-0-9]+)\]\s+readonly\s+def)")} }; for (const auto& [key, reg] : patterns) { std::smatch match; if (std::regex_search(fullText, match, reg) && match.size() > 1) { props[key] = match[1].str(); } } return props; } public: PFAManager(const std::string& filename) { std::ifstream file(filename); if (file) { std::stringstream buffer; buffer << file.rdbuf(); data = buffer.str(); parse(); } } void printProperties() { for (const auto& [key, value] : properties) { std::cout << key << ": " << value << std::endl; } } void write(const std::string& outputFilename) { std::ofstream out(outputFilename); if (out) { out << data; } } }; // Example usage: // int main() { // PFAManager pfa("example.pfa"); // pfa.printProperties(); // pfa.write("output.pfa"); // return 0; // } // ===== end task-533 .PFA ===== // ===== task-534 .PFAM [C] ===== #include #include #include typedef struct { char *filepath; char *header; // Use simple arrays or linked lists for properties; for simplicity, assume max 100 properties struct { char key[256]; char value[1024]; } gf[100]; int gf_count; // For GS, GR: nested, use simple string storage for demo char gs[100][1024]; int gs_count; char gr[100][1024]; int gr_count; struct { char key[256]; char value[1024]; } gc[100]; int gc_count; struct { char name[256]; char seq[1024]; } sequences[100]; int seq_count; } PfamFile; void init_pfam(PfamFile *pf, char *filepath) { pf->filepath = strdup(filepath); pf->header = NULL; pf->gf_count = 0; pf->gs_count = 0; pf->gr_count = 0; pf->gc_count = 0; pf->seq_count = 0; } void read_pfam(PfamFile *pf) { FILE *f = fopen(pf->filepath, "r"); if (!f) return; char line[2048]; while (fgets(line, sizeof(line), f)) { line[strcspn(line, "\n")] = 0; if (strlen(line) == 0 || strncmp(line, "//", 2) == 0) continue; if (strncmp(line, "# STOCKHOLM", 11) == 0) { pf->header = strdup(line); } else if (strncmp(line, "#=GF", 4) == 0) { sscanf(line + 5, "%255s %1023[^\n]", pf->gf[pf->gf_count].key, pf->gf[pf->gf_count].value); pf->gf_count++; } else if (strncmp(line, "#=GS", 4) == 0) { strncpy(pf->gs[pf->gs_count++], line + 5, 1023); } else if (strncmp(line, "#=GR", 4) == 0) { strncpy(pf->gr[pf->gr_count++], line + 5, 1023); } else if (strncmp(line, "#=GC", 4) == 0) { sscanf(line + 5, "%255s %1023[^\n]", pf->gc[pf->gc_count].key, pf->gc[pf->gc_count].value); pf->gc_count++; } else { char name[256], seq[1024]; sscanf(line, "%255s %1023[^\n]", name, seq); int i; for (i = 0; i < pf->seq_count; i++) { if (strcmp(pf->sequences[i].name, name) == 0) { strcat(pf->sequences[i].seq, seq); break; } } if (i == pf->seq_count) { strcpy(pf->sequences[pf->seq_count].name, name); strcpy(pf->sequences[pf->seq_count].seq, seq); pf->seq_count++; } } } fclose(f); } void print_properties(PfamFile *pf) { if (pf->header) printf("Header: %s\n", pf->header); printf("GF properties:\n"); for (int i = 0; i < pf->gf_count; i++) printf("%s: %s\n", pf->gf[i].key, pf->gf[i].value); printf("GS properties:\n"); for (int i = 0; i < pf->gs_count; i++) printf("%s\n", pf->gs[i]); printf("GR properties:\n"); for (int i = 0; i < pf->gr_count; i++) printf("%s\n", pf->gr[i]); printf("GC properties:\n"); for (int i = 0; i < pf->gc_count; i++) printf("%s: %s\n", pf->gc[i].key, pf->gc[i].value); printf("Sequences:\n"); for (int i = 0; i < pf->seq_count; i++) printf("%s: %s\n", pf->sequences[i].name, pf->sequences[i].seq); } void write_pfam(PfamFile *pf, char *new_filepath) { if (!new_filepath) new_filepath = pf->filepath; FILE *f = fopen(new_filepath, "w"); if (pf->header) fprintf(f, "%s\n", pf->header); for (int i = 0; i < pf->gf_count; i++) fprintf(f, "#=GF %s %s\n", pf->gf[i].key, pf->gf[i].value); for (int i = 0; i < pf->gs_count; i++) fprintf(f, "#=GS %s\n", pf->gs[i]); for (int i = 0; i < pf->seq_count; i++) { fprintf(f, "%s %s\n", pf->sequences[i].name, pf->sequences[i].seq); // Assume GR are printed after sequences; simplistic } for (int i = 0; i < pf->gr_count; i++) fprintf(f, "#=GR %s\n", pf->gr[i]); for (int i = 0; i < pf->gc_count; i++) fprintf(f, "#=GC %s %s\n", pf->gc[i].key, pf->gc[i].value); fprintf(f, "//\n"); fclose(f); } void free_pfam(PfamFile *pf) { free(pf->filepath); if (pf->header) free(pf->header); } // Example usage: // int main() { // PfamFile pf; // init_pfam(&pf, "example.sto"); // read_pfam(&pf); // print_properties(&pf); // write_pfam(&pf, "output.sto"); // free_pfam(&pf); // return 0; // } // ===== end task-534 .PFAM ===== // ===== task-535 .PFB [C++] ===== #include #include #include #include #include struct Segment { uint8_t type; uint32_t length; std::vector data; }; class PFBHandler { private: std::string filename; std::vector segments; public: PFBHandler(const std::string& fn) : filename(fn) { readAndDecode(); } void readAndDecode() { std::ifstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file"); } std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); size_t pos = 0; while (pos < data.size()) { if (data[pos] != 0x80) { throw std::runtime_error("Invalid PFB start byte"); } ++pos; uint8_t type = data[pos]; ++pos; if (type == 3) { break; } uint32_t length = 0; memcpy(&length, &data[pos], sizeof(length)); // Assumes little-endian host or handle conversion pos += 4; Segment seg; seg.type = type; seg.length = length; seg.data.resize(length); memcpy(seg.data.data(), &data[pos], length); segments.push_back(seg); pos += length; } } void printProperties() const { std::cout << "PFB Properties:" << std::endl; for (size_t i = 0; i < segments.size(); ++i) { std::cout << "Segment " << (i + 1) << ": Type " << static_cast(segments[i].type) << " (1=ASCII, 2=Binary), Length: " << segments[i].length << std::endl; } std::cout << "Total segments: " << segments.size() << std::endl; std::cout << "EOF marker: Present" << std::endl; } void write(const std::string& outputFilename) const { std::ofstream file(outputFilename, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open output file"); } for (const auto& seg : segments) { file.put(0x80); file.put(seg.type); uint32_t len = seg.length; // Assumes little-endian file.write(reinterpret_cast(&len), sizeof(len)); file.write(reinterpret_cast(seg.data.data()), seg.length); } file.put(0x80); file.put(0x03); } }; int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Usage: " << argv[0] << " input.pfb [output.pfb]" << std::endl; return 1; } try { PFBHandler handler(argv[1]); handler.printProperties(); if (argc > 2) { handler.write(argv[2]); } } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } // ===== end task-535 .PFB ===== // ===== task-536 .PFC [C++] ===== #include #include #include #include #include #include class PfcParser { private: std::string filename; std::vector data; std::map properties; // Simplified to string for print public: PfcParser(const std::string& fn) : filename(fn) {} void read() { std::ifstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file"); } file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(data.data(), size); size_t position = 0; char magic[9]; memcpy(magic, data.data() + position, 8); magic[8] = '\0'; properties["magic"] = magic; position += 8; if (std::string(magic) != "AOLVM100") { throw std::runtime_error("Invalid PFC file"); } position += 100; // Header // Index Table (simplified) std::vector> indexEntries; while (position + 4 < data.size()) { char entryStart[4]; memcpy(entryStart, data.data() + position, 4); if (memcmp(entryStart, "RS\0\0", 4) != 0) break; position += 4; uint32_t pointer; memcpy(&pointer, data.data() + position, 4); position += 4; uint32_t contentType; memcpy(&contentType, data.data() + position, 4); position += 4; uint8_t flags = *(data.data() + position); position += 1; uint32_t timestamp; memcpy(×tamp, data.data() + position, 4); position += 4; std::map entry; entry["pointer"] = pointer; entry["contentType"] = contentType; entry["flags"] = flags; entry["timestamp"] = timestamp; indexEntries.push_back(entry); position += 20; } // Store as string for print properties["indexEntries"] = "Count: " + std::to_string(indexEntries.size()); // Example email (placeholder, similar) } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& newFilename) { std::ofstream file(newFilename, std::ios::binary); if (!file) { throw std::runtime_error("Cannot write file"); } file.write("AOLVM100", 8); char header[100] = {0}; file.write(header, 100); // Add index, etc... (placeholder) } }; // Example usage // int main() { // try { // PfcParser parser("example.pfc"); // parser.read(); // parser.printProperties(); // parser.write("example.new.pfc"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-536 .PFC ===== // ===== task-537 .PFM [C++] ===== #include #include #include #include #include #include class PFMFile { private: std::string identifier; int width; int height; double scale; std::string endianness; int channels; std::vector data; // Vector of floats for pixel data public: void read(const std::string& filepath) { std::ifstream file(filepath, std::ios::binary); if (!file) { std::cerr << "Failed to open file" << std::endl; return; } std::getline(file, identifier); identifier.erase(std::remove(identifier.begin(), identifier.end(), '\r'), identifier.end()); // Trim CR if any std::string dimLine; std::getline(file, dimLine); std::sscanf(dimLine.c_str(), "%d %d", &width, &height); std::string scaleLine; std::getline(file, scaleLine); double scaleVal; std::sscanf(scaleLine.c_str(), "%lf", &scaleVal); endianness = (scaleVal > 0) ? "big" : "little"; scale = std::abs(scaleVal); channels = (identifier == "PF") ? 3 : 1; // Read data int sampleCount = width * height * channels; data.resize(sampleCount); file.read(reinterpret_cast(data.data()), sampleCount * sizeof(float)); // Handle endian swap if necessary (assuming host is little-endian for simplicity) if (endianness == "big" && (reinterpret_cast(&scaleVal)[0] != 0)) { // Crude host check for (float& val : data) { uint32_t* bytes = reinterpret_cast(&val); *bytes = __builtin_bswap32(*bytes); } } } void write(const std::string& filepath, const std::vector& newData = {}) { auto writeData = newData.empty() ? data : newData; if (writeData.size() != static_cast(width * height * channels)) { std::cerr << "Data mismatch" << std::endl; return; } std::ofstream file(filepath, std::ios::binary); if (!file) { std::cerr << "Failed to open file" << std::endl; return; } file << identifier << "\n"; file << width << " " << height << "\n"; double signedScale = (endianness == "big" ? 1 : -1) * scale; file << signedScale << "\n"; // Write data (assuming no swap needed; adjust if cross-endian) file.write(reinterpret_cast(writeData.data()), writeData.size() * sizeof(float)); } void printProperties() const { std::cout << "Identifier: " << identifier << std::endl; std::cout << "Width: " << width << std::endl; std::cout << "Height: " << height << std::endl; std::cout << "Scale Factor: " << scale << std::endl; std::cout << "Endianness: " << endianness << std::endl; std::cout << "Channels: " << channels << std::endl; } }; // Example usage: // int main() { // PFMFile pfm; // pfm.read("example.pfm"); // pfm.printProperties(); // pfm.write("output.pfm"); // return 0; // } // ===== end task-537 .PFM ===== // ===== task-538 .PFX [C] ===== #include #include #include typedef struct { const char *filepath; const char *password; PKCS12 *p12; } PFXHandler; void init_PFXHandler(PFXHandler *handler, const char *filepath, const char *password) { handler->filepath = filepath; handler->password = password; FILE *fp = fopen(filepath, "rb"); if (!fp) { fprintf(stderr, "Error opening file\n"); return; } handler->p12 = d2i_PKCS12_fp(fp, NULL); fclose(fp); if (!handler->p12) { fprintf(stderr, "Error loading PFX\n"); ERR_print_errors_fp(stderr); } } void print_properties(PFXHandler *handler) { if (!handler->p12) return; PKCS12_MAC_DATA *mac = NULL; STACK_OF(PKCS7) *asafes = NULL; if (PKCS12_verify_mac(handler->p12, handler->password, strlen(handler->password))) { printf("MAC verified\n"); } if (!PKCS12_parse(handler->p12, handler->password, NULL, NULL, &asafes)) { fprintf(stderr, "Error parsing\n"); return; } printf("PFX Properties:\n"); printf("- version: %d\n", PKCS12_get_version(handler->p12)); // Custom function if needed mac = PKCS12_get0_mac(handler->p12); if (mac) { printf("- macData:\n"); printf(" - iterations: %ld\n", ASN1_INTEGER_get(mac->iter)); // Print salt and mac printf(" - macSalt: (binary data)\n"); } // Print safes for (int i = 0; i < sk_PKCS7_num(asafes); i++) { PKCS7 *p7 = sk_PKCS7_value(asafes, i); printf("- AuthenticatedSafe[%d]:\n", i); // Further parse bags (omitted for brevity, use PKCS12_SAFEBAG functions) } sk_PKCS7_pop_free(asafes, PKCS7_free); } void write_PFX(PFXHandler *handler, const char *new_filepath, const char *new_password) { if (!handler->p12) return; FILE *fp = fopen(new_filepath, "wb"); if (!fp) { fprintf(stderr, "Error opening output file\n"); return; } i2d_PKCS12_fp(fp, handler->p12); fclose(fp); printf("Written new .PFX to %s\n", new_filepath); } void free_PFXHandler(PFXHandler *handler) { PKCS12_free(handler->p12); } // Example usage // int main() { // PFXHandler handler; // init_PFXHandler(&handler, "sample.pfx", "password"); // print_properties(&handler); // write_PFX(&handler, "new.pfx", "newpass"); // free_PFXHandler(&handler); // return 0; // } // ===== end task-538 .PFX ===== // ===== task-539 .PGN [C] ===== #include #include #include #include // For regex; may need -lregex on compile #define MAX_TAGS 50 #define MAX_KEY_LEN 50 #define MAX_VAL_LEN 255 #define MAX_MOVETEXT 4096 typedef struct { char keys[MAX_TAGS][MAX_KEY_LEN]; char values[MAX_TAGS][MAX_VAL_LEN]; int tag_count; char movetext[MAX_MOVETEXT]; } PGNHandler; void init_PGNHandler(PGNHandler *handler) { handler->tag_count = 0; memset(handler->movetext, 0, MAX_MOVETEXT); } int read_PGN(PGNHandler *handler, const char *filepath) { if (strstr(filepath, ".pgn") != filepath + strlen(filepath) - 4) { fprintf(stderr, "Invalid .PGN file path.\n"); return 1; } FILE *file = fopen(filepath, "r"); if (!file) { fprintf(stderr, "Failed to open file.\n"); return 1; } char line[512]; int in_tags = 1; char temp_movetext[MAX_MOVETEXT] = {0}; regex_t regex; regcomp(®ex, "^\\[([a-zA-Z0-9_]+)\\s+\"(.*)\"\\]$", REG_EXTENDED); while (fgets(line, sizeof(line), file)) { char *trimmed = strtok(line, "\r\n"); // Trim newline if (!trimmed) continue; if (in_tags) { regmatch_t matches[3]; if (regexec(®ex, trimmed, 3, matches, 0) == 0) { if (handler->tag_count < MAX_TAGS) { int key_len = matches[1].rm_eo - matches[1].rm_so; int val_len = matches[2].rm_eo - matches[2].rm_so; strncpy(handler->keys[handler->tag_count], trimmed + matches[1].rm_so, key_len); handler->keys[handler->tag_count][key_len] = '\0'; strncpy(handler->values[handler->tag_count], trimmed + matches[2].rm_so, val_len); handler->values[handler->tag_count][val_len] = '\0'; handler->tag_count++; } } else if (strlen(trimmed) == 0 || (trimmed[0] >= '0' && trimmed[0] <= '9')) { in_tags = 0; } } if (!in_tags && strlen(trimmed) > 0) { strcat(temp_movetext, trimmed); strcat(temp_movetext, " "); } } strcpy(handler->movetext, temp_movetext); regfree(®ex); fclose(file); return 0; } void print_properties(PGNHandler *handler) { for (int i = 0; i < handler->tag_count; i++) { printf("%s: %s\n", handler->keys[i], handler->values[i]); } } int write_PGN(PGNHandler *handler, const char *filepath, const char (*new_keys)[MAX_KEY_LEN], const char (*new_values)[MAX_VAL_LEN], int new_count, const char *new_movetext) { FILE *file = fopen(filepath, "w"); if (!file) { fprintf(stderr, "Failed to write file.\n"); return 1; } // If new properties provided, use them int count = new_count > 0 ? new_count : handler->tag_count; const char (*keys)[MAX_KEY_LEN] = new_count > 0 ? new_keys : handler->keys; const char (*values)[MAX_VAL_LEN] = new_count > 0 ? new_values : handler->values; // Sort keys (simple bubble sort for demo) char sorted_keys[MAX_TAGS][MAX_KEY_LEN]; char sorted_values[MAX_TAGS][MAX_VAL_LEN]; memcpy(sorted_keys, keys, sizeof(sorted_keys)); memcpy(sorted_values, values, sizeof(sorted_values)); for (int i = 0; i < count - 1; i++) { for (int j = 0; j < count - i - 1; j++) { if (strcmp(sorted_keys[j], sorted_keys[j + 1]) > 0) { char temp_key[MAX_KEY_LEN], temp_val[MAX_VAL_LEN]; strcpy(temp_key, sorted_keys[j]); strcpy(temp_val, sorted_values[j]); strcpy(sorted_keys[j], sorted_keys[j + 1]); strcpy(sorted_values[j], sorted_values[j + 1]); strcpy(sorted_keys[j + 1], temp_key); strcpy(sorted_values[j + 1], temp_val); } } } for (int i = 0; i < count; i++) { fprintf(file, "[%s \"%s\"]\n", sorted_keys[i], sorted_values[i]); } fprintf(file, "\n"); fprintf(file, "%s\n", new_movetext ? new_movetext : handler->movetext); fclose(file); return 0; } // Example usage: // int main() { // PGNHandler handler; // init_PGNHandler(&handler); // read_PGN(&handler, "example.pgn"); // print_properties(&handler); // // For write: define new_keys, new_values arrays // return 0; // } // ===== end task-539 .PGN ===== // ===== task-540 .PHF [C++] ===== #include #include #include #include #include #include "tinyxml2.h" // Assume tinyxml2 library using namespace tinyxml2; class PHFFile { private: std::string filepath; XMLDocument doc; std::map header; std::vector> unicode_mappings; std::vector>> glyphs; std::vector> data_images; public: PHFFile(const std::string& fp) : filepath(fp) {} void read() { doc.LoadFile(filepath.c. str()); if (doc.Error()) { std::cout << "Error loading XML" << std::endl; return; } decodeProperties(); } void decodeProperties() { XMLElement* root = doc.FirstChildElement("PhF"); if (!root) return; XMLElement* headerElem = root->FirstChildElement("header"); if (headerElem) { for (XMLElement* child = headerElem->FirstChildElement(); child; child = child->NextSiblingElement()) { const char* subtype = child->Attribute("subtype"); if (subtype) { header[subtype] = child->GetText() ? child->GetText() : ""; } } } XMLElement* globals = root->FirstChildElement("globals"); if (globals) { XMLElement* unicodeMapping = globals->FirstChildElement("unicode_mapping"); if (unicodeMapping) { for (XMLElement* map = unicodeMapping->FirstChildElement("map"); map; map = map->NextSiblingElement("map")) { std::map mapping; mapping["unc"] = map->Attribute("unc") ? map->Attribute("unc") : ""; mapping["id"] = map->Attribute("id") ? map->Attribute("id") : ""; unicode_mappings.push_back(mapping); } } } XMLElement* glyphsElem = root->FirstChildElement("glyphs"); if (glyphsElem) { for (XMLElement* glyph = glyphsElem->FirstChildElement("glyph"); glyph; glyph = glyph->NextSiblingElement("glyph")) { std::map> glyphData; glyphData["$"] = {{"id", glyph->Attribute("id") ? glyph->Attribute("id") : ""}}; XMLElement* image = glyph->FirstChildElement("image"); if (image) { glyphData["image"] = {{"type", image->Attribute("type") ? image->Attribute("type") : ""}, {"id", image->Attribute("id") ? image->Attribute("id") : ""}}; XMLElement* shape = image->FirstChildElement("shape"); glyphData["image"]["shape_embedded"] = shape->Attribute("embedded") ? shape->Attribute("embedded") : ""; XMLElement* ppm = image->FirstChildElement("ppm"); glyphData["image"]["ppm"] = ppm->Attribute("int") ? ppm->Attribute("int") : ""; XMLElement* bbox = image->FirstChildElement("bbox"); if (bbox) { glyphData["bbox"] = { {"width", bbox->Attribute("width") ? bbox->Attribute("width") : ""}, {"height", bbox->Attribute("height") ? bbox->Attribute("height") : ""}, {"x", bbox->Attribute("x") ? bbox->Attribute("x") : ""}, {"y", bbox->Attribute("y") ? bbox->Attribute("y") : ""} }; } XMLElement* base = image->FirstChildElement("base"); if (base) { glyphData["base"] = { {"x", base->Attribute("x") ? base->Attribute("x") : ""}, {"y", base->Attribute("y") ? base->Attribute("y") : ""} }; } XMLElement* delta = image->FirstChildElement("delta"); if (delta) { glyphData["delta"] = { {"x", delta->Attribute("x") ? delta->Attribute("x") : ""}, {"y", delta->Attribute("y") ? delta->Attribute("y") : ""} }; } } glyphs.push_back(glyphData); } } XMLElement* data = root->FirstChildElement("data"); if (data) { XMLElement* photo = data->FirstChildElement("photo"); if (photo) { for (XMLElement* img = photo->FirstChildElement("image"); img; img = img->NextSiblingElement("image")) { std::map imgData; imgData["id"] = img->Attribute("id") ? img->Attribute("id") : ""; imgData["base64_data"] = img->GetText() ? img->GetText() : ""; data_images.push_back(imgData); } } } } void printProperties() { std::cout << "PHF Properties:" << std::endl; std::cout << "\nHeader:" << std::endl; for (const auto& kv : header) { std::cout << " " << kv.first << ": " << kv.second << std::endl; } std::cout << "\nUnicode Mappings:" << std::endl; for (const auto& mapping : unicode_mappings) { std::cout << " UNC: " << mapping.at("unc") << ", ID: " << mapping.at("id") << std::endl; } std::cout << "\nGlyphs:" << std::endl; for (const auto& glyph : glyphs) { std::cout << " Glyph ID: " << glyph.at("$").at("id") << std::endl; const auto& img = glyph.at("image"); std::cout << " Type: " << img.at("type") << std::endl; std::cout << " ID: " << img.at("id") << std::endl; std::cout << " Shape Embedded: " << img.at("shape_embedded") << std::endl; std::cout << " PPM: " << img.at("ppm") << std::endl; const auto& bbox = glyph.at("bbox"); std::cout << " BBox: W=" << bbox.at("width") << ", H=" << bbox.at("height") << ", X=" << bbox.at("x") << ", Y=" << bbox.at("y") << std::endl; const auto& base = glyph.at("base"); std::cout << " Base: X=" << base.at("x") << ", Y=" << base.at("y") << std::endl; const auto& delta = glyph.at("delta"); std::cout << " Delta: X=" << delta.at("x") << ", Y=" << delta.at("y") << std::endl; } std::cout << "\nData Images:" << std::endl; for (const auto& img : data_images) { std::cout << " Image ID: " << img.at("id") << std::endl; std::string data = img.at("base64_data"); std::cout << " Base64 Data: " << data.substr(0, 50) << "... (truncated)" << std::endl; } } void write(const std::string& newFilepath) { doc.SaveFile((newFilepath.empty() ? filepath : newFilepath).c_str()); } }; // Example usage // int main() { // PHFFile phf("example.phf"); // phf.read(); // phf.printProperties(); // phf.write("modified.phf"); // return 0; // } // ===== end task-540 .PHF ===== // ===== task-541 .PHN [C] ===== #include #include #include typedef struct { int begin_sample; int end_sample; char *phonetic_label; } Segment; typedef struct { char *filepath; Segment *segments; int count; } PHNFileHandler; PHNFileHandler* createPHNFileHandler(const char *filepath) { PHNFileHandler *handler = malloc(sizeof(PHNFileHandler)); handler->filepath = strdup(filepath); handler->segments = NULL; handler->count = 0; return handler; } void read(PHNFileHandler *handler) { FILE *f = fopen(handler->filepath, "r"); if (!f) { perror("Error opening file"); return; } char line[256]; int capacity = 10; handler->segments = malloc(capacity * sizeof(Segment)); handler->count = 0; while (fgets(line, sizeof(line), f)) { int begin, end; char label[10]; if (sscanf(line, "%d %d %s", &begin, &end, label) == 3) { if (handler->count >= capacity) { capacity *= 2; handler->segments = realloc(handler->segments, capacity * sizeof(Segment)); } handler->segments[handler->count].begin_sample = begin; handler->segments[handler->count].end_sample = end; handler->segments[handler->count].phonetic_label = strdup(label); handler->count++; } } fclose(f); } void printProperties(PHNFileHandler *handler) { if (handler->count == 0) { printf("No segments loaded. Call read() first.\n"); return; } for (int i = 0; i < handler->count; i++) { printf("Segment %d:\n", i + 1); printf(" begin_sample: %d\n", handler->segments[i].begin_sample); printf(" end_sample: %d\n", handler->segments[i].end_sample); printf(" phonetic_label: %s\n", handler->segments[i].phonetic_label); printf("\n"); } } void write(PHNFileHandler *handler, const char *new_filepath) { const char *path = new_filepath ? new_filepath : handler->filepath; FILE *f = fopen(path, "w"); if (!f) { perror("Error opening file for writing"); return; } for (int i = 0; i < handler->count; i++) { fprintf(f, "%d %d %s\n", handler->segments[i].begin_sample, handler->segments[i].end_sample, handler->segments[i].phonetic_label); } fclose(f); } void destroyPHNFileHandler(PHNFileHandler *handler) { for (int i = 0; i < handler->count; i++) { free(handler->segments[i].phonetic_label); } free(handler->segments); free(handler->filepath); free(handler); } // Example usage int main() { PHNFileHandler *handler = createPHNFileHandler("example.phn"); read(handler); printProperties(handler); // To add and write handler->segments = realloc(handler->segments, (handler->count + 1) * sizeof(Segment)); handler->segments[handler->count].begin_sample = 0; handler->segments[handler->count].end_sample = 100; handler->segments[handler->count].phonetic_label = strdup("test"); handler->count++; write(handler, "new_example.phn"); destroyPHNFileHandler(handler); return 0; } // ===== end task-541 .PHN ===== // ===== task-542 .PHP [C] ===== #include #include #include #include #include #include #include #include typedef struct { char *filename; } PhpFileHandler; void init_php_file_handler(PhpFileHandler *handler, const char *filename) { if (strstr(filename, ".php") != filename + strlen(filename) - 4) { fprintf(stderr, "File must have .php extension\n"); exit(1); } handler->filename = strdup(filename); } void print_properties(const PhpFileHandler *handler) { struct stat st; if (stat(handler->filename, &st) != 0) { perror("stat"); return; } struct passwd *pwd = getpwuid(st.st_uid); struct group *grp = getgrgid(st.st_gid); printf("File name: %s\n", handler->filename); printf("File size (bytes): %ld\n", (long)st.st_size); printf("Modification time: %s", ctime(&st.st_mtime)); printf("Access time: %s", ctime(&st.st_atime)); printf("Change time: %s", ctime(&st.st_ctime)); printf("Permissions/mode: %o\n", st.st_mode & 0777); // Octal printf("Owner user ID: %d (%s)\n", st.st_uid, pwd ? pwd->pw_name : "unknown"); printf("Owner group ID: %d (%s)\n", st.st_gid, grp ? grp->gr_name : "unknown"); printf("Inode number: %ld\n", (long)st.st_ino); printf("Device ID: %ld\n", (long)st.st_dev); printf("Number of hard links: %ld\n", (long)st.st_nlink); } char *read_content(const PhpFileHandler *handler) { FILE *fp = fopen(handler->filename, "r"); if (!fp) { perror("fopen"); return NULL; } fseek(fp, 0, SEEK_END); long size = ftell(fp); fseek(fp, 0, SEEK_SET); char *content = malloc(size + 1); fread(content, 1, size, fp); content[size] = '\0'; fclose(fp); return content; } void write_content(const PhpFileHandler *handler, const char *content) { FILE *fp = fopen(handler->filename, "w"); if (!fp) { perror("fopen"); return; } fprintf(fp, "%s", content ? content : ""); fclose(fp); printf("Written to %s\n", handler->filename); } void free_php_file_handler(PhpFileHandler *handler) { free(handler->filename); } // Example usage: // int main() { // PhpFileHandler handler; // init_php_file_handler(&handler, "example.php"); // print_properties(&handler); // write_content(&handler, NULL); // free_php_file_handler(&handler); // return 0; // } // ===== end task-542 .PHP ===== // ===== task-543 .PHP3 [C++] ===== #include #include #include #include #include #include // For UID/GID on Unix-like class PHP3FileHandler { private: std::string filepath; struct stat stats; public: PHP3FileHandler(const std::string& fp) : filepath(fp) { if (filepath.substr(filepath.find_last_of(".") + 1) != "php3") { throw std::invalid_argument("File must have .php3 extension"); } if (stat(filepath.c_str(), &stats) != 0) { throw std::runtime_error("Failed to get file stats"); } } std::string readContent() { std::ifstream file(filepath); if (!file) { throw std::runtime_error("Failed to open file for reading"); } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); return content; } void writeContent(const std::string& content) { std::ofstream file(filepath); if (!file) { throw std::runtime_error("Failed to open file for writing"); } file << content; if (stat(filepath.c_str(), &stats) != 0) { // Update stats throw std::runtime_error("Failed to get updated file stats"); } } void printProperties() { std::cout << "File name: " << filepath.substr(filepath.find_last_of("/\\") + 1) << std::endl; std::cout << "File path: " << std::string(std::filesystem::absolute(filepath)) << std::endl; // C++17 std::cout << "File size: " << stats.st_size << " bytes" << std::endl; std::cout << "Creation time: " << std::ctime(&stats.st_ctime); std::cout << "Last modification time: " << std::ctime(&stats.st_mtime); std::cout << "Last access time: " << std::ctime(&stats.st_atime); std::cout << "Permissions: " << std::oct << (stats.st_mode & 0777) << std::dec << std::endl; std::cout << "Owner UID: " << stats.st_uid << std::endl; std::cout << "Group GID: " << stats.st_gid << std::endl; std::cout << "Inode number: " << stats.st_ino << std::endl; } }; // Example usage: // int main() { // try { // PHP3FileHandler handler("example.php3"); // std::cout << handler.readContent() << std::endl; // handler.writeContent(""); // handler.printProperties(); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-543 .PHP3 ===== // ===== task-544 .PHP4 [C] ===== #include #include #include #include #include #include #include typedef struct { char *filepath; } PHP4FileHandler; PHP4FileHandler* create_handler(const char *filepath) { if (strstr(filepath, ".php4") != filepath + strlen(filepath) - 5) { fprintf(stderr, "File must have .php4 extension\n"); exit(1); } PHP4FileHandler *handler = malloc(sizeof(PHP4FileHandler)); handler->filepath = strdup(filepath); return handler; } char* read_content(PHP4FileHandler *handler) { FILE *f = fopen(handler->filepath, "r"); if (!f) { perror("fopen"); return NULL; } fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); char *content = malloc(size + 1); fread(content, 1, size, f); content[size] = '\0'; fclose(f); return content; } void write_content(PHP4FileHandler *handler, const char *content) { FILE *f = fopen(handler->filepath, "w"); if (!f) { perror("fopen"); return; } fprintf(f, "%s", content); fclose(f); } void print_properties(PHP4FileHandler *handler) { struct stat st; if (stat(handler->filepath, &st) == -1) { perror("stat"); return; } printf("Inode number: %ld\n", (long)st.st_ino); printf("Permissions: %o (%s)\n", st.st_mode & 07777, (st.st_mode & S_IRUSR) ? "r" : "-"); printf("Number of hard links: %ld\n", (long)st.st_nlink); printf("Owner UID: %d\n", st.st_uid); printf("Owner GID: %d\n", st.st_gid); printf("Device ID: %ld\n", (long)st.st_dev); printf("File size: %ld bytes\n", (long)st.st_size); printf("Access time: %s", ctime(&st.st_atime)); printf("Modification time: %s", ctime(&st.st_mtime)); printf("Change time: %s", ctime(&st.st_ctime)); } void destroy_handler(PHP4FileHandler *handler) { free(handler->filepath); free(handler); } // Example usage: // int main() { // PHP4FileHandler *handler = create_handler("example.php4"); // char *content = read_content(handler); // if (content) { // printf("%s\n", content); // free(content); // } // write_content(handler, ""); // print_properties(handler); // destroy_handler(handler); // return 0; // } // ===== end task-544 .PHP4 ===== // ===== task-545 .PHR [C++] ===== #include #include #include #include #include // Assume nlohmann/json library for JSON parsing using json = nlohmann::json; class PHRFile { private: std::string filepath; std::vector resources; public: PHRFile(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath); std::string line; while (std::getline(file, line)) { if (!line.empty()) { try { json resource = json::parse(line); resources.push_back(resource); } catch (const json::exception& e) { std::cout << "Error decoding line: " << e.what() << std::endl; } } } } void decode() { // Decoding is parsing JSON, done in read } void printProperties() { for (size_t idx = 0; idx < resources.size(); ++idx) { const json& resource = resources[idx]; std::cout << "Resource " << (idx + 1) << ":" << std::endl; std::cout << " Type: " << (resource.contains("resourceType") ? resource["resourceType"].get() : "N/A") << std::endl; std::cout << " ID: " << (resource.contains("id") ? resource["id"].get() : "N/A") << std::endl; std::string name = "N/A"; if (resource.contains("name") && !resource["name"].empty() && resource["name"].is_array() && resource["name"][0].contains("text")) { name = resource["name"][0]["text"].get(); } std::cout << " Patient Name: " << name << std::endl; std::string version = "N/A"; if (resource.contains("meta") && resource["meta"].contains("versionId")) { version = resource["meta"]["versionId"].get(); } std::cout << " Version: " << version << std::endl; std::cout << " Provenance: " << (resource.contains("contained") ? "Present" : "Absent") << std::endl; std::cout << " Signature: " << (resource.contains("signature") ? "Present" : "Absent") << std::endl; std::cout << " Full Resource: " << resource.dump(2) << std::endl << std::endl; } } void write(const std::vector& newResources, const std::string& newFilepath = "") { std::string path = newFilepath.empty() ? filepath : newFilepath; std::ofstream file(path); for (const auto& res : newResources) { file << res.dump() << std::endl; } } }; // Example usage: // int main() { // PHRFile phr("example.phr"); // phr.read(); // phr.printProperties(); // std::vector newRes = {{{"resourceType", "Patient"}, {"id", "new"}}}; // phr.write(newRes, "new.phr"); // return 0; // } // ===== end task-545 .PHR ===== // ===== task-547 .PHZ [C] ===== #include #include // Assume libzip is installed struct PHZHandler { const char* filename; // Properties would be stored in a struct or map, but for simplicity use printf directly }; void phz_read(const char* filename) { int err = 0; zip_t *z = zip_open(filename, 0, &err); if (z == NULL) { printf("Error opening %s\n", filename); return; } zip_int64_t num_entries = zip_get_num_entries(z, 0); printf("Number of files: %lld\n", num_entries); long total_compressed = 0; long total_uncompressed = 0; for (zip_int64_t i = 0; i < num_entries; i++) { struct zip_stat st; zip_stat_index(z, i, 0, &st); printf("\nFile: %s\n", st.name); printf(" Compressed size: %llu\n", st.comp_size); printf(" Uncompressed size: %llu\n", st.size); printf(" Compression method: %u\n", st.comp_method); printf(" Last mod time: %u\n", st.mtime); printf(" CRC: %u\n", st.crc); total_compressed += st.comp_size; total_uncompressed += st.size; } printf("\nTotal compressed size: %ld\n", total_compressed); printf("Total uncompressed size: %ld\n", total_uncompressed); zip_close(z); } void phz_write(const char* output_filename, const char** files_to_add, int num_files) { int err = 0; zip_t *z = zip_open(output_filename, ZIP_CREATE | ZIP_TRUNCATE, &err); if (z == NULL) { printf("Error creating %s\n", output_filename); return; } for (int i = 0; i < num_files; i++) { zip_source_t *src = zip_source_file(z, files_to_add[i], 0, 0); if (src == NULL || zip_file_add(z, files_to_add[i], src, ZIP_FL_OVERWRITE) < 0) { zip_source_free(src); printf("Error adding file %s\n", files_to_add[i]); } } zip_close(z); printf("Written new .PHZ to %s\n", output_filename); } // Example usage: // int main() { // phz_read("example.phz"); // const char* files[] = {"scene.phn", "thumbnail.png", "checksums.txt"}; // phz_write("new.phz", files, 3); // return 0; // } // ===== end task-547 .PHZ ===== // ===== task-548 .PI2 [C++] ===== #include #include #include #include #include #include // For bswap_16 on little-endian systems class PI2File { public: uint16_t resolution; uint16_t palette[16]; uint8_t* bitmap_data; uint16_t left_limits[4]; uint16_t right_limits[4]; uint16_t directions[4]; uint16_t delays[4]; PI2File(const std::string& filename) { std::ifstream file(filename, std::ios::binary | std::ios::ate); std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); if (size != 32066) { throw std::runtime_error("Invalid .PI2 file size"); } std::vector data(size); file.read(reinterpret_cast(data.data()), size); memcpy(&resolution, data.data(), 2); resolution = __bswap_16(resolution); // Convert big-endian to host for (int i = 0; i < 16; ++i) { memcpy(&palette[i], data.data() + 2 + i * 2, 2); palette[i] = __bswap_16(palette[i]); } bitmap_data = new uint8_t[32000]; memcpy(bitmap_data, data.data() + 34, 32000); size_t offset = 32034; for (int i = 0; i < 4; ++i) { memcpy(&left_limits[i], data.data() + offset + i * 2, 2); left_limits[i] = __bswap_16(left_limits[i]); } offset += 8; for (int i = 0; i < 4; ++i) { memcpy(&right_limits[i], data.data() + offset + i * 2, 2); right_limits[i] = __bswap_16(right_limits[i]); } offset += 8; for (int i = 0; i < 4; ++i) { memcpy(&directions[i], data.data() + offset + i * 2, 2); directions[i] = __bswap_16(directions[i]); } offset += 8; for (int i = 0; i < 4; ++i) { memcpy(&delays[i], data.data() + offset + i * 2, 2); delays[i] = __bswap_16(delays[i]); } } ~PI2File() { delete[] bitmap_data; } void print_properties() { std::cout << "Resolution: " << resolution << std::endl; for (int i = 0; i < 16; ++i) { std::cout << "Color " << i << ": 0x" << std::hex << palette[i] << std::dec << std::endl; } std::cout << "Bitmap data size: 32000 bytes" << std::endl; std::cout << "Left color animation limits: "; for (int i = 0; i < 4; ++i) { std::cout << left_limits[i] << " "; } std::cout << std::endl; std::cout << "Right color animation limits: "; for (int i = 0; i < 4; ++i) { std::cout << right_limits[i] << " "; } std::cout << std::endl; std::cout << "Animation channel directions: "; for (int i = 0; i < 4; ++i) { std::cout << directions[i] << " "; } std::cout << std::endl; std::cout << "Animation channel delays: "; for (int i = 0; i < 4; ++i) { std::cout << delays[i] << " "; } std::cout << std::endl; } void write(const std::string& filename) { std::ofstream file(filename, std::ios::binary); uint16_t be_res = __bswap_16(resolution); file.write(reinterpret_cast(&be_res), 2); for (int i = 0; i < 16; ++i) { uint16_t be_color = __bswap_16(palette[i]); file.write(reinterpret_cast(&be_color), 2); } file.write(reinterpret_cast(bitmap_data), 32000); for (int i = 0; i < 4; ++i) { uint16_t be_limit = __bswap_16(left_limits[i]); file.write(reinterpret_cast(&be_limit), 2); } for (int i = 0; i < 4; ++i) { uint16_t be_limit = __bswap_16(right_limits[i]); file.write(reinterpret_cast(&be_limit), 2); } for (int i = 0; i < 4; ++i) { uint16_t be_dir = __bswap_16(directions[i]); file.write(reinterpret_cast(&be_dir), 2); } for (int i = 0; i < 4; ++i) { uint16_t be_delay = __bswap_16(delays[i]); file.write(reinterpret_cast(&be_delay), 2); } } }; // ===== end task-548 .PI2 ===== // ===== task-549 .PIE [C++] ===== #include #include #include #include #include #include class PieFileHandler { private: std::string filepath; std::vector> records; std::map> fieldNames; public: PieFileHandler(std::string filepath) : filepath(filepath) { fieldNames["IR852_0003"] = {"PIE Return type", "Version Number", "PIE Name", "IR Number", "Period End Date", "Total investment asset value", "Gross Income", "Deductible Expenses", "Net Income/Loss", "Net Land Class Income/Loss", "Combined Income/Loss", "Formation Loss Used", "Land Class Loss Brought Forward", "Land Class Loss amount to Carry Forward", "Land Class Loss claimed", "Taxable Income", "Taxable Loss", "Income/Loss not attributed Taxed @ Top PIR", "Income/Loss of Exited Zero-rate Investors", "Investor expenses less credits for fees", "Total Income To Attribute", "Total Loss To Attribute", "Income Attributed to 0% PIR", "Loss Attributed to 0% PIR", "Income Attributed to Low PIR", "Loss Attributed to Low PIR", "Income Attributed to Mid PIR", "Loss Attributed to Mid PIR", "Income Attributed to Top PIR", "Loss Attributed to Top PIR", "Tax Liability/Credit", "Zero-rated Exited Investor’s Tax payment for Exit Period", "Net Tax Liability/Credit", "Foreign Tax Credit", "Other Tax Credits", "Imputation Credit", "Resident Withholding Tax"}; fieldNames["IR852_0004"] = {"PIE Return type", "Version Number", "PIE Name", "IR Number", "Period End Date", "Total investment asset value", "Gross Income", "Deductible Expenses", "Net Income/Loss", "Net Land Class Income/Loss", "Combined Income/Loss", "Formation Loss Used", "Land Class Loss Brought Forward", "Land Class Loss amount to Carry Forward", "Land Class Loss claimed", "Taxable Income", "Taxable Loss", "Income/Loss not attributed Taxed @ Top PIR", "Income/Loss of Exited Zero-rate Investors", "Investor expenses less credits for fees", "Total Income To Attribute", "Total Loss To Attribute", "Income Attributed to 0% PIR", "Loss Attributed to 0% PIR", "Income Attributed to Low PIR", "Loss Attributed to Low PIR", "Income Attributed to Mid PIR", "Loss Attributed to Mid PIR", "Income Attributed to Top PIR", "Loss Attributed to Top PIR", "Tax Liability/Credit", "Zero-rated Exited Investor’s Tax payment for Exit Period", "Net Tax Liability/Credit", "Foreign Tax Credit", "Other Tax Credits", "Imputation Credit", "Resident Withholding Tax", "Income Attributed to NFI", "Tax paid on NFI Income"}; fieldNames["IR853_0003"] = {"PIE Return type", "Version Number", "PIE Name", "IR Number", "Period End Date", "Total Number of Certificates", "Taxable Income/Loss", "Total Tax Credits used for low, mid and top PIR Investors", "PIE Tax Paid / Credited on Investor’s Income for low, mid and top PIR", "Taxable Income/Loss Taxed at low and/or mid rate(s)", "PIE Tax Paid / Credited on Investor’s Income at low and/or mid rate(s)", "Total Tax Credits on Investor’s income low and/or mid rate(s)", "Zero-rated Exited Investor Taxable Income / Loss", "Total Zero-rated Attributed Foreign Tax Credits", "Total Zero-rated Attributed Other /MAC Tax Credits", "Total Zero-rated Attributed IC Tax Credits", "Total Zero-rated Attributed RWT Tax Credits", "Zero-rated Exited Investor’s Tax payment for Exit Period"}; fieldNames["IR853_0004"] = {"PIE Return type", "Version Number", "PIE Name", "IR Number", "Period End Date", "Total Number of Certificates", "Total Income/Loss", "Total Tax Credits used", "PIE Tax Paid / Credited", "Taxable Income/Loss Taxed at low and/or mid rate(s)", "PIE Tax Paid / Credited on Investor’s Income at low and/or mid rate(s)", "Total Tax Credits on Investor’s income low and/or mid rate(s)", "Zero-rated Exited Investor Taxable Income / Loss", "Total Zero-rated Attributed Foreign Tax Credits", "Total Zero-rated Attributed Other /MAC Tax Credits", "Total Zero-rated Attributed IC Tax Credits", "Total Zero-rated Attributed RWT Tax Credits", "Zero-rated Exited Investor’s Tax payment for Exit Period"}; fieldNames["PIEC"] = {"Detail record indicator Parent", "PIE Return Type", "Version Number", "PIE Name", "PIE IR Number", "Period End Date", "Investor’s Name", "Investor’s IR Number", "Investor Certificate Identifier", "Prescribed Investor Rate (PIR) as at Year-end", "Was PIR changed during the year?", "Total Income/Loss", "Taxable Income/Loss", "PIE Tax Paid / Credited", "Foreign Tax Credits", "Other Tax Credits", "Imputation Credits", "Resident Withholding Tax", "Units Held at Year-end", "Country Code", "Address Line 1", "Address Line 2", "Address Line 3", "Post Code", "Country", "Email Address", "Phone Number", "Number of Joint Holders", "Joint Holder 1 Name", "Joint Holder 1 IR Number"}; fieldNames["PIEJ"] = {"Detail record indicator Joint", "Joint Holder Name", "Joint Holder IR Number"}; } void read() { std::ifstream file(filepath); std::string line; while (std::getline(file, line)) { if (line.empty()) continue; std::stringstream ss(line); std::string field; std::vector fields; while (std::getline(ss, field, ',')) { fields.push_back(field); } std::string type = fields[0]; std::string version = fields.size() > 1 ? fields[1] : ""; std::string key = (type == "PIEC" || type == "PIEJ") ? type : type + "_" + version; if (fieldNames.count(key) && fields.size() == fieldNames[key].size()) { std::map record; for (size_t i = 0; i < fieldNames[key].size(); ++i) { record[fieldNames[key][i]] = fields[i]; } records.push_back(record); } } } void printProperties() { read(); for (size_t i = 0; i < records.size(); ++i) { std::cout << "Record " << (i + 1) << ":" << std::endl; for (const auto& pair : records[i]) { std::cout << " " << pair.first << ": " << pair.second << std::endl; } } } void write(const std::vector>& newRecords) { std::ofstream file(filepath); for (const auto& record : newRecords) { std::string type = record.count("PIE Return type") ? record.at("PIE Return type") : (record.count("Detail record indicator Parent") ? "PIEC" : "PIEJ"); std::string version = record.count("Version Number") ? record.at("Version Number") : ""; std::string key = (type == "PIEC" || type == "PIEJ") ? type : type + "_" + version; if (fieldNames.count(key)) { for (size_t i = 0; i < fieldNames[key].size(); ++i) { auto it = record.find(fieldNames[key][i]); file << (it != record.end() ? it->second : "") << (i < fieldNames[key].size() - 1 ? "," : ""); } file << std::endl; } } } }; int main() { PieFileHandler handler("example.pie"); handler.printProperties(); // handler.write({}); return 0; } // ===== end task-549 .PIE ===== // ===== task-550 .PIR [C++] ===== #include #include #include #include #include struct Entry { std::string typeCode; std::string id; std::string description; std::string sequence; std::vector optionalLines; }; class PirFile { private: std::vector entries; public: void read(const std::string& filepath) { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file" << std::endl; return; } entries.clear(); std::string line; Entry current; bool inSequence = false; while (std::getline(file, line)) { if (line[0] == '>') { if (!current.typeCode.empty()) { entries.push_back(current); } current = Entry(); std::string header = line.substr(1); size_t semiPos = header.find(';'); if (semiPos != std::string::npos) { current.typeCode = header.substr(0, semiPos); current.id = header.substr(semiPos + 1); } else { current.typeCode = header; } inSequence = false; } else if (!current.description.empty() == false) { current.description = line; // Trim whitespace current.description.erase(0, current.description.find_first_not_of(" \t")); current.description.erase(current.description.find_last_not_of(" \t") + 1); inSequence = true; } else if (inSequence) { std::string stripped = line; // Remove spaces stripped.erase(std::remove_if(stripped.begin(), stripped.end(), isspace), stripped.end()); size_t starPos = stripped.find('*'); if (starPos != std::string::npos) { current.sequence += stripped.substr(0, starPos); inSequence = false; } else { current.sequence += stripped; } } else { std::string opt = line; opt.erase(0, opt.find_first_not_of(" \t")); opt.erase(opt.find_last_not_of(" \t") + 1); if (!opt.empty()) { current.optionalLines.push_back(opt); } } } if (!current.typeCode.empty()) { entries.push_back(current); } file.close(); } void printProperties() const { for (size_t i = 0; i < entries.size(); ++i) { const Entry& entry = entries[i]; std::cout << "Entry " << (i + 1) << ":" << std::endl; std::cout << " Type Code: " << entry.typeCode << std::endl; std::cout << " Sequence ID: " << entry.id << std::endl; std::cout << " Description: " << entry.description << std::endl; std::cout << " Sequence: " << entry.sequence << std::endl; std::cout << " Optional Lines: "; for (size_t j = 0; j < entry.optionalLines.size(); ++j) { std::cout << entry.optionalLines[j]; if (j < entry.optionalLines.size() - 1) std::cout << ", "; } std::cout << std::endl << std::endl; } } void write(const std::string& filepath) const { std::ofstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file for write" << std::endl; return; } for (const auto& entry : entries) { file << ">" << entry.typeCode << ";" << entry.id << "\n"; file << entry.description << "\n"; std::string seq = entry.sequence; for (size_t i = 0; i < seq.length(); i += 60) { file << seq.substr(i, 60) << "\n"; } file << "*\n"; for (const auto& opt : entry.optionalLines) { file << opt << "\n"; } } file.close(); } }; // Example usage: // int main() { // PirFile pir; // pir.read("example.pir"); // pir.printProperties(); // pir.write("output.pir"); // return 0; // } // ===== end task-550 .PIR ===== // ===== task-551 .PIT [C] ===== #include #include #include #include typedef struct { uint32_t magic; uint32_t entry_count; uint32_t unknown1; uint32_t unknown2; uint16_t unknown3; uint16_t unknown4; uint16_t unknown5; uint16_t unknown6; uint16_t unknown7; uint16_t unknown8; } pit_header_t; typedef struct { uint32_t binary_type; uint32_t device_type; uint32_t identifier; uint32_t attributes; uint32_t update_attributes; uint32_t block_size_or_offset; uint32_t block_count; uint32_t file_offset; uint32_t file_size; char partition_name[32]; char flash_file_name[32]; char fota_file_name[32]; } pit_entry_t; typedef struct { pit_header_t header; pit_entry_t *entries; } pit_file_t; void pit_read(const char *filename, pit_file_t *pit) { FILE *fp = fopen(filename, "rb"); if (!fp) { perror("Failed to open file"); exit(1); } fseek(fp, 0, SEEK_END); long size = ftell(fp); fseek(fp, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, fp); fclose(fp); uint8_t *ptr = data; memcpy(&pit->header, ptr, sizeof(pit_header_t)); ptr += sizeof(pit_header_t); if (pit->header.magic != 0x12349876) { fprintf(stderr, "Invalid .PIT magic\n"); free(data); exit(1); } pit->entries = malloc(pit->header.entry_count * sizeof(pit_entry_t)); memcpy(pit->entries, ptr, pit->header.entry_count * sizeof(pit_entry_t)); free(data); } void pit_print_properties(const pit_file_t *pit) { printf("Header:\n"); printf(" magic: 0x%x\n", pit->header.magic); printf(" entry_count: %u\n", pit->header.entry_count); printf(" unknown1: %u\n", pit->header.unknown1); printf(" unknown2: %u\n", pit->header.unknown2); printf(" unknown3: %u\n", pit->header.unknown3); printf(" unknown4: %u\n", pit->header.unknown4); printf(" unknown5: %u\n", pit->header.unknown5); printf(" unknown6: %u\n", pit->header.unknown6); printf(" unknown7: %u\n", pit->header.unknown7); printf(" unknown8: %u\n", pit->header.unknown8); printf("\nPartitions:\n"); for (uint32_t i = 0; i < pit->header.entry_count; i++) { pit_entry_t *e = &pit->entries[i]; printf("Partition %u:\n", i + 1); printf(" binary_type: %u\n", e->binary_type); printf(" device_type: %u\n", e->device_type); printf(" identifier: %u\n", e->identifier); printf(" attributes: %u\n", e->attributes); printf(" update_attributes: %u\n", e->update_attributes); printf(" block_size_or_offset: %u\n", e->block_size_or_offset); printf(" block_count: %u\n", e->block_count); printf(" file_offset: %u\n", e->file_offset); printf(" file_size: %u\n", e->file_size); printf(" partition_name: %s\n", e->partition_name); printf(" flash_file_name: %s\n", e->flash_file_name); printf(" fota_file_name: %s\n", e->fota_file_name); } } void pit_write(const char *output_filename, const pit_file_t *pit) { FILE *fp = fopen(output_filename, "wb"); if (!fp) { perror("Failed to open output file"); exit(1); } fwrite(&pit->header, sizeof(pit_header_t), 1, fp); fwrite(pit->entries, sizeof(pit_entry_t), pit->header.entry_count, fp); fclose(fp); } void pit_free(pit_file_t *pit) { free(pit->entries); } // Example usage: int main() { pit_file_t pit; pit_read("example.pit", &pit); pit_print_properties(&pit); pit_write("output.pit", &pit); pit_free(&pit); return 0; } // ===== end task-551 .PIT ===== // ===== task-552 .PK3 [C++] ===== #include #include #include #include #include #include #include #include // For crc32 class PK3Handler { private: std::string filename; std::map archive_props; // Using uint64 for large vals std::vector> file_props; // String for simplicity public: PK3Handler(const std::string& fn = "") : filename(fn) { if (!fn.empty()) read(); } void read() { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) return; std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); std::vector buffer(size); file.read(buffer.data(), size); parse(buffer); } void parse(const std::vector& data) { // Find EOCD size_t eocd_offset = data.size() - 22; while (eocd_offset > 0) { uint32_t sig; memcpy(&sig, data.data() + eocd_offset, 4); if (sig == 0x06054B50) break; --eocd_offset; } if (eocd_offset == 0) return; // Invalid // Parse EOCD uint16_t num_this_disk, disk_cd_start, num_cd_this_disk, total_cd; uint32_t size_cd, offset_cd; uint16_t comment_len; memcpy(&num_this_disk, data.data() + eocd_offset + 4, 2); memcpy(&disk_cd_start, data.data() + eocd_offset + 6, 2); memcpy(&num_cd_this_disk, data.data() + eocd_offset + 8, 2); memcpy(&total_cd, data.data() + eocd_offset + 10, 2); memcpy(&size_cd, data.data() + eocd_offset + 12, 4); memcpy(&offset_cd, data.data() + eocd_offset + 16, 4); memcpy(&comment_len, data.data() + eocd_offset + 20, 2); archive_props["signature"] = 0x06054B50; archive_props["number_of_this_disk"] = num_this_disk; archive_props["disk_central_start"] = disk_cd_start; archive_props["num_cd_records_this_disk"] = num_cd_this_disk; archive_props["total_cd_records"] = total_cd; archive_props["size_central_dir"] = size_cd; archive_props["offset_central_dir"] = offset_cd; std::string comment(data.begin() + eocd_offset + 22, data.begin() + eocd_offset + 22 + comment_len); // Store as string in map? Use separate or cast later // ZIP64 stub // Parse CD size_t cd_offset = offset_cd; for (uint16_t i = 0; i < total_cd; ++i) { uint32_t cd_sig; memcpy(&cd_sig, data.data() + cd_offset, 4); if (cd_sig != 0x02014B50) break; std::map fp; uint16_t version_made, version_needed, bit_flag, comp_method, mod_time, mod_date; uint32_t crc, comp_size, uncomp_size; uint16_t name_len, extra_len, comment_len; uint16_t disk_start, int_attr; uint32_t ext_attr, rel_offset; memcpy(&version_made, data.data() + cd_offset + 4, 2); memcpy(&version_needed, data.data() + cd_offset + 6, 2); memcpy(&bit_flag, data.data() + cd_offset + 8, 2); memcpy(&comp_method, data.data() + cd_offset + 10, 2); memcpy(&mod_time, data.data() + cd_offset + 12, 2); memcpy(&mod_date, data.data() + cd_offset + 14, 2); memcpy(&crc, data.data() + cd_offset + 16, 4); memcpy(&comp_size, data.data() + cd_offset + 20, 4); memcpy(&uncomp_size, data.data() + cd_offset + 24, 4); memcpy(&name_len, data.data() + cd_offset + 28, 2); memcpy(&extra_len, data.data() + cd_offset + 30, 2); memcpy(&comment_len, data.data() + cd_offset + 32, 2); memcpy(&disk_start, data.data() + cd_offset + 34, 2); memcpy(&int_attr, data.data() + cd_offset + 36, 2); memcpy(&ext_attr, data.data() + cd_offset + 38, 4); memcpy(&rel_offset, data.data() + cd_offset + 42, 4); std::string file_name(data.begin() + cd_offset + 46, data.begin() + cd_offset + 46 + name_len); std::string extra(data.begin() + cd_offset + 46 + name_len, data.begin() + cd_offset + 46 + name_len + extra_len); std::string file_comment(data.begin() + cd_offset + 46 + name_len + extra_len, data.begin() + cd_offset + 46 + name_len + extra_len + comment_len); fp["file_name"] = file_name; fp["file_comment"] = file_comment; // Add others as strings fp["version_made_by"] = std::to_string(version_made); fp["version_needed"] = std::to_string(version_needed); fp["general_bit_flag"] = std::to_string(bit_flag); fp["compression_method"] = std::to_string(comp_method); fp["last_mod_time"] = std::to_string(mod_time); fp["last_mod_date"] = std::to_string(mod_date); fp["crc32"] = std::to_string(crc); fp["compressed_size"] = std::to_string(comp_size); fp["uncompressed_size"] = std::to_string(uncomp_size); fp["disk_number_start"] = std::to_string(disk_start); fp["internal_attributes"] = std::to_string(int_attr); fp["external_attributes"] = std::to_string(ext_attr); fp["relative_offset_local"] = std::to_string(rel_offset); // Extra parse for ZIP64 file_props.push_back(fp); cd_offset += 46 + name_len + extra_len + comment_len; } } void print_properties() { std::cout << "Archive Properties:" << std::endl; for (const auto& p : archive_props) { std::cout << " " << p.first << ": " << p.second << std::endl; } std::cout << "\nFile Properties:" << std::endl; for (size_t i = 0; i < file_props.size(); ++i) { std::cout << "File " << (i + 1) << ":" << std::endl; for (const auto& fp : file_props[i]) { std::cout << " " << fp.first << ": " << fp.second << std::endl; } } } void write(const std::string& output_filename, const std::map& files_to_add) { std::ofstream out(output_filename, std::ios::binary); size_t offset = 0; std::vector cd_headers; for (const auto& entry : files_to_add) { const std::string& name = entry.first; const std::string& content = entry.second; uLong crc = crc32(0L, reinterpret_cast(content.data()), content.size()); uint32_t size = content.size(); // Local header uint32_t local_sig = 0x04034B50; out.write(reinterpret_cast(&local_sig), 4); uint16_t version = 20; out.write(reinterpret_cast(&version), 2); uint16_t flag = 0; out.write(reinterpret_cast(&flag), 2); uint16_t comp = 0; out.write(reinterpret_cast(&comp), 2); // no comp uint16_t time = 0; out.write(reinterpret_cast(&time), 2); uint16_t date = 0; out.write(reinterpret_cast(&date), 2); out.write(reinterpret_cast(&crc), 4); out.write(reinterpret_cast(&size), 4); out.write(reinterpret_cast(&size), 4); uint16_t name_len = name.size(); out.write(reinterpret_cast(&name_len), 2); uint16_t extra_len = 0; out.write(reinterpret_cast(&extra_len), 2); out << name; out << content; // CD header std::vector cd_entry(46 + name.size()); uint32_t cd_sig = 0x02014B50; memcpy(cd_entry.data(), &cd_sig, 4); memcpy(cd_entry.data() + 4, &version, 2); uint16_t version_needed = 20; memcpy(cd_entry.data() + 6, &version_needed, 2); memcpy(cd_entry.data() + 8, &flag, 2); memcpy(cd_entry.data() + 10, &comp, 2); memcpy(cd_entry.data() + 12, &time, 2); memcpy(cd_entry.data() + 14, &date, 2); memcpy(cd_entry.data() + 16, &crc, 4); memcpy(cd_entry.data() + 20, &size, 4); memcpy(cd_entry.data() + 24, &size, 4); memcpy(cd_entry.data() + 28, &name_len, 2); uint16_t zero = 0; memcpy(cd_entry.data() + 30, &zero, 2); // extra memcpy(cd_entry.data() + 32, &zero, 2); // comment memcpy(cd_entry.data() + 34, &zero, 2); // disk memcpy(cd_entry.data() + 36, &zero, 2); // int attr uint32_t ext_attr = 0; memcpy(cd_entry.data() + 38, &ext_attr, 4); uint32_t rel_off = static_cast(offset); memcpy(cd_entry.data() + 42, &rel_off, 4); memcpy(cd_entry.data() + 46, name.data(), name.size()); cd_headers.insert(cd_headers.end(), cd_entry.begin(), cd_entry.end()); offset = out.tellp(); } size_t cd_offset = offset; out.write(cd_headers.data(), cd_headers.size()); // EOCD uint32_t eocd_sig = 0x06054B50; out.write(reinterpret_cast(&eocd_sig), 4); uint16_t zero16 = 0; out.write(reinterpret_cast(&zero16), 2); out.write(reinterpret_cast(&zero16), 2); uint16_t num_files = files_to_add.size(); out.write(reinterpret_cast(&num_files), 2); out.write(reinterpret_cast(&num_files), 2); uint32_t cd_size = cd_headers.size(); out.write(reinterpret_cast(&cd_size), 4); uint32_t cd_off = static_cast(cd_offset); out.write(reinterpret_cast(&cd_off), 4); out.write(reinterpret_cast(&zero16), 2); // comment len } }; int main(int argc, char* argv[]) { if (argc > 1) { PK3Handler handler(argv[1]); handler.print_properties(); // To write: std::map files = {{"test.txt", "Hello"}}; handler.write("output.pk3", files); } return 0; } // ===== end task-552 .PK3 ===== // ===== task-553 .PKA [C++] ===== #include #include #include #include #include #include #include #include // Assume tinyxml2 for XML parsing class PKAFile { private: std::string filename; std::string xml; tinyxml2::XMLDocument doc; public: PKAFile(const std::string& fn) : filename(fn) {} std::vector reverseXor(const std::vector& data) { size_t length = data.size(); uint8_t k = static_cast(length); std::vector temp(length); for (size_t i = 0; i < length; ++i) { uint8_t ch = data[length - i - 1]; uint8_t a = static_cast(k * static_cast(i)); uint8_t c = static_cast(length - a); temp[i] = c ^ ch; } return temp; } std::vector forwardXor(const std::vector& data) { size_t length = data.size(); std::vector temp = data; for (size_t i = 0; i < length; ++i) { uint8_t key = static_cast(length - i); temp[i] ^= key; } return temp; } std::vector twofishDecrypt(const std::vector& data) { byte key[CryptoPP::Twofish::DEFAULT_KEYLENGTH]; byte iv[CryptoPP::Twofish::BLOCKSIZE]; std::fill(key, key + sizeof(key), 0x89); std::fill(iv, iv + sizeof(iv), 0x10); std::string plain; CryptoPP::CBC_Mode::Decryption d(key, sizeof(key), iv); CryptoPP::StringSource ss(data.data(), data.size(), true, new CryptoPP::StreamTransformationFilter(d, new CryptoPP::StringSink(plain) ) ); return std::vector(plain.begin(), plain.end()); } std::vector decompress(const std::vector& data) { uint32_t uncompSize = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]; std::vector xmlBytes(uncompSize); z_stream infstream; infstream.zalloc = Z_NULL; infstream.zfree = Z_NULL; infstream.opaque = Z_NULL; infstream.avail_in = data.size() - 4; infstream.next_in = const_cast(&data[4]); infstream.avail_out = uncompSize; infstream.next_out = &xmlBytes[0]; inflateInit(&infstream); inflate(&infstream, Z_NO_FLUSH); inflateEnd(&infstream); return xmlBytes; } void read() { std::ifstream file(filename, std::ios::binary); std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); data = reverseXor(data); data = twofishDecrypt(data); data = forwardXor(data); auto xmlBytes = decompress(data); xml = std::string(xmlBytes.begin(), xmlBytes.end()); for (char& c : xml) if (c < 9) c = '?'; doc.Parse(xml.c_str()); } void printProperties() { if (doc.IsEmpty()) read(); auto root = doc.RootElement(); std::cout << "Root: " << root->Name() << std::endl; std::cout << "Version: " << root->FirstChildElement("VERSION")->GetText() << std::endl; tinyxml2::XMLElement* network = root->FirstChildElement("NETWORK"); auto device = network->FirstChildElement("DEVICES")->FirstChildElement("DEVICE"); int count = 0; while (device) { count++; std::cout << "Device " << count << ":" << std::endl; auto engine = device->FirstChildElement("ENGINE"); std::cout << " Type: " << engine->FirstChildElement("TYPE")->GetText() << std::endl; std::cout << " Model: " << engine->FirstChildElement("TYPE")->Attribute("model") << std::endl; std::cout << " Name: " << engine->FirstChildElement("NAME")->GetText() << std::endl; std::cout << " Power: " << engine->FirstChildElement("POWER")->GetText() << std::endl; std::cout << " Description: " << engine->FirstChildElement("DESCRIPTION")->GetText() << std::endl; device = device->NextSiblingElement("DEVICE"); } std::cout << "Network Devices: " << count << std::endl; // Add for other properties } std::vector compress(const std::vector& xmlBytes) { uLongf compSize = compressBound(xmlBytes.size()); std::vector compressed(compSize); compress(&compressed[0], &compSize, &xmlBytes[0], xmlBytes.size()); compressed.resize(compSize); std::vector result(4 + compSize); result[0] = (xmlBytes.size() >> 24) & 0xFF; result[1] = (xmlBytes.size() >> 16) & 0xFF; result[2] = (xmlBytes.size() >> 8) & 0xFF; result[3] = xmlBytes.size() & 0xFF; std::copy(compressed.begin(), compressed.end(), result.begin() + 4); return result; } std::vector twofishEncrypt(const std::vector& data) { byte key[CryptoPP::Twofish::DEFAULT_KEYLENGTH]; byte iv[CryptoPP::Twofish::BLOCKSIZE]; std::fill(key, key + sizeof(key), 0x89); std::fill(iv, iv + sizeof(iv), 0x10); std::string cipher; CryptoPP::CBC_Mode::Encryption e(key, sizeof(key), iv); CryptoPP::StringSource ss(data.data(), data.size(), true, new CryptoPP::StreamTransformationFilter(e, new CryptoPP::StringSink(cipher) ) ); return std::vector(cipher.begin(), cipher.end()); } std::vector reverseXorEncode(const std::vector& data) { size_t length = data.size(); uint8_t k = static_cast(length); std::vector temp(length); for (size_t i = 0; i < length; ++i) { uint8_t c = data[i]; uint8_t a = static_cast(k * static_cast(i)); uint8_t key = static_cast(length - a); uint8_t ch = c ^ key; temp[length - i - 1] = ch; } return temp; } void write(const std::string& newFilename) { if (xml.empty()) return; std::vector xmlBytes(xml.begin(), xml.end()); auto data = compress(xmlBytes); data = forwardXor(data); data = twofishEncrypt(data); data = reverseXorEncode(data); std::ofstream file(newFilename, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); file.close(); } }; // ===== end task-553 .PKA ===== // ===== task-554 .PKG [C] ===== #include #include #include #include #include // Assume tinyxml or manual XML parsing; here, stubbed with simple string search for demo // In production, link with libxml2 or similar for full XML parse typedef struct { char* filepath; uint32_t magic; uint16_t hsize; uint16_t version; uint64_t toc_comp_len; uint64_t toc_uncomp_len; uint32_t cksum_alg; char* toc_xml; // Raw XML string // Properties would be parsed into a list of structs; stubbed } PkgHandler; PkgHandler* pkg_create(const char* filepath) { PkgHandler* handler = (PkgHandler*)malloc(sizeof(PkgHandler)); handler->filepath = strdup(filepath); handler->toc_xml = NULL; return handler; } void pkg_read(PkgHandler* handler) { FILE* f = fopen(handler->filepath, "rb"); if (!f) { perror("Failed to open file"); return; } fseek(f, 0, SEEK_END); long filesize = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = (uint8_t*)malloc(filesize); fread(data, 1, filesize, f); fclose(f); // Parse header (big-endian manual) handler->magic = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]; if (handler->magic != 0x78617221) { printf("Invalid PKG/XAR magic\n"); free(data); return; } handler->hsize = (data[4] << 8) | data[5]; handler->version = (data[6] << 8) | data[7]; handler->toc_comp_len = ((uint64_t)data[8] << 56) | ((uint64_t)data[9] << 48) | ((uint64_t)data[10] << 40) | ((uint64_t)data[11] << 32) | ((uint64_t)data[12] << 24) | ((uint64_t)data[13] << 16) | ((uint64_t)data[14] << 8) | data[15]; handler->toc_uncomp_len = ((uint64_t)data[16] << 56) | ((uint64_t)data[17] << 48) | ((uint64_t)data[18] << 40) | ((uint64_t)data[19] << 32) | ((uint64_t)data[20] << 24) | ((uint64_t)data[21] << 16) | ((uint64_t)data[22] << 8) | data[23]; handler->cksum_alg = (data[24] << 24) | (data[25] << 16) | (data[26] << 8) | data[27]; // Extract compressed TOC uint8_t* toc_comp = data + handler->hsize; uLongf uncomp_len = handler->toc_uncomp_len; handler->toc_xml = (char*)malloc(uncomp_len + 1); int ret = uncompress((Bytef*)handler->toc_xml, &uncomp_len, (Bytef*)toc_comp, handler->toc_comp_len); if (ret != Z_OK) { printf("TOC decompression failed: %d\n", ret); free(handler->toc_xml); handler->toc_xml = NULL; } handler->toc_xml[uncomp_len] = '\0'; // Null-terminate free(data); } void pkg_print_properties(PkgHandler* handler) { if (!handler->toc_xml) { printf("No TOC loaded. Call pkg_read first.\n"); return; } // Stub: In full impl, parse XML with libxml2 and print properties // Here, just print raw TOC XML as demo printf("TOC XML (properties embedded):\n%s\n", handler->toc_xml); // Extend to extract and print name, type, etc. } void pkg_write(PkgHandler* handler, const char* new_filepath) { if (!handler->toc_xml) { printf("No TOC loaded. Call pkg_read first.\n"); return; } // Stub: Compress TOC, build header, write file (heap not included) printf("Write stub: Would write to %s\n", new_filepath); // Implement full compression and write here } void pkg_destroy(PkgHandler* handler) { free(handler->filepath); free(handler->toc_xml); free(handler); } // Example usage: // int main() { // PkgHandler* handler = pkg_create("example.pkg"); // pkg_read(handler); // pkg_print_properties(handler); // pkg_write(handler, "modified.pkg"); // pkg_destroy(handler); // return 0; // } // ===== end task-554 .PKG ===== // ===== task-555 .PKL [C++] ===== #include #include #include #include #include #include struct OpcodeInfo { uint8_t code; std::string name; std::string argType; }; class PklHandlerCpp { private: OpcodeInfo opcodes[69] = { {0x28, "MARK", "none"}, // ... (add all opcodes similar to above, omitted for brevity) {0x98, "READONLY_BUFFER", "none"} }; public: std::vector readPkl(const std::string& filename) { std::ifstream file(filename, std::ios::binary); std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); size_t offset = 0; std::cout << "Dumped PKL properties (opcodes and arguments):" << std::endl; while (offset < data.size()) { uint8_t code = data[offset]; offset++; std::string name = "Unknown"; std::string argType = "none"; for (const auto& op : opcodes) { if (op.code == code) { name = op.name; argType = op.argType; break; } } std::cout << "Opcode: " << name << " (0x" << std::hex << static_cast(code) << ")" << std::endl; // Parsing logic similar to Python/JS // For brevity, implement similar switch for argType using memcpy for structs, loops for strings, etc. // Example for u1: // if (argType == "u1") { // uint8_t arg; memcpy(&arg, &data[offset], 1); offset += 1; // std::cout << "Arg: " << static_cast(arg) << std::endl; // } // Add for all types... } return data; } void writePkl(const std::string& filename, const std::vector& data) { std::ofstream file(filename, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); } }; int main(int argc, char** argv) { if (argc < 2) { std::cout << "Usage: ./program input.pkl [output.pkl]" << std::endl; return 1; } PklHandlerCpp handler; auto data = handler.readPkl(argv[1]); if (argc > 2) { handler.writePkl(argv[2], data); } return 0; } // ===== end task-555 .PKL ===== // ===== task-556 .PL [C] ===== #include #include #include #include #include #include typedef struct { char *filepath; struct stat properties; } PLFileHandler; PLFileHandler* PLFileHandler_create(const char *filepath) { if (strstr(filepath, ".pl") != filepath + strlen(filepath) - 3) { fprintf(stderr, "File must have .pl extension\n"); return NULL; } PLFileHandler *handler = malloc(sizeof(PLFileHandler)); handler->filepath = strdup(filepath); if (stat(handler->filepath, &handler->properties) != 0) { free(handler->filepath); free(handler); return NULL; } return handler; } void PLFileHandler_printProperties(PLFileHandler *handler) { if (handler == NULL) return; char time_buf[64]; printf("mode: %o\n", handler->properties.st_mode); printf("inode: %ld\n", handler->properties.st_ino); printf("device_id: %ld\n", handler->properties.st_dev); printf("num_links: %ld\n", handler->properties.st_nlink); printf("owner_uid: %d\n", handler->properties.st_uid); printf("group_gid: %d\n", handler->properties.st_gid); printf("size: %ld\n", handler->properties.st_size); strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", localtime(&handler->properties.st_atime)); printf("last_access: %s\n", time_buf); strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", localtime(&handler->properties.st_mtime)); printf("last_modification: %s\n", time_buf); strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", localtime(&handler->properties.st_ctime)); printf("creation_time: %s\n", time_buf); } char* PLFileHandler_read(PLFileHandler *handler) { if (handler == NULL) return NULL; FILE *f = fopen(handler->filepath, "r"); if (!f) return NULL; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); char *content = malloc(size + 1); fread(content, 1, size, f); content[size] = '\0'; fclose(f); return content; } int PLFileHandler_write(PLFileHandler *handler, const char *content) { if (handler == NULL) return -1; FILE *f = fopen(handler->filepath, "w"); if (!f) return -1; fprintf(f, "%s", content); fclose(f); // Update properties stat(handler->filepath, &handler->properties); return 0; } void PLFileHandler_destroy(PLFileHandler *handler) { if (handler) { free(handler->filepath); free(handler); } } // Example usage // int main() { // PLFileHandler *handler = PLFileHandler_create("example.pl"); // if (handler) { // PLFileHandler_printProperties(handler); // PLFileHandler_destroy(handler); // } // return 0; // } // ===== end task-556 .PL ===== // ===== task-557 .PLANET [C++] ===== #include #include #include #include #include #include class PlanetFile { private: std::string filepath; std::string name; std::string make; std::string frequency; int h_width; int v_width; double front_to_back; std::string gain; std::vector> horizontal; std::vector> vertical; public: PlanetFile(const std::string& fp) : filepath(fp), h_width(0), v_width(0), front_to_back(0.0) {} void read() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file" << std::endl; return; } std::string line, current_section; int section_count = 0; while (std::getline(file, line)) { std::istringstream iss(line); std::string token; iss >> token; if (token == "NAME") { std::getline(iss, name); } else if (token == "MAKE") { std::getline(iss, make); } else if (token == "FREQUENCY") { std::getline(iss, frequency); } else if (token == "H" && (iss >> token) && token == "WIDTH") { iss >> h_width; } else if (token == "V" && (iss >> token) && token == "WIDTH") { iss >> v_width; } else if (token == "FRONT" && (iss >> token) && token == "TO" && (iss >> token) && token == "BACK") { iss >> front_to_back; } else if (token == "GAIN") { std::getline(iss, gain); } else if (token == "HORIZONTAL") { current_section = "horizontal"; iss >> section_count; horizontal.clear(); } else if (token == "VERTICAL") { current_section = "vertical"; iss >> section_count; vertical.clear(); } else if (!current_section.empty() && section_count > 0) { double angle, loss; std::istringstream data_line(line); data_line >> angle >> loss; if (current_section == "horizontal") { horizontal.emplace_back(angle, loss); } else if (current_section == "vertical") { vertical.emplace_back(angle, loss); } section_count--; if (section_count == 0) current_section = ""; } } file.close(); } void print_properties() { std::cout << "NAME: " << name << std::endl; std::cout << "MAKE: " << make << std::endl; std::cout << "FREQUENCY: " << frequency << std::endl; std::cout << "H WIDTH: " << h_width << std::endl; std::cout << "V WIDTH: " << v_width << std::endl; std::cout << "FRONT TO BACK: " << front_to_back << std::endl; std::cout << "GAIN: " << gain << std::endl; std::cout << "HORIZONTAL: " << std::endl; for (const auto& p : horizontal) { std::cout << p.first << " " << p.second << std::endl; } std::cout << "VERTICAL: " << std::endl; for (const auto& p : vertical) { std::cout << p.first << " " << p.second << std::endl; } } void write() { std::ofstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file for write" << std::endl; return; } file << "NAME" << name << "\n"; file << "MAKE" << make << "\n"; file << "FREQUENCY" << frequency << "\n"; file << "H WIDTH " << h_width << "\n"; file << "V WIDTH " << v_width << "\n"; file << "FRONT TO BACK " << front_to_back << "\n"; file << "GAIN" << gain << "\n"; file << "HORIZONTAL " << horizontal.size() << "\n"; for (const auto& p : horizontal) { file << p.first << " " << p.second << "\n"; } file << "VERTICAL " << vertical.size() << "\n"; for (const auto& p : vertical) { file << p.first << " " << p.second << "\n"; } file.close(); } }; // Example usage: // int main() { // PlanetFile pf("example.PLANET"); // pf.read(); // pf.print_properties(); // pf.write(); // return 0; // } // ===== end task-557 .PLANET ===== // ===== task-559 .PLR [C++] ===== #include #include #include #include #include #include #include // Assume OpenSSL for AES class PlrFile { private: std::string filename; std::map properties; // Simplified, use structs for complex types public: PlrFile(const std::string& fn) : filename(fn) { load(); } void decrypt(const std::vector& input, std::vector& output) { unsigned char key[16] = {0x68, 0x00, 0x33, 0x00, 0x79, 0x00, 0x5F, 0x00, 0x67, 0x00, 0x55, 0x00, 0x79, 0x00, 0x5A, 0x00}; AES_KEY aesKey; AES_set_decrypt_key(key, 128, &aesKey); output.resize(input.size()); for (size_t i = 0; i < input.size(); i += 16) { AES_cbc_encrypt(&input[i], &output[i], 16, &aesKey, key, AES_DECRYPT); // IV modified in place } } void load() { std::ifstream file(filename, std::ios::binary); std::vector encrypted((std::istreambuf_iterator(file)), std::istreambuf_iterator()); std::vector decrypted; decrypt(encrypted, decrypted); // Parse decrypted using memcmp or custom readers for little-endian. // Similar to Python, but with pointer offsets. // Omitted full for brevity. } void printProperties() { for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } void write(const std::string& outputFilename) { // Serialize and encrypt. } }; // Usage: PlrFile plr("example.plr"); plr.printProperties(); // ===== end task-559 .PLR ===== // ===== task-560 .PLS [C++] ===== #include #include #include #include #include #include #include struct Entry { std::string file; std::string title; int length = -2; // -2 means not set }; class PLSHandler { private: int version = 2; int numberOfEntries = 0; std::vector entries; public: PLSHandler(const std::string& filepath = "") { if (!filepath.empty()) { read(filepath); } } void read(const std::string& filepath) { std::ifstream file(filepath); if (!file.is_open()) { throw std::runtime_error("Could not open file"); } std::string line; std::getline(file, line); if (line.find("[playlist]") == std::string::npos) { throw std::runtime_error("Invalid PLS file"); } std::map entryMap; std::regex regex(R"(^(\w+)=(.+)$)"); while (std::getline(file, line)) { std::smatch match; if (std::regex_match(line, match, regex)) { std::string key = match[1]; std::string value = match[2]; if (key == "Version") { version = std::stoi(value); } else if (key == "NumberOfEntries") { numberOfEntries = std::stoi(value); } else { std::regex entryRegex(R"(^(\w+)(\d+)$)"); std::smatch entryMatch; if (std::regex_match(key, entryMatch, entryRegex)) { std::string type = entryMatch[1]; int index = std::stoi(entryMatch[2]); if (type == "File") { entryMap[index].file = value; } else if (type == "Title") { entryMap[index].title = value; } else if (type == "Length") { entryMap[index].length = std::stoi(value); } } } } } file.close(); for (auto& pair : entryMap) { entries.push_back(pair.second); } if (entries.size() != static_cast(numberOfEntries)) { throw std::runtime_error("Entry count mismatch"); } } void write(const std::string& filepath) { std::ofstream file(filepath); if (!file.is_open()) { throw std::runtime_error("Could not open file for writing"); } file << "[playlist]\n"; for (size_t i = 0; i < entries.size(); ++i) { size_t idx = i + 1; if (!entries[i].file.empty()) { file << "File" << idx << "=" << entries[i].file << "\n"; } if (!entries[i].title.empty()) { file << "Title" << idx << "=" << entries[i].title << "\n"; } if (entries[i].length != -2) { file << "Length" << idx << "=" << entries[i].length << "\n"; } } file << "NumberOfEntries=" << numberOfEntries << "\n"; file << "Version=" << version << "\n"; file.close(); } void printProperties() { std::cout << "Version: " << version << std::endl; std::cout << "NumberOfEntries: " << numberOfEntries << std::endl; for (size_t i = 0; i < entries.size(); ++i) { std::cout << "Entry " << (i + 1) << ":" << std::endl; std::cout << " File: " << entries[i].file << std::endl; std::cout << " Title: " << entries[i].title << std::endl; std::cout << " Length: " << entries[i].length << std::endl; } } }; // Example usage: // int main() { // try { // PLSHandler handler("example.pls"); // handler.printProperties(); // handler.write("new.pls"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-560 .PLS ===== // ===== task-561 .PM [C] ===== #include #include #include #include typedef struct { char *filename; char *content; char *package_name; char *version; char **inherited_packages; int inherited_count; char **exported_symbols; int exported_count; char **subroutines; int sub_count; char *ending_true; } PMHandler; PMHandler *pm_handler_create(const char *filename) { PMHandler *handler = malloc(sizeof(PMHandler)); handler->filename = strdup(filename); handler->content = NULL; handler->package_name = NULL; handler->version = NULL; handler->inherited_packages = NULL; handler->inherited_count = 0; handler->exported_symbols = NULL; handler->exported_count = 0; handler->subroutines = NULL; handler->sub_count = 0; handler->ending_true = NULL; return handler; } void pm_handler_open_and_read(PMHandler *handler) { FILE *f = fopen(handler->filename, "r"); if (!f) return; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); handler->content = malloc(size + 1); fread(handler->content, 1, size, f); handler->content[size] = '\0'; fclose(f); pm_handler_extract_properties(handler); } void pm_handler_extract_properties(PMHandler *handler) { // Use regex to extract (simplified, C regex is basic, may need pcre) // For brevity, assume simple strstr and parsing // Package name char *pkg = strstr(handler->content, "package "); if (pkg) { pkg += 8; char *end = strchr(pkg, ';'); if (end) { handler->package_name = malloc(end - pkg + 1); strncpy(handler->package_name, pkg, end - pkg); handler->package_name[end - pkg] = '\0'; } } // Version, inherited, exports, subs similar, but skipped for brevity as C regex is complex // Ending if (strstr(handler->content, "1;")) handler->ending_true = strdup("Present"); else handler->ending_true = strdup("Missing"); } void pm_handler_print_properties(PMHandler *handler) { if (handler->package_name) printf("Package Name: %s\n", handler->package_name); if (handler->version) printf("Version: %s\n", handler->version); // Print others similarly printf("Ending True Value: %s\n", handler->ending_true); } void pm_handler_write(PMHandler *handler, const char *new_filename, /* pass new properties as map or struct */ ) { // Similar to other, open file, write string based on properties } void pm_handler_destroy(PMHandler *handler) { free(handler->filename); free(handler->content); free(handler->package_name); free(handler->version); // Free others free(handler->ending_true); free(handler); } // Example usage: // PMHandler *handler = pm_handler_create("example.pm"); // pm_handler_open_and_read(handler); // pm_handler_print_properties(handler); // pm_handler_destroy(handler); // ===== end task-561 .PM ===== // ===== task-562 .PMA [C++] ===== #include #include #include #include #include #include struct Entry { uint8_t headerLen; uint8_t checksum; std::string methodId; uint32_t comprSize; uint32_t uncomprSize; std::tm timestamp; uint8_t attr; uint8_t level; uint16_t crc16; std::string filename; char osType = '\0'; uint16_t extSize = 0; }; class PMAFile { private: std::string filepath; std::vector entries; void parse() { std::ifstream file(filepath, std::ios::binary); if (!file) return; std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); size_t offset = 0; while (offset < data.size()) { uint8_t headerLen = static_cast(data[offset]); if (headerLen == 0) break; offset += 1; uint8_t checksum = static_cast(data[offset]); std::string methodId(&data[offset + 1], &data[offset + 6]); uint32_t comprSize = *reinterpret_cast(&data[offset + 6]); uint32_t uncomprSize = *reinterpret_cast(&data[offset + 10]); uint32_t timestampRaw = *reinterpret_cast(&data[offset + 14]); uint16_t dosDate = (timestampRaw >> 16) & 0xFFFF; uint16_t dosTime = timestampRaw & 0xFFFF; std::tm ts{}; ts.tm_year = 1980 + ((dosDate >> 9) & 0x7F) - 1900; ts.tm_mon = ((dosDate >> 5) & 0x0F) - 1; ts.tm_mday = dosDate & 0x1F; ts.tm_hour = (dosTime >> 11) & 0x1F; ts.tm_min = (dosTime >> 5) & 0x3F; ts.tm_sec = (dosTime & 0x1F) * 2; uint8_t attr = static_cast(data[offset + 18]); uint8_t level = static_cast(data[offset + 19]); offset += 20; Entry entry; entry.headerLen = headerLen; entry.checksum = checksum; entry.methodId = methodId; entry.comprSize = comprSize; entry.uncomprSize = uncomprSize; entry.timestamp = ts; entry.attr = attr; entry.level = level; if (level == 0) { uint8_t fnLen = static_cast(data[offset]); entry.filename = std::string(&data[offset + 1], &data[offset + 1 + fnLen]); offset += 1 + fnLen; } entry.crc16 = *reinterpret_cast(&data[offset]); offset += 2; if (level == 2) { entry.osType = data[offset]; entry.extSize = *reinterpret_cast(&data[offset + 1]); offset += 3 + entry.extSize; } offset += comprSize; // Skip body entries.push_back(entry); } } public: PMAFile(const std::string& filepath) : filepath(filepath) { parse(); } void printProperties() { for (size_t i = 0; i < entries.size(); ++i) { auto& e = entries[i]; std::cout << "Entry " << (i + 1) << ":" << std::endl; std::cout << " Header Length: " << static_cast(e.headerLen) << std::endl; std::cout << " Header Checksum: " << static_cast(e.checksum) << std::endl; std::cout << " Compression Method: " << e.methodId << std::endl; std::cout << " Compressed Size: " << e.comprSize << std::endl; std::cout << " Uncompressed Size: " << e.uncomprSize << std::endl; char timeBuf[20]; std::strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", &e.timestamp); std::cout << " Timestamp: " << timeBuf << std::endl; std::cout << " Attribute: " << static_cast(e.attr) << std::endl; std::cout << " Level: " << static_cast(e.level) << std::endl; if (!e.filename.empty()) { std::cout << " Filename: " << e.filename << std::endl; } std::cout << " Uncompressed CRC16: " << e.crc16 << std::endl; if (e.osType != '\0') { std::cout << " OS Type: " << e.osType << std::endl; std::cout << " Extended Header Size: " << e.extSize << std::endl; } } } void write(const std::string& newFilepath, const std::vector>& newBodies) { std::ofstream file(newFilepath, std::ios::binary); for (const auto& body : newBodies) { uint8_t headerLen = 22; file.put(static_cast(headerLen)); file.put(0); // checksum std::string methodId = "-pm0-"; file.write(methodId.data(), 5); uint32_t comprSize = static_cast(body.size()); file.write(reinterpret_cast(&comprSize), 4); file.write(reinterpret_cast(&comprSize), 4); // uncomprSize std::time_t now = std::time(nullptr); std::tm* local = std::localtime(&now); uint16_t dosDate = ((local->tm_year + 1900 - 1980) << 9) | ((local->tm_mon + 1) << 5) | local->tm_mday; uint16_t dosTime = (local->tm_hour << 11) | (local->tm_min << 5) | (local->tm_sec / 2); uint32_t timestampRaw = (static_cast(dosDate) << 16) | dosTime; file.write(reinterpret_cast(×tampRaw), 4); file.put(0); // attr file.put(0); // level uint16_t crc16 = 0; file.write(reinterpret_cast(&crc16), 2); file.write(body.data(), body.size()); } file.put(0); // End } }; // Example usage: // PMAFile pma("example.pma"); // pma.printProperties(); // pma.write("new.pma", {std::vector{'t', 'e', 's', 't'}}); // ===== end task-562 .PMA ===== // ===== task-563 .PMP [C] ===== #include #include #include // Assume miniz.h for ZIP (https://github.com/richgel999/miniz) // Assume cJSON.h for JSON (https://github.com/DaveGamble/cJSON) #include "miniz.h" #include "cJSON.h" typedef struct { char* filename; cJSON* data; char** assets; int asset_count; } PMPFile; PMPFile* pmp_create(const char* filename) { PMPFile* pmp = malloc(sizeof(PMPFile)); pmp->filename = strdup(filename); pmp->data = NULL; pmp->assets = NULL; pmp->asset_count = 0; return pmp; } void pmp_read(PMPFile* pmp) { mz_zip_archive zip_archive = {0}; if (!mz_zip_reader_init_file(&zip_archive, pmp->filename, 0)) { printf("Error opening ZIP\n"); return; } // Extract and parse project.json size_t json_size; void* json_buf = mz_zip_reader_extract_file_to_heap(&zip_archive, "project.json", &json_size, 0); if (json_buf) { char* json_str = (char*)json_buf; json_str[json_size] = '\0'; pmp->data = cJSON_Parse(json_str); free(json_buf); } // Collect assets int num_files = mz_zip_reader_get_num_files(&zip_archive); pmp->assets = malloc(num_files * sizeof(char*)); for (int i = 0; i < num_files; i++) { mz_zip_archive_file_stat file_stat; mz_zip_reader_file_stat(&zip_archive, i, &file_stat); if (strcmp(file_stat.m_filename, "project.json") != 0) { pmp->assets[pmp->asset_count++] = strdup(file_stat.m_filename); } } mz_zip_reader_end(&zip_archive); } void pmp_print_properties(PMPFile* pmp) { if (pmp->data) { char* printed = cJSON_Print(pmp->data); printf("%s\n", printed); free(printed); } printf("\nAssets:\n"); for (int i = 0; i < pmp->asset_count; i++) { printf("%s\n", pmp->assets[i]); } } void pmp_write(PMPFile* pmp, const char* new_filename) { mz_zip_archive zip_archive = {0}; mz_zip_writer_init_file(&zip_archive, new_filename, 0); if (pmp->data) { char* json_str = cJSON_Print(pmp->data); mz_zip_writer_add_mem(&zip_archive, "project.json", json_str, strlen(json_str), MZ_DEFAULT_COMPRESSION); free(json_str); } // Add assets (would require extracting and re-adding; simplified here as placeholder) mz_zip_writer_finalize_archive(&zip_archive); mz_zip_writer_end(&zip_archive); } void pmp_destroy(PMPFile* pmp) { if (pmp->data) cJSON_Delete(pmp->data); for (int i = 0; i < pmp->asset_count; i++) free(pmp->assets[i]); free(pmp->assets); free(pmp->filename); free(pmp); } // Example usage: // int main() { // PMPFile* pmp = pmp_create("example.pmp"); // pmp_read(pmp); // pmp_print_properties(pmp); // pmp_write(pmp, "modified.pmp"); // pmp_destroy(pmp); // return 0; // } // ===== end task-563 .PMP ===== // ===== task-564 .PNG [C++] ===== #include #include #include #include #include #include #include #include // For CRC, but use crc32 function class PNG { private: std::vector data; std::map> properties; struct Chunk { std::string type; std::vector chunkData; uint32_t crc; }; std::vector chunks; public: PNG(const std::string& filename) { std::ifstream file(filename, std::ios::binary); if (!file) throw std::runtime_error("File not found"); data.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); parse(); } void parse() { if (!checkSignature()) { throw std::runtime_error("Invalid PNG signature"); } properties["signature"]["value"] = "89 50 4E 47 0D 0A 1A 0A"; size_t offset = 8; while (offset < data.size()) { uint32_t length = readUint32(offset); std::string type(reinterpret_cast(&data[offset + 4]), 4); std::vector chunkData(data.begin() + offset + 8, data.begin() + offset + 8 + length); uint32_t crc = readUint32(offset + 8 + length); auto chunkProp = parseChunk(type, chunkData); chunkProp["length"] = std::to_string(length); chunkProp["crc"] = toHex(crc); properties[type] = chunkProp; Chunk chunk; chunk.type = type; chunk.chunkData = chunkData; chunk.crc = crc; chunks.push_back(chunk); offset += 12 + length; if (type == "IEND") break; } } bool checkSignature() { uint8_t sig[8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}; for (int i = 0; i < 8; ++i) { if (data[i] != sig[i]) return false; } return true; } uint32_t readUint32(size_t offset) { return (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]; } std::map parseChunk(const std::string& type, const std::vector& chunkData) { std::map parsed; // Raw data as hex string or something std::ostringstream oss; for (auto b : chunkData) oss << std::hex << std::setw(2) << std::setfill('0') << (int)b << " "; parsed["raw_data"] = oss.str(); if (type == "IHDR") { parsed["width"] = std::to_string(readUint32(0)); parsed["height"] = std::to_string(readUint32(4)); parsed["bit_depth"] = std::to_string(data[8]); // etc. } // Add more return parsed; } std::string toHex(uint32_t val) { std::ostringstream oss; oss << std::hex << std::uppercase << val; return oss.str(); } void printProperties() { for (const auto& [key, val] : properties) { std::cout << key << ": " << std::endl; for (const auto& [subkey, subval] : val) { std::cout << " " << subkey << ": " << subval << std::endl; } } } void write(const std::string& filename) { std::ofstream file(filename, std::ios::binary); uint8_t sig[8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}; file.write(reinterpret_cast(sig), 8); for (const auto& chunk : chunks) { uint32_t length = chunk.chunkData.size(); file.write(reinterpret_cast(&length), 4); // Note: big-endian, assume host is little, swap if needed file.write(chunk.type.c_str(), 4); file.write(reinterpret_cast(chunk.chunkData.data()), length); file.write(reinterpret_cast(&chunk.crc), 4); } } }; // Example: // int main() { // PNG png("example.png"); // png.printProperties(); // png.write("output.png"); // return 0; // } // ===== end task-564 .PNG ===== // ===== task-565 .POM [C++] ===== #include #include #include using namespace tinyxml2; class PomHandler { private: std::string filepath; XMLDocument doc; public: PomHandler(const std::string& fp) : filepath(fp) {} bool read() { if (doc.LoadFile(filepath.c_str()) != XML_SUCCESS) { std::cerr << "Error loading POM: " << doc.ErrorStr() << std::endl; return false; } return true; } void printProperties() { XMLElement* root = doc.FirstChildElement("project"); if (!root) { std::cout << "No project element found." << std::endl; return; } printElement(root, 0); } void printElement(XMLElement* elem, int indent) { std::string indentStr(indent * 2, ' '); std::cout << indentStr << elem->Name() << ":" << std::endl; const char* text = elem->GetText(); if (text && std::string(text).find_first_not_of(" \t\n\r") != std::string::npos) { std::cout << indentStr << " " << text << std::endl; } for (XMLElement* child = elem->FirstChildElement(); child; child = child->NextSiblingElement()) { printElement(child, indent + 1); } } bool write(const std::string& outputPath) { XMLDocument newDoc; XMLDeclaration* decl = newDoc.NewDeclaration(); newDoc.InsertFirstChild(decl); XMLElement* root = newDoc.NewElement("project"); root->SetAttribute("xmlns", "http://maven.apache.org/POM/4.0.0"); root->SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); root->SetAttribute("xsi:schemaLocation", "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"); newDoc.InsertEndChild(root); XMLElement* modelVersion = newDoc.NewElement("modelVersion"); modelVersion->SetText("4.0.0"); root->InsertEndChild(modelVersion); XMLElement* groupId = newDoc.NewElement("groupId"); groupId->SetText("com.example"); root->InsertEndChild(groupId); XMLElement* artifactId = newDoc.NewElement("artifactId"); artifactId->SetText("example-project"); root->InsertEndChild(artifactId); XMLElement* version = newDoc.NewElement("version"); version->SetText("1.0.0"); root->InsertEndChild(version); XMLElement* packaging = newDoc.NewElement("packaging"); packaging->SetText("jar"); root->InsertEndChild(packaging); XMLPrinter printer; newDoc.Accept(&printer); std::string xml = printer.CStr(); FILE* file = fopen(outputPath.c_str(), "w"); if (!file) { std::cerr << "Error opening output file." << std::endl; return false; } fprintf(file, "%s", xml.c_str()); fclose(file); std::cout << "Written sample POM to " << outputPath << std::endl; return true; } }; // Example usage: // int main() { // PomHandler handler("example.pom"); // if (handler.read()) { // handler.printProperties(); // } // handler.write("new.pom"); // return 0; // } // ===== end task-565 .POM ===== // ===== task-566 .PEG [C++] ===== #include #include #include #include #include class PEGHandler { private: std::string filepath; std::map rules; public: PEGHandler(const std::string& fp) : filepath(fp) {} void readAndDecode() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Failed to open file." << std::endl; return; } std::string line; std::regex pattern(R"(^(\w+)\s*<-\s*(.*)$)"); while (std::getline(file, line)) { line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); if (!line.empty() && line[0] != '#' && !line.substr(0, 2).compare("//") != 0) { std::smatch match; if (std::regex_match(line, match, pattern)) { rules[match[1].str()] = match[2].str(); } } } file.close(); } void printProperties() const { if (rules.empty()) { std::cout << "No properties found." << std::endl; return; } std::cout << "Extracted Properties (Rules):" << std::endl; for (const auto& pair : rules) { std::cout << "Identifier: " << pair.first << std::endl; std::cout << "Expression: " << pair.second << std::endl; std::cout << "----------------------------------------" << std::endl; } } void write(const std::string& newFilepath = "") const { std::string outputPath = newFilepath.empty() ? filepath : newFilepath; std::ofstream file(outputPath); if (!file.is_open()) { std::cerr << "Failed to write file." << std::endl; return; } for (const auto& pair : rules) { file << pair.first << " <- " << pair.second << "\n"; } file.close(); } }; // Example usage: // int main() { // PEGHandler handler("example.peg"); // handler.readAndDecode(); // handler.printProperties(); // handler.write("new.peg"); // return 0; // } // ===== end task-566 .PEG ===== // ===== task-567 .PPSX [C++] ===== #include #include #include #include #include class PPSXHandler { private: std::string filepath; std::map coreProps; std::map extProps; void loadProperties() { zip_t* za = zip_open(filepath.c_str(), ZIP_RDONLY, nullptr); if (!za) return; struct zip_stat st; zip_stat_init(&st); // Core if (zip_stat(za, "docProps/core.xml", 0, &st) == 0) { char* contents = new char[st.size + 1]; zip_file_t* f = zip_fopen(za, "docProps/core.xml", 0); zip_fread(f, contents, st.size); contents[st.size] = '\0'; zip_fclose(f); tinyxml2::XMLDocument doc; doc.Parse(contents); const char* props[] = {"category", "contentStatus", "contentType", "created", "creator", "description", "identifier", "keywords", "language", "lastModifiedBy", "lastPrinted", "modified", "revision", "subject", "title", "version"}; for (auto prop : props) { tinyxml2::XMLElement* elem = doc.FirstChildElement("cp:coreProperties")->FirstChildElement(prop); if (!elem) elem = doc.FirstChildElement("dc:coreProperties")->FirstChildElement(prop); // Fallback namespace coreProps[prop] = elem ? elem->GetText() : "N/A"; } delete[] contents; } // Extended if (zip_stat(za, "docProps/app.xml", 0, &st) == 0) { char* contents = new char[st.size + 1]; zip_file_t* f = zip_fopen(za, "docProps/app.xml", 0); zip_fread(f, contents, st.size); contents[st.size] = '\0'; zip_fclose(f); tinyxml2::XMLDocument doc; doc.Parse(contents); const char* props[] = {"Template", "Manager", "Company", "Pages", "Words", "Characters", "PresentationFormat", "Lines", "Paragraphs", "Slides", "Notes", "TotalTime", "HiddenSlides", "MultimediaClips", "ScaleCrop", "HeadingPairs", "TitlesOfParts", "LinksUpToDate", "CharactersWithSpaces", "SharedDocument", "HyperlinkBase", "HyperlinkList", "HyperlinksChanged", "DigitalSignature", "Application", "ApplicationVersion", "DocumentSecurity"}; for (auto prop : props) { tinyxml2::XMLElement* elem = doc.FirstChildElement("Properties")->FirstChildElement(prop); extProps[prop] = elem ? elem->GetText() : "N/A"; } delete[] contents; } zip_close(za); } public: PPSXHandler(const std::string& fp) : filepath(fp) { loadProperties(); } void printProperties() { std::cout << "Core Properties:" << std::endl; for (const auto& pair : coreProps) { std::cout << pair.first << ": " << pair.second << std::endl; } std::cout << "\nExtended Properties:" << std::endl; for (const auto& pair : extProps) { std::cout << pair.first << ": " << pair.second << std::endl; } } void writeProperty(const std::string& propName, const std::string& newValue, bool isCore = true) { zip_t* zaIn = zip_open(filepath.c_str(), ZIP_RDONLY, nullptr); if (!zaIn) return; std::string tempFile = filepath + ".tmp"; zip_t* zaOut = zip_open(tempFile.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); if (!zaOut) { zip_close(zaIn); return; } int numEntries = zip_get_num_entries(zaIn, 0); for (int i = 0; i < numEntries; ++i) { const char* name = zip_get_name(zaIn, i, 0); struct zip_stat st; zip_stat_index(zaIn, i, 0, &st); char* contents = new char[st.size + 1]; zip_file_t* f = zip_fopen_index(zaIn, i, 0); zip_fread(f, contents, st.size); contents[st.size] = '\0'; zip_fclose(f); bool modify = (isCore && std::string(name) == "docProps/core.xml") || (!isCore && std::string(name) == "docProps/app.xml"); if (modify) { tinyxml2::XMLDocument doc; doc.Parse(contents); tinyxml2::XMLElement* elem = doc.FirstChildElement(isCore ? "cp:coreProperties" : "Properties")->FirstChildElement(propName.c_str()); if (elem) elem->SetText(newValue.c_str()); tinyxml2::XMLPrinter printer; doc.Print(&printer); delete[] contents; contents = const_cast(printer.CStr()); st.size = printer.Size(); } zip_source_t* src = zip_source_buffer(zaOut, contents, st.size, 0); zip_file_add(zaOut, name, src, ZIP_FL_OVERWRITE); } zip_close(zaOut); zip_close(zaIn); std::remove(filepath.c_str()); std::rename(tempFile.c_str(), filepath.c_str()); loadProperties(); // Reload } }; // Example usage: // int main() { // PPSXHandler handler("example.ppsx"); // handler.printProperties(); // handler.writeProperty("title", "New Title"); // return 0; // } // ===== end task-567 .PPSX ===== // ===== task-568 .PPTX [C++] ===== #include #include #include #include #include class PPTXHandler { private: std::string filepath; std::map properties; std::string readZipFile(zip_t* zip, const std::string& name) { zip_file_t* file = zip_fopen(zip, name.c_str(), 0); if (!file) return ""; zip_stat_t stat; zip_stat_init(&stat); zip_stat(zip, name.c_str(), 0, &stat); char* buffer = new char[stat.size + 1]; zip_fread(file, buffer, stat.size); buffer[stat.size] = '\0'; std::string content(buffer); delete[] buffer; zip_fclose(file); return content; } public: PPTXHandler(const std::string& filepath) : filepath(filepath) {} void readProperties() { int err = 0; zip_t* zip = zip_open(filepath.c_str(), ZIP_RDONLY, &err); if (!zip) return; properties["File Extension"] = ".pptx"; properties["MIME Type"] = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; properties["Magic Number"] = "50 4B 03 04"; properties["Number of Files in ZIP Archive"] = std::to_string(zip_get_num_entries(zip, 0)); std::string mandatoryParts[4] = {"[Content_Types].xml", "_rels/.rels", "ppt/presentation.xml", "docProps/core.xml"}; bool allPresent = true; for (const auto& part : mandatoryParts) { if (zip_name_locate(zip, part.c_str(), 0) < 0) { allPresent = false; break; } } properties["Mandatory Parts Present"] = allPresent ? "Yes" : "No"; // Core Metadata std::string coreXml = readZipFile(zip, "docProps/core.xml"); if (!coreXml.empty()) { tinyxml2::XMLDocument doc; doc.Parse(coreXml.c_str()); properties["Title"] = doc.FirstChildElement()->FirstChildElement("dc:title") ? doc.FirstChildElement()->FirstChildElement("dc:title")->GetText() : "N/A"; properties["Subject"] = doc.FirstChildElement()->FirstChildElement("cp:subject") ? doc.FirstChildElement()->FirstChildElement("cp:subject")->GetText() : "N/A"; properties["Creator"] = doc.FirstChildElement()->FirstChildElement("dc:creator") ? doc.FirstChildElement()->FirstChildElement("dc:creator")->GetText() : "N/A"; properties["Keywords"] = doc.FirstChildElement()->FirstChildElement("cp:keywords") ? doc.FirstChildElement()->FirstChildElement("cp:keywords")->GetText() : "N/A"; properties["Description"] = doc.FirstChildElement()->FirstChildElement("dc:description") ? doc.FirstChildElement()->FirstChildElement("dc:description")->GetText() : "N/A"; properties["Last Modified By"] = doc.FirstChildElement()->FirstChildElement("cp:lastModifiedBy") ? doc.FirstChildElement()->FirstChildElement("cp:lastModifiedBy")->GetText() : "N/A"; properties["Revision"] = doc.FirstChildElement()->FirstChildElement("cp:revision") ? doc.FirstChildElement()->FirstChildElement("cp:revision")->GetText() : "N/A"; properties["Created Date"] = doc.FirstChildElement()->FirstChildElement("dcterms:created") ? doc.FirstChildElement()->FirstChildElement("dcterms:created")->GetText() : "N/A"; properties["Modified Date"] = doc.FirstChildElement()->FirstChildElement("dcterms:modified") ? doc.FirstChildElement()->FirstChildElement("dcterms:modified")->GetText() : "N/A"; } // Extended Metadata std::string appXml = readZipFile(zip, "docProps/app.xml"); if (!appXml.empty()) { tinyxml2::XMLDocument doc; doc.Parse(appXml.c_str()); properties["Application"] = doc.FirstChildElement()->FirstChildElement("Application") ? doc.FirstChildElement()->FirstChildElement("Application")->GetText() : "N/A"; properties["App Version"] = doc.FirstChildElement()->FirstChildElement("AppVersion") ? doc.FirstChildElement()->FirstChildElement("AppVersion")->GetText() : "N/A"; properties["Company"] = doc.FirstChildElement()->FirstChildElement("Company") ? doc.FirstChildElement()->FirstChildElement("Company")->GetText() : "N/A"; properties["Number of Slides"] = doc.FirstChildElement()->FirstChildElement("Slides") ? doc.FirstChildElement()->FirstChildElement("Slides")->GetText() : "N/A"; properties["Number of Hidden Slides"] = doc.FirstChildElement()->FirstChildElement("HiddenSlides") ? doc.FirstChildElement()->FirstChildElement("HiddenSlides")->GetText() : "N/A"; properties["Number of Notes"] = doc.FirstChildElement()->FirstChildElement("Notes") ? doc.FirstChildElement()->FirstChildElement("Notes")->GetText() : "N/A"; properties["Number of Paragraphs"] = doc.FirstChildElement()->FirstChildElement("Paragraphs") ? doc.FirstChildElement()->FirstChildElement("Paragraphs")->GetText() : "N/A"; properties["Number of Words"] = doc.FirstChildElement()->FirstChildElement("Words") ? doc.FirstChildElement()->FirstChildElement("Words")->GetText() : "N/A"; properties["Number of Characters"] = doc.FirstChildElement()->FirstChildElement("Characters") ? doc.FirstChildElement()->FirstChildElement("Characters")->GetText() : "N/A"; properties["Template"] = doc.FirstChildElement()->FirstChildElement("Template") ? doc.FirstChildElement()->FirstChildElement("Template")->GetText() : "N/A"; } // Number of Slides from presentation.xml std::string presXml = readZipFile(zip, "ppt/presentation.xml"); if (!presXml.empty()) { tinyxml2::XMLDocument doc; doc.Parse(presXml.c_str()); int count = 0; for (tinyxml2::XMLElement* elem = doc.FirstChildElement()->FirstChildElement("p:sldIdLst")->FirstChildElement("p:sldId"); elem; elem = elem->NextSiblingElement("p:sldId")) { count++; } properties["Number of Slides (from presentation.xml)"] = std::to_string(count); } zip_close(zip); } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void writeProperties(const std::map>& newProperties, const std::string& outputPath) { int err = 0; zip_t* srcZip = zip_open(filepath.c_str(), ZIP_RDONLY, &err); zip_t* destZip = zip_open(outputPath.c_str(), ZIP_CREATE | ZIP_TRUNCATE, &err); for (int i = 0; i < zip_get_num_entries(srcZip, 0); ++i) { const char* name = zip_get_name(srcZip, i, 0); std::string content = readZipFile(srcZip, name); if (std::string(name) == "docProps/core.xml" && newProperties.find("core") != newProperties.end()) { tinyxml2::XMLDocument doc; doc.Parse(content.c_str()); for (const auto& prop : newProperties.at("core")) { tinyxml2::XMLElement* elem = doc.FirstChildElement()->FirstChildElement(prop.first.c_str()); if (elem) { elem->SetText(prop.second.c_str()); } else { tinyxml2::XMLElement* newElem = doc.NewElement(prop.first.c_str()); newElem->SetText(prop.second.c_str()); doc.FirstChildElement()->InsertEndChild(newElem); } } tinyxml2::XMLPrinter printer; doc.Print(&printer); content = printer.CStr(); } else if (std::string(name) == "docProps/app.xml" && newProperties.find("app") != newProperties.end()) { tinyxml2::XMLDocument doc; doc.Parse(content.c_str()); for (const auto& prop : newProperties.at("app")) { tinyxml2::XMLElement* elem = doc.FirstChildElement()->FirstChildElement(prop.first.c_str()); if (elem) { elem->SetText(prop.second.c_str()); } else { tinyxml2::XMLElement* newElem = doc.NewElement(prop.first.c_str()); newElem->SetText(prop.second.c_str()); doc.FirstChildElement()->InsertEndChild(newElem); } } tinyxml2::XMLPrinter printer; doc.Print(&printer); content = printer.CStr(); } zip_source_t* source = zip_source_buffer(destZip, content.c_str(), content.size(), 0); zip_file_add(destZip, name, source, ZIP_FL_OVERWRITE); } zip_close(srcZip); zip_close(destZip); } }; // ===== end task-568 .PPTX ===== // ===== task-569 .PRJ [C++] ===== #include #include #include #include #include #include using namespace std; class PrjFile { private: string filepath; string wkt; map properties; map parseWKT(const string& wkt) { stack*> stack; map root; map* current = &root; string key = ""; string value = ""; bool inString = false; for (char charr : wkt) { if (charr == '"') { inString = !inString; } else if (inString) { value += charr; } else if (charr == '[' || charr == '(') { if (!key.empty()) { (*current)[key] = map{}; stack.push(current); current = &any_cast&>((*current)[key]); key = ""; } } else if (charr == ']' || charr == ')') { if (!value.empty()) { (*current)[key] = value; value = ""; key = ""; } if (!stack.empty()) { current = stack.top(); stack.pop(); } } else if (charr == ',') { if (!value.empty()) { (*current)[key] = value; value = ""; key = ""; } } else { value += charr; } } return root; } void printProperties(const map& props, const string& indent) { for (const auto& entry : props) { cout << indent << entry.first << ":" << endl; if (entry.second.type() == typeid(map)) { printProperties(any_cast&>(entry.second), indent + " "); } else if (entry.second.type() == typeid(string)) { cout << indent << " " << any_cast(entry.second) << endl; } } } string serializeProperties(const map& props) { string wkt = ""; for (const auto& entry : props) { wkt += entry.first + "["; if (entry.second.type() == typeid(map)) { wkt += serializeProperties(any_cast&>(entry.second)); } else if (entry.second.type() == typeid(string)) { wkt += any_cast(entry.second); } wkt += "],"; } if (!wkt.empty()) wkt.pop_back(); // Remove last , return wkt.replace(wkt.find(",]"), 2, "]"); } public: PrjFile(const string& fp) : filepath(fp) { read(); } void read() { ifstream file(filepath); getline(file, wkt); properties = parseWKT(wkt); file.close(); } void printProperties() { printProperties(properties, ""); } void write(const string& fp) { ofstream file(fp); file << serializeProperties(properties); file.close(); } }; // Example usage: // int main() { // PrjFile prj("example.prj"); // prj.printProperties(); // prj.write("output.prj"); // return 0; // } // ===== end task-569 .PRJ ===== // ===== task-570 .PROPERTIES [C++] ===== #include #include #include #include #include class PropertiesFile { private: std::string filepath; std::map properties; std::string unescape(const std::string& s) { std::string result; for (size_t i = 0; i < s.length(); ++i) { if (s[i] == '\\' && i + 1 < s.length()) { if (s[i+1] == 'u' && i + 5 < s.length()) { std::string code = s.substr(i+2, 4); char ch = static_cast(std::stoi(code, nullptr, 16)); result += ch; i += 5; } else { result += s[i+1]; ++i; } } else { result += s[i]; } } return result; } std::string escape(const std::string& s) { std::string result; for (char c : s) { if (c == '\\' || c == ':' || c == '=' || c == ' ') { result += '\\'; } result += c; } return result; } public: PropertiesFile(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::in | std::ios::binary); // For ISO-8859-1, treat as binary if (!file.is_open()) { throw std::runtime_error("File not found: " + filepath); } std::string line, current_line; while (std::getline(file, line)) { line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); // Handle CR std::string trimmed = line; trimmed.erase(0, trimmed.find_first_not_of(" \t")); if (trimmed.empty() || trimmed[0] == '#' || trimmed[0] == '!') continue; if (!line.empty() && line.back() == '\\') { current_line += line.substr(0, line.size() - 1); continue; } current_line += line; if (!current_line.empty()) { std::smatch match; if (std::regex_match(current_line, match, std::regex(R"(([^=:\s]+)\s*[=:\s]\s*(.*))"))) { std::string key = unescape(match[1].str()); std::string value = unescape(match[2].str()); properties[key] = value; } else { std::string key = unescape(current_line); properties[key] = ""; } } current_line = ""; } file.close(); } void write() { std::ofstream file(filepath); if (!file.is_open()) { throw std::runtime_error("Cannot write to file: " + filepath); } for (const auto& pair : properties) { std::string escaped_key = escape(pair.first); std::string escaped_value = escape(pair.second); file << escaped_key << "=" << escaped_value << "\n"; } file.close(); } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } }; // Example usage: // int main() { // try { // PropertiesFile pf("example.properties"); // pf.read(); // pf.printProperties(); // // Add property: pf.properties["new_key"] = "new_value"; // // pf.write(); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-570 .PROPERTIES ===== // ===== task-571 .PROTO [C++] ===== #include #include #include #include #include #include #include struct Field { uint32_t field_number; uint32_t wire_type; std::vector value; // For varint, encode to bytes; for message, serialize sub-fields std::vector sub_fields; // If message }; class ProtoParser { private: std::vector data; std::vector parsed; uint64_t read_varint(size_t& pos) { uint64_t result = 0; int shift = 0; while (true) { uint8_t b = data[pos++]; result |= static_cast(b & 0x7F) << shift; if (!(b & 0x80)) break; shift += 7; if (shift > 63) throw std::runtime_error("Varint too long"); } return result; } std::vector parse_message(size_t start, size_t end) { std::vector fields; size_t pos = start; while (pos < end) { uint64_t key = read_varint(pos); uint32_t field_number = key >> 3; uint32_t wire_type = key & 0x7; Field f; f.field_number = field_number; f.wire_type = wire_type; if (wire_type == 0) { uint64_t val = read_varint(pos); f.value = encode_varint(val); // Store as bytes for consistency } else if (wire_type == 5) { f.value.assign(data.begin() + pos, data.begin() + pos + 4); pos += 4; } else if (wire_type == 1) { f.value.assign(data.begin() + pos, data.begin() + pos + 8); pos += 8; } else if (wire_type == 2) { uint64_t length = read_varint(pos); size_t sub_start = pos; size_t sub_end = pos + length; try { auto sub_parsed = parse_message(sub_start, sub_end); if (pos == sub_end) { f.sub_fields = sub_parsed; } else { f.value.assign(data.begin() + sub_start, data.begin() + sub_end); } } catch (...) { f.value.assign(data.begin() + sub_start, data.begin() + sub_end); } pos = sub_end; } else { throw std::runtime_error("Unknown wire type"); } fields.push_back(f); } return fields; } void print_properties(const std::vector& fields, const std::string& indent) { for (const auto& field : fields) { std::cout << indent << "Field " << field.field_number << " (wire type " << field.wire_type << "): "; if (field.wire_type == 0) { size_t p = 0; uint64_t val = read_varint_from_bytes(field.value, p); std::cout << "varint " << val << std::endl; } else if (field.wire_type == 1 || field.wire_type == 5) { std::cout << "fixed ["; for (size_t i = 0; i < field.value.size(); ++i) { std::cout << std::hex << std::setfill('0') << std::setw(2) << static_cast(field.value[i]) << (i < field.value.size() - 1 ? " " : ""); } std::cout << "]" << std::dec << std::endl; } else if (field.wire_type == 2) { if (!field.sub_fields.empty()) { std::cout << "message {" << std::endl; print_properties(field.sub_fields, indent + " "); std::cout << indent << "}" << std::endl; } else { std::cout << "bytes ["; for (size_t i = 0; i < field.value.size(); ++i) { std::cout << std::hex << std::setfill('0') << std::setw(2) << static_cast(field.value[i]) << (i < field.value.size() - 1 ? " " : ""); } std::cout << "]" << std::dec << std::endl; } } } } std::vector encode_varint(uint64_t value) { std::vector bytes; while (true) { uint8_t byte_val = value & 0x7F; value >>= 7; if (value) byte_val |= 0x80; bytes.push_back(byte_val); if (!value) break; } return bytes; } uint64_t read_varint_from_bytes(const std::vector& bytes, size_t& pos) { uint64_t result = 0; int shift = 0; while (true) { uint8_t b = bytes[pos++]; result |= static_cast(b & 0x7F) << shift; if (!(b & 0x80)) break; shift += 7; } return result; } std::vector encode_message(const std::vector& fields) { std::vector result; for (const auto& field : fields) { uint64_t key = (static_cast(field.field_number) << 3) | field.wire_type; auto key_bytes = encode_varint(key); result.insert(result.end(), key_bytes.begin(), key_bytes.end()); if (field.wire_type == 0) { result.insert(result.end(), field.value.begin(), field.value.end()); } else if (field.wire_type == 1 || field.wire_type == 5) { result.insert(result.end(), field.value.begin(), field.value.end()); } else if (field.wire_type == 2) { std::vector sub_data; if (!field.sub_fields.empty()) { sub_data = encode_message(field.sub_fields); } else { sub_data = field.value; } auto len_bytes = encode_varint(sub_data.size()); result.insert(result.end(), len_bytes.begin(), len_bytes.end()); result.insert(result.end(), sub_data.begin(), sub_data.end()); } } return result; } public: ProtoParser(const std::string& filename) { std::ifstream file(filename, std::ios::binary); if (!file) throw std::runtime_error("Cannot open file"); data = std::vector((std::istreambuf_iterator(file)), std::istreambuf_iterator()); parsed = parse_message(0, data.size()); } void print_properties() { print_properties(parsed, ""); } void write(const std::string& filename) { auto encoded = encode_message(parsed); std::ofstream file(filename, std::ios::binary); file.write(reinterpret_cast(encoded.data()), encoded.size()); } }; // ===== end task-571 .PROTO ===== // ===== task-572 .PRP [C++] ===== #include #include #include #include #include using namespace std; struct Node { string type; string name; string defaultValue; vector values; vector children; }; class PRPFile { private: string filepath; vector structure; void parse(const string& text) { istringstream iss(text); string line; vector stack; Node* current = new Node{"root", "", "", {}, {}}; structure = current->children; while (getline(iss, line)) { line = line.substr(0, line.find("//")); // Ignore comments istringstream lineIss(line); string token; vector parts; while (lineIss >> token) parts.push_back(token); if (parts.empty()) continue; if (parts[0] == "end") { if (!stack.empty()) { current = stack.back(); stack.pop_back(); } continue; } if (parts[0] == "Subject") { Node node = {"Subject", parts[1], "", {}, {}}; current->children.push_back(node); stack.push_back(current); current = ¤t->children.back(); } else if (parts[0] == "Metaclass") { Node node = {"Metaclass", parts[1], "", {}, {}}; current->children.push_back(node); stack.push_back(current); current = ¤t->children.back(); } else if (parts[0] == "Property") { Node node = {"Property", parts[1], "", {}, {}}; current->children.push_back(node); stack.push_back(current); current = ¤t->children.back(); } else if (parts[0] == "Enum") { string vals = parts[1].substr(1, parts[1].length() - 2); istringstream valIss(vals); string val; vector values; while (getline(valIss, val, ',')) values.push_back(val); string def = parts.size() > 2 ? parts[2].substr(1, parts[2].length() - 2) : ""; Node node = {"Enum", "", def, values, {}}; current->children.push_back(node); } } } void printProperties(const vector& nodes, int indent = 0) { for (const auto& prop : nodes) { for (int i = 0; i < indent; ++i) cout << " "; cout << prop.type << ": " << prop.name << endl; if (!prop.values.empty()) { for (int i = 0; i < indent + 1; ++i) cout << " "; cout << "Values: "; for (size_t j = 0; j < prop.values.size(); ++j) { cout << prop.values[j]; if (j < prop.values.size() - 1) cout << ", "; } cout << endl; } if (!prop.defaultValue.empty()) { for (int i = 0; i < indent + 1; ++i) cout << " "; cout << "Default: " << prop.defaultValue << endl; } printProperties(prop.children, indent + 1); } } string serialize(const vector& nodes, int indent = 0) { stringstream ss; for (const auto& prop : nodes) { for (int i = 0; i < indent; ++i) ss << " "; if (prop.type == "Subject") ss << "Subject " << prop.name << endl; else if (prop.type == "Metaclass") ss << "Metaclass " << prop.name << endl; else if (prop.type == "Property") ss << "Property " << prop.name << endl; ss << serialize(prop.children, indent + 1); if (prop.type != "Enum") { for (int i = 0; i < indent; ++i) ss << " "; ss << "end" << endl; } else { for (int i = 0; i < indent; ++i) ss << " "; ss << "Enum \""; for (size_t j = 0; j < prop.values.size(); ++j) { ss << prop.values[j]; if (j < prop.values.size() - 1) ss << ","; } ss << "\", \"" << prop.defaultValue << "\"\n"; } } return ss.str(); } public: void open(const string& fp) { filepath = fp; ifstream file(fp); stringstream buffer; buffer << file.rdbuf(); parse(buffer.str()); } void print_properties() { printProperties(structure); } void write(const string& fp) { ofstream file(fp); file << serialize(structure); } }; // Example usage // int main() { // PRPFile prp; // prp.open("example.prp"); // prp.print_properties(); // prp.write("output.prp"); // return 0; // } // ===== end task-572 .PRP ===== // ===== task-573 .PS [C++] ===== #include #include #include #include #include class PSFileHandler { private: std::string filepath; std::map properties; std::string content; public: PSFileHandler(const std::string& fp) : filepath(fp) { readAndDecode(); } void readAndDecode() { std::ifstream file(filepath); if (!file) { std::cerr << "Error opening file." << std::endl; return; } std::string line; std::stringstream ss; std::regex regex(R"(%%(\w+):\s*(.*))"); while (std::getline(file, line)) { ss << line << "\n"; std::smatch match; if (std::regex_match(line, match, regex)) { properties[match[1]] = match[2]; } } content = ss.str(); file.close(); } void printProperties() const { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& newFilepath, const std::map& newProperties = {}) { for (const auto& pair : newProperties) { properties[pair.first] = pair.second; } std::ofstream file(newFilepath); if (!file) { std::cerr << "Error writing file." << std::endl; return; } file << "%!PS-Adobe-3.0\n"; for (const auto& pair : properties) { file << "%%" << pair.first << ": " << pair.second << "\n"; } file << "%%EndComments\n"; size_t pos = content.find("%%EndComments"); if (pos != std::string::npos) { file << content.substr(pos + std::string("%%EndComments").length() + 1); } else { file << content; } file.close(); } }; // Example usage: // int main() { // PSFileHandler handler("example.ps"); // handler.printProperties(); // std::map updates = {{"Title", "Updated Title"}}; // handler.write("new.ps", updates); // return 0; // } // ===== end task-573 .PS ===== // ===== task-574 .PS1 [C++] ===== #include #include #include #include #include class PS1Handler { private: std::filesystem::path filePath; public: PS1Handler(const std::string& path) : filePath(path) { if (filePath.extension().string() != ".ps1") { throw std::invalid_argument("File must have .ps1 extension"); } if (!std::filesystem::exists(filePath)) { throw std::invalid_argument("File does not exist"); } } void printProperties() { struct stat st; if (stat(filePath.string().c_str(), &st) == 0) { std::cout << "File Name: " << filePath.filename().string() << std::endl; std::cout << "File Size (bytes): " << st.st_size << std::endl; std::cout << "Creation Time: " << std::ctime(&st.st_ctime); std::cout << "Last Modification Time: " << std::ctime(&st.st_mtime); std::cout << "Last Access Time: " << std::ctime(&st.st_atime); std::cout << "Read-Only Attribute: " << ((st.st_mode & S_IWUSR) == 0) << std::endl; std::cout << "Hidden Attribute: " << (filePath.filename().string()[0] == '.') << std::endl; std::cout << "System Attribute: 0" << std::endl; // Not standard in POSIX std::cout << "Owner: " << st.st_uid << std::endl; std::cout << "Permissions: " << std::oct << (st.st_mode & 0777) << std::endl; } } void writeAttribute(const std::string& attribute, bool value) { if (attribute == "read_only") { struct stat st; stat(filePath.string().c_str(), &st); mode_t newMode = value ? (st.st_mode & ~0222) : (st.st_mode | 0222); chmod(filePath.string().c_str(), newMode); } // For modification time: use utimes() with struct timeval } }; // Example usage: // int main() { // try { // PS1Handler handler("example.ps1"); // handler.printProperties(); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-574 .PS1 ===== // ===== task-575 .PSD [C++] ===== #include #include #include #include class PSDFile { private: std::string filepath; char signature[5]; uint16_t version; uint8_t reserved[6]; uint16_t channels; uint32_t height; uint32_t width; uint16_t depth; uint16_t colorMode; public: PSDFile(const std::string& fp) : filepath(fp) { signature[4] = '\0'; } void readProperties() { std::ifstream file(filepath, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file"); } char buffer[26]; file.read(buffer, 26); if (file.gcount() < 26) { throw std::runtime_error("Invalid PSD file"); } memcpy(signature, buffer, 4); memcpy(&version, buffer + 4, 2); version = __builtin_bswap16(version); // Big-endian to host memcpy(reserved, buffer + 6, 6); memcpy(&channels, buffer + 12, 2); channels = __builtin_bswap16(channels); memcpy(&height, buffer + 14, 4); height = __builtin_bswap32(height); memcpy(&width, buffer + 18, 4); width = __builtin_bswap32(width); memcpy(&depth, buffer + 22, 2); depth = __builtin_bswap16(depth); memcpy(&colorMode, buffer + 24, 2); colorMode = __builtin_bswap16(colorMode); } void printProperties() { std::cout << "signature: " << signature << std::endl; std::cout << "version: " << version << std::endl; std::cout << "reserved: "; for (int i = 0; i < 6; ++i) std::cout << (int)reserved[i] << " "; std::cout << std::endl; std::cout << "channels: " << channels << std::endl; std::cout << "height: " << height << std::endl; std::cout << "width: " << width << std::endl; std::cout << "depth: " << depth << std::endl; std::cout << "colorMode: " << colorMode << std::endl; } void writeProperties(const std::string& newFilepath) { // Simple copy std::ifstream src(filepath, std::ios::binary); std::ofstream dst(newFilepath, std::ios::binary); dst << src.rdbuf(); std::cout << "Written to " << newFilepath << std::endl; } }; // Example usage: // int main() { // try { // PSDFile psd("example.psd"); // psd.readProperties(); // psd.printProperties(); // psd.writeProperties("output.psd"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-575 .PSD ===== // ===== task-576 .PSDC [C++] ===== #include #include #include #include #include class PSDCFile { private: char signature[5]; uint16_t version; uint8_t reserved[6]; uint16_t channels; uint32_t height; uint32_t width; uint16_t depth; uint16_t colorMode; public: PSDCFile(const std::string& filename) { read(filename); } void read(const std::string& filename) { std::ifstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file"); } char header[26]; file.read(header, 26); if (file.gcount() < 26) { throw std::runtime_error("File too small"); } memcpy(signature, header, 4); signature[4] = '\0'; version = *reinterpret_cast(header + 4); memcpy(reserved, header + 6, 6); channels = *reinterpret_cast(header + 12); height = *reinterpret_cast(header + 14); width = *reinterpret_cast(header + 18); depth = *reinterpret_cast(header + 22); colorMode = *reinterpret_cast(header + 24); // Note: Big-endian swap if needed, assuming big-endian input } void printProperties() { std::cout << "Signature: " << signature << std::endl; std::cout << "Version: " << version << std::endl; std::cout << "Reserved: "; for (int i = 0; i < 6; ++i) std::cout << static_cast(reserved[i]) << " "; std::cout << std::endl; std::cout << "Channels: " << channels << std::endl; std::cout << "Height: " << height << std::endl; std::cout << "Width: " << width << std::endl; std::cout << "Depth: " << depth << std::endl; std::cout << "ColorMode: " << colorMode << std::endl; } void write(const std::string& filename) { std::ofstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Cannot write file"); } char header[26]; memcpy(header, signature, 4); *reinterpret_cast(header + 4) = version; memcpy(header + 6, reserved, 6); *reinterpret_cast(header + 12) = channels; *reinterpret_cast(header + 14) = height; *reinterpret_cast(header + 18) = width; *reinterpret_cast(header + 22) = depth; *reinterpret_cast(header + 24) = colorMode; file.write(header, 26); } }; // Example usage: // int main() { // try { // PSDCFile psdc("example.psdc"); // psdc.printProperties(); // psdc.write("new.psdc"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-576 .PSDC ===== // ===== task-577 .PSM1 [C++] ===== #include #include #include #include #include #include class PSM1Handler { private: std::string filePath; std::string content; public: PSM1Handler(const std::string& fp) : filePath(fp) { if (filePath.size() < 5 || strcasecmp(filePath.substr(filePath.size() - 5).c_str(), ".psm1") != 0) { throw std::invalid_argument("File must have .psm1 extension"); } } std::string read() { std::ifstream file(filePath, std::ios::in | std::ios::binary); if (!file) throw std::runtime_error("Cannot open file"); content.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); return content; } void write(const std::string& newContent) { std::ofstream file(filePath, std::ios::out | std::ios::binary); if (!file) throw std::runtime_error("Cannot write to file"); file << newContent; content = newContent; } void printProperties() { struct stat st; if (stat(filePath.c_str(), &st) != 0) { throw std::runtime_error("Cannot get file stats"); } std::cout << "File Name: " << filePath.substr(filePath.find_last_of("/\\") + 1) << std::endl; std::cout << "File Path: " << filePath << std::endl; std::cout << "Size: " << st.st_size << " bytes" << std::endl; std::cout << "Creation Time: " << std::ctime(&st.st_ctime); std::cout << "Last Modified Time: " << std::ctime(&st.st_mtime); std::cout << "Last Access Time: " << std::ctime(&st.st_atime); std::string attributes; if (st.st_mode & S_IRUSR) attributes += "Readable, "; if (st.st_mode & S_IWUSR) attributes += "Writable, "; if (st.st_mode & S_IXUSR) attributes += "Executable, "; if (attributes.empty()) attributes = "None"; else attributes = attributes.substr(0, attributes.size() - 2); std::cout << "Attributes: " << attributes << std::endl; } }; // Example usage: // int main() { // try { // PSM1Handler handler("example.psm1"); // handler.read(); // handler.printProperties(); // handler.write("New content"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-577 .PSM1 ===== // ===== task-578 .PSPPALETTE [C] ===== #include #include #include typedef struct { char *signature; char *version; int num_colors; int (*colors)[3]; // array of [r, g, b] } PspPalette; PspPalette* psp_palette_new() { PspPalette* pal = malloc(sizeof(PspPalette)); pal->signature = strdup("JASC-PAL"); pal->version = strdup("0100"); pal->num_colors = 0; pal->colors = NULL; return pal; } void psp_palette_free(PspPalette* pal) { free(pal->signature); free(pal->version); free(pal->colors); free(pal); } int psp_palette_read(PspPalette* pal, const char* filename) { FILE* f = fopen(filename, "r"); if (!f) return -1; char line[256]; if (!fgets(line, sizeof(line), f)) goto error; pal->signature = strdup(strtok(line, "\r\n")); if (!fgets(line, sizeof(line), f)) goto error; pal->version = strdup(strtok(line, "\r\n")); if (!fgets(line, sizeof(line), f)) goto error; pal->num_colors = atoi(line); pal->colors = malloc(pal->num_colors * sizeof(int[3])); for (int i = 0; i < pal->num_colors; i++) { if (!fgets(line, sizeof(line), f)) goto error; sscanf(line, "%d %d %d", &pal->colors[i][0], &pal->colors[i][1], &pal->colors[i][2]); } fclose(f); return 0; error: fclose(f); return -1; } int psp_palette_write(PspPalette* pal, const char* filename) { FILE* f = fopen(filename, "w"); if (!f) return -1; fprintf(f, "%s\r\n", pal->signature); fprintf(f, "%s\r\n", pal->version); fprintf(f, "%d\r\n", pal->num_colors); for (int i = 0; i < pal->num_colors; i++) { fprintf(f, "%d %d %d\r\n", pal->colors[i][0], pal->colors[i][1], pal->colors[i][2]); } fclose(f); return 0; } void psp_palette_print_properties(PspPalette* pal) { printf("Signature: %s\n", pal->signature); printf("Version: %s\n", pal->version); printf("Number of Colors: %d\n", pal->num_colors); printf("Colors:\n"); for (int i = 0; i < pal->num_colors; i++) { printf("(%d, %d, %d)\n", pal->colors[i][0], pal->colors[i][1], pal->colors[i][2]); } } int main(int argc, char** argv) { if (argc > 1) { PspPalette* pal = psp_palette_new(); if (psp_palette_read(pal, argv[1]) == 0) { psp_palette_print_properties(pal); } else { printf("Error reading file\n"); } psp_palette_free(pal); } return 0; } // ===== end task-578 .PSPPALETTE ===== // ===== task-579 .PST [C++] ===== #include #include #include #include class PstFile { private: std::string filepath; std::vector header; bool isUnicode; public: PstFile(const std::string& fp) : filepath(fp), isUnicode(false) {} void open() { std::ifstream f(filepath, std::ios::binary); if (!f) { throw std::runtime_error("Cannot open file"); } header.resize(544); f.read(reinterpret_cast(header.data()), 544); if (f.gcount() < 544) { throw std::runtime_error("File too small for PST header"); } unsigned short wVer = *reinterpret_cast(header.data() + 10); isUnicode = wVer >= 23; } void decodeAndPrintProperties() { if (header.empty()) { throw std::runtime_error("File not opened"); } unsigned int dwMagic = *reinterpret_cast(header.data() + 0); std::cout << "dwMagic: 0x" << std::hex << dwMagic << std::endl; unsigned int dwCRCPartial = *reinterpret_cast(header.data() + 4); std::cout << "dwCRCPartial: 0x" << std::hex << dwCRCPartial << std::endl; unsigned short wMagicClient = *reinterpret_cast(header.data() + 8); std::cout << "wMagicClient: 0x" << std::hex << wMagicClient << std::endl; unsigned short wVer = *reinterpret_cast(header.data() + 10); std::cout << "wVer: " << std::dec << wVer << std::endl; unsigned short wVerClient = *reinterpret_cast(header.data() + 12); std::cout << "wVerClient: " << std::dec << wVerClient << std::endl; unsigned char bPlatformCreate = header[14]; std::cout << "bPlatformCreate: 0x" << std::hex << static_cast(bPlatformCreate) << std::endl; unsigned char bPlatformAccess = header[15]; std::cout << "bPlatformAccess: 0x" << std::hex << static_cast(bPlatformAccess) << std::endl; unsigned int dwReserved1 = *reinterpret_cast(header.data() + 16); std::cout << "dwReserved1: 0x" << std::hex << dwReserved1 << std::endl; unsigned int dwReserved2 = *reinterpret_cast(header.data() + 20); std::cout << "dwReserved2: 0x" << std::hex << dwReserved2 << std::endl; if (isUnicode) { unsigned long long bidUnused = *reinterpret_cast(header.data() + 24); std::cout << "bidUnused: 0x" << std::hex << bidUnused << std::endl; unsigned long long bidNextP = *reinterpret_cast(header.data() + 32); std::cout << "bidNextP: 0x" << std::hex << bidNextP << std::endl; unsigned int dwUnique = *reinterpret_cast(header.data() + 40); std::cout << "dwUnique: 0x" << std::hex << dwUnique << std::endl; unsigned long long qwUnused = *reinterpret_cast(header.data() + 172); std::cout << "qwUnused: 0x" << std::hex << qwUnused << std::endl; unsigned char bSentinel = header[496]; std::cout << "bSentinel: 0x" << std::hex << static_cast(bSentinel) << std::endl; unsigned char bCryptMethod = header[497]; std::cout << "bCryptMethod: 0x" << std::hex << static_cast(bCryptMethod) << std::endl; unsigned long long bidNextB = *reinterpret_cast(header.data() + 500); std::cout << "bidNextB: 0x" << std::hex << bidNextB << std::endl; unsigned int dwCRCFull = *reinterpret_cast(header.data() + 508); std::cout << "dwCRCFull: 0x" << std::hex << dwCRCFull << std::endl; } else { // ANSI unsigned int bidNextB = *reinterpret_cast(header.data() + 24); std::cout << "bidNextB: 0x" << std::hex << bidNextB << std::endl; unsigned int bidNextP = *reinterpret_cast(header.data() + 28); std::cout << "bidNextP: 0x" << std::hex << bidNextP << std::endl; unsigned int dwUnique = *reinterpret_cast(header.data() + 32); std::cout << "dwUnique: 0x" << std::hex << dwUnique << std::endl; unsigned char bSentinel = header[460]; std::cout << "bSentinel: 0x" << std::hex << static_cast(bSentinel) << std::endl; unsigned char bCryptMethod = header[461]; std::cout << "bCryptMethod: 0x" << std::hex << static_cast(bCryptMethod) << std::endl; } } void write(const std::string& newFilepath = "") { std::string outPath = newFilepath.empty() ? filepath : newFilepath; std::ifstream fIn(filepath, std::ios::binary); std::ofstream fOut(outPath, std::ios::binary); if (!fIn || !fOut) { throw std::runtime_error("Cannot open files for write"); } fOut.write(reinterpret_cast(header.data()), header.size()); char buf[4096]; while (fIn.read(buf, sizeof(buf))) { fOut.write(buf, fIn.gcount()); } fOut.write(buf, fIn.gcount()); } }; // Example usage // PstFile pst("path/to/file.pst"); // pst.open(); // pst.decodeAndPrintProperties(); // pst.write("path/to/modified.pst"); // ===== end task-579 .PST ===== // ===== task-580 .PTF [C] ===== #include #include #include #define MAX_LINE 1024 #define MAX_SECTIONS 10 typedef struct { char name[64]; char content[100][MAX_LINE]; int content_count; // For simplicity, not parsing sub-properties fully } Section; typedef struct { char filepath[256]; Section sections[MAX_SECTIONS]; int section_count; } PTFHandler; void init_ptf(PTFHandler *handler, const char *filepath) { strncpy(handler->filepath, filepath, 255); handler->section_count = 0; } void read_ptf(PTFHandler *handler) { FILE *fp = fopen(handler->filepath, "r"); if (!fp) { printf("Error opening file\n"); return; } char line[MAX_LINE]; int current = -1; while (fgets(line, MAX_LINE, fp)) { char *trimmed = line; while (*trimmed == ' ') trimmed++; // Simple trim if (strlen(trimmed) == 0 || trimmed[0] == '#') continue; if (strstr(trimmed, "Task") == trimmed || strstr(trimmed, "Objective") == trimmed || strstr(trimmed, "Constraints") == trimmed || strstr(trimmed, "Variables") == trimmed || strstr(trimmed, "Integer") == trimmed || strstr(trimmed, "SymmetricMatrixes") == trimmed || strstr(trimmed, "Solutions") == trimmed) { current = handler->section_count++; sscanf(trimmed, "%s %[^\n]", handler->sections[current].name, trimmed); // Rough parse handler->sections[current].content_count = 0; } else if (current >= 0) { strncpy(handler->sections[current].content[handler->sections[current].content_count++], trimmed, MAX_LINE - 1); // Parse further if needed } } fclose(fp); } void print_properties(PTFHandler *handler) { printf("{\n \"sections\": {\n"); for (int i = 0; i < handler->section_count; i++) { printf(" \"%s\": {\n \"content\": [\n", handler->sections[i].name); for (int j = 0; j < handler->sections[i].content_count; j++) { printf(" \"%s\",\n", handler->sections[i].content[j]); } printf(" ]\n },\n"); } printf(" }\n}\n"); } void write_ptf(PTFHandler *handler, const char *new_filepath) { FILE *fp = fopen(new_filepath ? new_filepath : handler->filepath, "w"); if (!fp) return; for (int i = 0; i < handler->section_count; i++) { fprintf(fp, "%s\n", handler->sections[i].name); for (int j = 0; j < handler->sections[i].content_count; j++) { fprintf(fp, " %s\n", handler->sections[i].content[j]); } } fclose(fp); } int main() { PTFHandler handler; init_ptf(&handler, "example.ptf"); read_ptf(&handler); print_properties(&handler); write_ptf(&handler, "output.ptf"); return 0; } // ===== end task-580 .PTF ===== // ===== task-581 .PTS [C] ===== #include #include #include typedef struct { double x, y, z; int intensity, r, g, b; } Point; typedef struct { int num_points; Point *points; } PTSFile; PTSFile* pts_create(const char *filename) { PTSFile *pts = malloc(sizeof(PTSFile)); pts->num_points = 0; pts->points = NULL; if (filename) { pts_read(pts, filename); } return pts; } void pts_read(PTSFile *pts, const char *filename) { FILE *fp = fopen(filename, "r"); if (!fp) { perror("Failed to open file"); exit(1); } char line[256]; if (fgets(line, sizeof(line), fp)) { pts->num_points = atoi(line); } if (pts->points) free(pts->points); pts->points = malloc(pts->num_points * sizeof(Point)); int idx = 0; while (fgets(line, sizeof(line), fp) && idx < pts->num_points) { char *token = strtok(line, " "); if (token) pts->points[idx].x = atof(token); token = strtok(NULL, " "); if (token) pts->points[idx].y = atof(token); token = strtok(NULL, " "); if (token) pts->points[idx].z = atof(token); token = strtok(NULL, " "); if (token) pts->points[idx].intensity = atoi(token); token = strtok(NULL, " "); if (token) pts->points[idx].r = atoi(token); token = strtok(NULL, " "); if (token) pts->points[idx].g = atoi(token); token = strtok(NULL, " "); if (token) pts->points[idx].b = atoi(token); idx++; } fclose(fp); if (idx != pts->num_points) { fprintf(stderr, "Point count mismatch\n"); exit(1); } } void pts_print_properties(const PTSFile *pts) { printf("Number of points: %d\n", pts->num_points); for (int i = 0; i < pts->num_points; i++) { const Point *p = &pts->points[i]; printf("Point %d: x=%.6f, y=%.6f, z=%.6f, intensity=%d, r=%d, g=%d, b=%d\n", i + 1, p->x, p->y, p->z, p->intensity, p->r, p->g, p->b); } } void pts_write(const PTSFile *pts, const char *filename) { FILE *fp = fopen(filename, "w"); if (!fp) { perror("Failed to open file for writing"); exit(1); } fprintf(fp, "%d\n", pts->num_points); for (int i = 0; i < pts->num_points; i++) { const Point *p = &pts->points[i]; fprintf(fp, "%.6f %.6f %.6f %d %d %d %d\n", p->x, p->y, p->z, p->intensity, p->r, p->g, p->b); } fclose(fp); } void pts_destroy(PTSFile *pts) { free(pts->points); free(pts); } // ===== end task-581 .PTS ===== // ===== task-582 .PTX [C++] ===== #include #include #include #include #include #include class PTXParser { private: std::string version; std::string target; std::string address_size; std::vector entries; std::vector funcs; std::vector variables; std::vector registers; std::string text; public: void open(const std::string& filepath) { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file: " << filepath << std::endl; return; } std::stringstream buffer; buffer << file.rdbuf(); text = buffer.str(); file.close(); decode(); } void decode() { if (text.empty()) { throw std::runtime_error("No file loaded"); } std::istringstream iss(text); std::string line; while (std::getline(iss, line)) { line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); if (line.empty() || line.substr(0, 2) == "//") continue; if (line.substr(0, 8) == ".version") { std::regex r("\\.version\\s+(\\S+)"); std::smatch m; if (std::regex_search(line, m, r)) version = m[1]; } else if (line.substr(0, 7) == ".target") { std::regex r("\\.target\\s+(\\S+)"); std::smatch m; if (std::regex_search(line, m, r)) target = m[1]; } else if (line.substr(0, 13) == ".address_size") { std::regex r("\\.address_size\\s+(\\S+)"); std::smatch m; if (std::regex_search(line, m, r)) address_size = m[1]; } else if (line.substr(0, 6) == ".entry") { std::regex r("\\.entry\\s+(\\S+)\\s*\\(?"); std::smatch m; if (std::regex_search(line, m, r)) entries.push_back(m[1]); } else if (line.substr(0, 5) == ".func") { std::regex r("\\.func\\s+(\\S+)\\s*\\(?"); std::smatch m; if (std::regex_search(line, m, r)) funcs.push_back(m[1]); } else if (line.substr(0, 7) == ".global" || line.substr(0, 6) == ".const" || line.substr(0, 7) == ".shared") { variables.push_back(line); } else if (line.substr(0, 4) == ".reg") { registers.push_back(line); } } } void print_properties() const { std::cout << "Version: " << (version.empty() ? "Not found" : version) << std::endl; std::cout << "Target: " << (target.empty() ? "Not found" : target) << std::endl; std::cout << "Address Size: " << (address_size.empty() ? "64 (default)" : address_size) << std::endl; std::cout << "Entry Points: "; if (entries.empty()) { std::cout << "None"; } else { for (size_t i = 0; i < entries.size(); ++i) { std::cout << entries[i] << (i < entries.size() - 1 ? ", " : ""); } } std::cout << std::endl; std::cout << "Functions: "; if (funcs.empty()) { std::cout << "None"; } else { for (size_t i = 0; i < funcs.size(); ++i) { std::cout << funcs[i] << (i < funcs.size() - 1 ? ", " : ""); } } std::cout << std::endl; std::cout << "Variables:" << std::endl; if (variables.empty()) { std::cout << "None" << std::endl; } else { for (const auto& var : variables) { std::cout << var << std::endl; } } std::cout << "Registers:" << std::endl; if (registers.empty()) { std::cout << "None" << std::endl; } else { for (const auto& reg : registers) { std::cout << reg << std::endl; } } } void write(const std::string& filepath, const std::string& modified_text = "") const { std::string text_to_write = modified_text.empty() ? text : modified_text; std::ofstream file(filepath); if (!file.is_open()) { std::cerr << "Error writing file: " << filepath << std::endl; return; } file << text_to_write; file.close(); } }; // Example usage: // int main() { // PTXParser parser; // parser.open("example.ptx"); // parser.print_properties(); // parser.write("output.ptx"); // return 0; // } // ===== end task-582 .PTX ===== // ===== task-583 .PUB [C++] ===== #include #include #include #include #include #include class PubFileHandler { private: std::string filepath; std::map properties; // Store as hex strings for simplicity public: PubFileHandler(const std::string& fp) : filepath(fp) { readProperties(); } void readProperties() { std::ifstream file(filepath, std::ios::binary); if (!file) { std::cerr << "Error opening file" << std::endl; return; } std::vector header(512); file.read(header.data(), 512); file.close(); std::ostringstream oss; for (int i = 0; i < 8; ++i) oss << std::hex << std::setw(2) << std::setfill('0') << (static_cast(header[i])); properties["Header Signature"] = oss.str(); oss.str(""); for (int i = 8; i < 24; ++i) oss << std::hex << std::setw(2) << std::setfill('0') << (static_cast(header[i])); properties["Header CLSID"] = oss.str(); unsigned short minor = *reinterpret_cast(&header[24]); properties["Minor Version"] = std::to_string(minor); unsigned short major = *reinterpret_cast(&header[26]); properties["Major Version"] = std::to_string(major); unsigned short byteOrder = *reinterpret_cast(&header[28]); properties["Byte Order"] = std::to_string(byteOrder); unsigned short sectorShift = *reinterpret_cast(&header[30]); properties["Sector Shift"] = std::to_string(sectorShift); unsigned short miniSectorShift = *reinterpret_cast(&header[32]); properties["Mini Sector Shift"] = std::to_string(miniSectorShift); oss.str(""); for (int i = 34; i < 40; ++i) oss << std::hex << std::setw(2) << std::setfill('0') << (static_cast(header[i])); properties["Reserved"] = oss.str(); unsigned int dirSectors = *reinterpret_cast(&header[40]); properties["Number of Directory Sectors"] = std::to_string(dirSectors); unsigned int fatSectors = *reinterpret_cast(&header[44]); properties["Number of FAT Sectors"] = std::to_string(fatSectors); unsigned int firstDir = *reinterpret_cast(&header[48]); properties["First Directory Sector Location"] = std::to_string(firstDir); unsigned int transSig = *reinterpret_cast(&header[52]); properties["Transaction Signature Number"] = std::to_string(transSig); unsigned int miniCutoff = *reinterpret_cast(&header[56]); properties["Mini Stream Cutoff Size"] = std::to_string(miniCutoff); unsigned int firstMiniFat = *reinterpret_cast(&header[60]); properties["First Mini FAT Sector Location"] = std::to_string(firstMiniFat); unsigned int numMiniFat = *reinterpret_cast(&header[64]); properties["Number of Mini FAT Sectors"] = std::to_string(numMiniFat); unsigned int firstDifat = *reinterpret_cast(&header[68]); properties["First DIFAT Sector Location"] = std::to_string(firstDifat); unsigned int numDifat = *reinterpret_cast(&header[72]); properties["Number of DIFAT Sectors"] = std::to_string(numDifat); oss.str(""); for (int i = 76; i < 512; ++i) oss << std::hex << std::setw(2) << std::setfill('0') << (static_cast(header[i])); properties["DIFAT"] = oss.str(); } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void writeProperties(const std::map& newProperties) { for (const auto& pair : newProperties) { if (properties.count(pair.first)) { properties[pair.first] = pair.second; } } std::fstream file(filepath, std::ios::binary | std::ios::in | std::ios::out); if (!file) { std::cerr << "Error opening file for write" << std::endl; return; } std::vector header(512, 0); auto hexToBytes = [](const std::string& hex) { std::vector bytes; for (size_t i = 0; i < hex.length(); i += 2) { std::string byteStr = hex.substr(i, 2); char byte = static_cast(std::stoi(byteStr, nullptr, 16)); bytes.push_back(byte); } return bytes; }; auto sig = hexToBytes(properties["Header Signature"]); std::copy(sig.begin(), sig.end(), header.begin()); auto clsid = hexToBytes(properties["Header CLSID"]); std::copy(clsid.begin(), clsid.end(), header.begin() + 8); *reinterpret_cast(&header[24]) = std::stoul(properties["Minor Version"]); *reinterpret_cast(&header[26]) = std::stoul(properties["Major Version"]); *reinterpret_cast(&header[28]) = std::stoul(properties["Byte Order"]); *reinterpret_cast(&header[30]) = std::stoul(properties["Sector Shift"]); *reinterpret_cast(&header[32]) = std::stoul(properties["Mini Sector Shift"]); auto reserved = hexToBytes(properties["Reserved"]); std::copy(reserved.begin(), reserved.end(), header.begin() + 34); *reinterpret_cast(&header[40]) = std::stoul(properties["Number of Directory Sectors"]); *reinterpret_cast(&header[44]) = std::stoul(properties["Number of FAT Sectors"]); *reinterpret_cast(&header[48]) = std::stoul(properties["First Directory Sector Location"]); *reinterpret_cast(&header[52]) = std::stoul(properties["Transaction Signature Number"]); *reinterpret_cast(&header[56]) = std::stoul(properties["Mini Stream Cutoff Size"]); *reinterpret_cast(&header[60]) = std::stoul(properties["First Mini FAT Sector Location"]); *reinterpret_cast(&header[64]) = std::stoul(properties["Number of Mini FAT Sectors"]); *reinterpret_cast(&header[68]) = std::stoul(properties["First DIFAT Sector Location"]); *reinterpret_cast(&header[72]) = std::stoul(properties["Number of DIFAT Sectors"]); auto difat = hexToBytes(properties["DIFAT"]); std::copy(difat.begin(), difat.end(), header.begin() + 76); file.seekp(0); file.write(header.data(), 512); file.close(); } }; // Example usage // int main() { // PubFileHandler handler("example.pub"); // handler.printProperties(); // std::map updates; // updates["Minor Version"] = "63"; // 0x003F // handler.writeProperties(updates); // return 0; // } // ===== end task-583 .PUB ===== // ===== task-584 .PUP [C++] ===== #include #include #include #include #include #include struct Segment { uint64_t id; uint64_t offset; uint64_t size; uint32_t hashed; uint32_t pad; }; struct Digest { uint64_t index; uint8_t digest[20]; uint32_t pad; }; class PupFile { private: uint8_t magic[7]; uint8_t format_flag; uint64_t package_version; uint64_t image_version; uint64_t segment_count; uint64_t header_length; uint64_t data_size; std::vector segments; std::vector digests; uint8_t header_hmac[20]; uint8_t padding[12]; std::vector> segment_data; uint64_t be_to_uint64(const uint8_t* buf) { uint64_t val = 0; for (int i = 0; i < 8; ++i) { val = (val << 8) | buf[i]; } return val; } uint32_t be_to_uint32(const uint8_t* buf) { uint32_t val = 0; for (int i = 0; i < 4; ++i) { val = (val << 8) | buf[i]; } return val; } void uint64_to_be(uint64_t val, uint8_t* buf) { for (int i = 7; i >= 0; --i) { buf[i] = val & 0xFF; val >>= 8; } } void uint32_to_be(uint32_t val, uint8_t* buf) { for (int i = 3; i >= 0; --i) { buf[i] = val & 0xFF; val >>= 8; } } public: PupFile(const std::string& filename = "") { memset(magic, 0, 7); format_flag = 0; package_version = 0; image_version = 0; segment_count = 0; header_length = 0; data_size = 0; memset(header_hmac, 0, 20); memset(padding, 0, 12); if (!filename.empty()) { load(filename); } } void load(const std::string& filename) { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) { std::cerr << "Failed to open file" << std::endl; return; } size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(reinterpret_cast(data.data()), size); memcpy(magic, data.data(), 7); format_flag = data[7]; package_version = be_to_uint64(&data[8]); image_version = be_to_uint64(&data[16]); segment_count = be_to_uint64(&data[24]); header_length = be_to_uint64(&data[32]); data_size = be_to_uint64(&data[40]); size_t offset = 48; segments.clear(); for (uint64_t i = 0; i < segment_count; ++i) { Segment seg; seg.id = be_to_uint64(&data[offset]); seg.offset = be_to_uint64(&data[offset + 8]); seg.size = be_to_uint64(&data[offset + 16]); seg.hashed = be_to_uint32(&data[offset + 24]); seg.pad = be_to_uint32(&data[offset + 28]); segments.push_back(seg); offset += 32; } digests.clear(); for (uint64_t i = 0; i < segment_count; ++i) { Digest dig; dig.index = be_to_uint64(&data[offset]); memcpy(dig.digest, &data[offset + 8], 20); dig.pad = be_to_uint32(&data[offset + 28]); digests.push_back(dig); offset += 32; } memcpy(header_hmac, &data[offset], 20); offset += 20; memcpy(padding, &data[offset], 12); segment_data.clear(); for (const auto& seg : segments) { std::vector sdata(seg.size); memcpy(sdata.data(), &data[seg.offset], seg.size); segment_data.push_back(sdata); } } void print_properties() { std::cout << "Magic: "; for (int i = 0; i < 7; ++i) std::cout << magic[i]; std::cout << std::endl; std::cout << "Format flag: " << (int)format_flag << std::endl; std::cout << "Package version: " << package_version << std::endl; std::cout << "Image version: " << image_version << std::endl; std::cout << "Segment count: " << segment_count << std::endl; std::cout << "Header length: " << header_length << std::endl; std::cout << "Data size: " << data_size << std::endl; for (size_t i = 0; i < segments.size(); ++i) { const auto& seg = segments[i]; std::cout << "Segment " << i << ": ID=" << seg.id << ", Offset=" << seg.offset << ", Size=" << seg.size << ", Hashed=" << seg.hashed << ", Pad=" << seg.pad << std::endl; } for (size_t i = 0; i < digests.size(); ++i) { const auto& dig = digests[i]; std::cout << "Digest " << i << ": Index=" << dig.index << ", Digest="; for (int j = 0; j < 20; ++j) std::cout << std::hex << std::setw(2) << std::setfill('0') << (int)dig.digest[j]; std::cout << ", Pad=" << dig.pad << std::dec << std::endl; } std::cout << "Header HMAC: "; for (int i = 0; i < 20; ++i) std::cout << std::hex << std::setw(2) << std::setfill('0') << (int)header_hmac[i]; std::cout << std::dec << std::endl; std::cout << "Padding: "; for (int i = 0; i < 12; ++i) std::cout << std::hex << std::setw(2) << std::setfill('0') << (int)padding[i]; std::cout << std::dec << std::endl; } void save(const std::string& filename) { std::vector header(0x10000); // Oversize memcpy(&header[0], magic, 7); header[7] = format_flag; uint64_to_be(package_version, &header[8]); uint64_to_be(image_version, &header[16]); uint64_to_be(segments.size(), &header[24]); uint64_to_be(0, &header[32]); // Placeholder uint64_to_be(0, &header[40]); // Placeholder size_t offset = 48; for (const auto& seg : segments) { uint64_to_be(seg.id, &header[offset]); uint64_to_be(seg.offset, &header[offset + 8]); uint64_to_be(seg.size, &header[offset + 16]); uint32_to_be(seg.hashed, &header[offset + 24]); uint32_to_be(seg.pad, &header[offset + 28]); offset += 32; } for (const auto& dig : digests) { uint64_to_be(dig.index, &header[offset]); memcpy(&header[offset + 8], dig.digest, 20); uint32_to_be(dig.pad, &header[offset + 28]); offset += 32; } memcpy(&header[offset], header_hmac, 20); offset += 20; memcpy(&header[offset], padding, 12); offset += 12; uint64_t header_length_val = offset; uint64_t data_size_val = 0; for (const auto& d : segment_data) { data_size_val += d.size(); } // Update placeholders uint64_to_be(header_length_val, &header[32]); uint64_to_be(data_size_val, &header[40]); // Update segment offsets uint64_t current_offset = header_length_val; offset = 48; for (auto& seg : segments) { seg.offset = current_offset; uint64_to_be(seg.id, &header[offset]); uint64_to_be(seg.offset, &header[offset + 8]); uint64_to_be(seg.size, &header[offset + 16]); uint32_to_be(seg.hashed, &header[offset + 24]); uint32_to_be(seg.pad, &header[offset + 28]); current_offset += seg.size; offset += 32; } std::ofstream out(filename, std::ios::binary); out.write(reinterpret_cast(header.data()), header_length_val); for (const auto& d : segment_data) { out.write(reinterpret_cast(d.data()), d.size()); } } }; // ===== end task-584 .PUP ===== // ===== task-585 .PY [C] ===== #include #include #include #include #include #include #include typedef struct { char *filepath; char *content; } PyFileHandler; PyFileHandler* create_pyfilehandler(const char *filepath) { PyFileHandler *handler = malloc(sizeof(PyFileHandler)); handler->filepath = strdup(filepath); handler->content = NULL; return handler; } void destroy_pyfilehandler(PyFileHandler *handler) { if (handler->content) free(handler->content); free(handler->filepath); free(handler); } int open_and_decode(PyFileHandler *handler) { FILE *f = fopen(handler->filepath, "r"); if (!f) return -1; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); handler->content = malloc(size + 1); fread(handler->content, 1, size, f); handler->content[size] = '\0'; fclose(f); return 0; } char* read_content(PyFileHandler *handler) { if (!handler->content) open_and_decode(handler); return handler->content; } int write_content(PyFileHandler *handler, const char *new_content) { FILE *f = fopen(handler->filepath, "w"); if (!f) return -1; fprintf(f, "%s", new_content); fclose(f); printf("Content written to %s\n", handler->filepath); return 0; } void print_properties(PyFileHandler *handler) { struct stat st; if (stat(handler->filepath, &st) != 0) { perror("stat failed"); return; } printf("File Size: %ld bytes\n", st.st_size); printf("Creation/Change Time: %s", ctime(&st.st_ctime)); printf("Last Modification Time: %s", ctime(&st.st_mtime)); printf("Last Access Time: %s", ctime(&st.st_atime)); printf("Permissions: %o\n", st.st_mode); printf("Owner UID: %d\n", st.st_uid); printf("Owner GID: %d\n", st.st_gid); printf("Inode Number: %ld\n", st.st_ino); printf("Device ID: %ld\n", st.st_dev); printf("Number of Hard Links: %ld\n", st.st_nlink); } // Example usage: // int main() { // PyFileHandler *handler = create_pyfilehandler("example.py"); // open_and_decode(handler); // printf("%s\n", read_content(handler)); // print_properties(handler); // write_content(handler, "print(\"Hello\")\n"); // destroy_pyfilehandler(handler); // return 0; // } // ===== end task-585 .PY ===== // ===== task-586 .QFX [C++] ===== #include #include #include #include #include class QFXParser { private: std::string filename; std::map properties; public: QFXParser(const std::string& fn) : filename(fn) {} void read() { std::ifstream file(filename); if (!file.is_open()) { std::cerr << "Error opening file." << std::endl; return; } std::string line; // Parse header while (std::getline(file, line)) { if (line.find(':') != std::string::npos) { std::istringstream iss(line); std::string key, value; std::getline(iss, key, ':'); std::getline(iss, value); properties[key] = value; } else if (!line.empty()) { break; } } // Parse body std::string tag, value; do { line = line.substr(line.find_first_not_of(" \t")); if (line.rfind('<', 0) == 0 && line.rfind("\n"; for (const auto& pair : properties) { std::string key = pair.first; if (!std::all_of(key.begin(), key.end(), ::isupper) || key.find(':') != std::string::npos) { out << "<" << key << ">" << pair.second << "\n"; } } out << "\n"; out.close(); } }; // Example usage: // int main() { // QFXParser parser("sample.qfx"); // parser.read(); // parser.printProperties(); // parser.write("output.qfx"); // return 0; // } // ===== end task-586 .QFX ===== // ===== task-587 .QIF [C] ===== #include #include #include #define MAX_LINE 256 #define MAX_FIELDS 50 typedef struct { char key; char *value; } Field; typedef struct { Field fields[MAX_FIELDS]; int field_count; } Transaction; typedef struct { char *filename; Transaction *transactions; int tx_count; char *header; } QIFHandler; QIFHandler* qif_init(const char *filename) { QIFHandler *handler = malloc(sizeof(QIFHandler)); handler->filename = strdup(filename); handler->transactions = NULL; handler->tx_count = 0; handler->header = NULL; return handler; } void qif_read(QIFHandler *handler) { FILE *f = fopen(handler->filename, "r"); if (!f) return; char line[MAX_LINE]; Transaction current_tx = { .field_count = 0 }; int capacity = 0; while (fgets(line, MAX_LINE, f)) { line[strcspn(line, "\n")] = 0; // Trim newline if (strncmp(line, "!Type:", 6) == 0) { handler->header = strdup(line); } else if (strcmp(line, "^") == 0) { if (current_tx.field_count > 0) { if (handler->tx_count >= capacity) { capacity = capacity ? capacity * 2 : 4; handler->transactions = realloc(handler->transactions, capacity * sizeof(Transaction)); } handler->transactions[handler->tx_count++] = current_tx; current_tx.field_count = 0; } } else if (strlen(line) > 0) { char key = line[0]; char *value = strdup(line + 1); current_tx.fields[current_tx.field_count].key = key; current_tx.fields[current_tx.field_count].value = value; current_tx.field_count++; // Overwrite not handled; assumes no duplicates } } if (current_tx.field_count > 0) { handler->transactions[handler->tx_count++] = current_tx; } fclose(f); } void qif_print_properties(QIFHandler *handler) { printf("Header: %s\n", handler->header); for (int i = 0; i < handler->tx_count; i++) { printf("\nTransaction %d:\n", i + 1); Transaction tx = handler->transactions[i]; for (int j = 0; j < tx.field_count; j++) { printf("%c: %s\n", tx.fields[j].key, tx.fields[j].value); } } } void qif_write(QIFHandler *handler, const char *new_filename) { FILE *f = fopen(new_filename, "w"); if (!f) return; fprintf(f, "%s\n", handler->header); for (int i = 0; i < handler->tx_count; i++) { Transaction tx = handler->transactions[i]; for (int j = 0; j < tx.field_count; j++) { fprintf(f, "%c%s\n", tx.fields[j].key, tx.fields[j].value); } fprintf(f, "^\n"); } fclose(f); } void qif_free(QIFHandler *handler) { free(handler->header); for (int i = 0; i < handler->tx_count; i++) { for (int j = 0; j < handler->transactions[i].field_count; j++) { free(handler->transactions[i].fields[j].value); } } free(handler->transactions); free(handler->filename); free(handler); } // Example usage: // int main() { // QIFHandler *handler = qif_init("sample.qif"); // qif_read(handler); // qif_print_properties(handler); // qif_write(handler, "output.qif"); // qif_free(handler); // return 0; // } // ===== end task-587 .QIF ===== // ===== task-588 .QLC [C] ===== #include #include #include #include #define MAX_LINES 1000 #define MAX_PARAMS 20 #define MAX_STR 256 typedef struct { int xref; char **ports; int ports_count; char **types; int types_count; char **stations; int stations_count; char **ios; int ios_count; char **comments; int comments_count; } QLCProperties; QLCProperties* create_properties() { QLCProperties* props = malloc(sizeof(QLCProperties)); props->xref = 0; props->ports = NULL; props->ports_count = 0; props->types = NULL; props->types_count = 0; props->stations = NULL; props->stations_count = 0; props->ios = NULL; props->ios_count = 0; props->comments = NULL; props->comments_count = 0; return props; } void add_to_list(char*** list, int* count, const char* line) { (*count)++; *list = realloc(*list, (*count) * sizeof(char*)); (*list)[*count - 1] = strdup(line); } void read_and_decode(const char* filename, QLCProperties* props) { FILE* fp = fopen(filename, "r"); if (!fp) return; char line[MAX_STR]; while (fgets(line, sizeof(line), fp)) { for (char* p = line; *p; p++) *p = toupper(*p); char* trim = strtok(line, "\n"); if (!trim || strlen(trim) == 0) continue; if (trim[0] == '*') { add_to_list(&props->comments, &props->comments_count, trim + 1); } else if (strncmp(trim, "XREF", 4) == 0) { props->xref = 1; } else if (strncmp(trim, "PORT", 4) == 0) { add_to_list(&props->ports, &props->ports_count, trim + 4); } else if (strncmp(trim, "TYPE", 4) == 0) { add_to_list(&props->types, &props->types_count, trim + 4); } else if (strncmp(trim, "STATION", 7) == 0) { add_to_list(&props->stations, &props->stations_count, trim + 7); } else if (strncmp(trim, "IN", 2) == 0 || strncmp(trim, "OUT", 3) == 0 || strncmp(trim, "IN_E", 4) == 0 || strncmp(trim, "OUT_E", 5) == 0) { add_to_list(&props->ios, &props->ios_count, trim); } } fclose(fp); } void print_properties(QLCProperties* props) { printf("XREF: %d\n", props->xref); printf("Ports (%d):\n", props->ports_count); for (int i = 0; i < props->ports_count; i++) printf("%s\n", props->ports[i]); printf("Types (%d):\n", props->types_count); for (int i = 0; i < props->types_count; i++) printf("%s\n", props->types[i]); printf("Stations (%d):\n", props->stations_count); for (int i = 0; i < props->stations_count; i++) printf("%s\n", props->stations[i]); printf("I/Os (%d):\n", props->ios_count); for (int i = 0; i < props->ios_count; i++) printf("%s\n", props->ios[i]); printf("Comments (%d):\n", props->comments_count); for (int i = 0; i < props->comments_count; i++) printf("%s\n", props->comments[i]); } void write(const char* new_filename, QLCProperties* props) { FILE* fp = fopen(new_filename, "w"); if (!fp) return; if (props->xref) fprintf(fp, "XREF\n"); for (int i = 0; i < props->ports_count; i++) fprintf(fp, "PORT%s\n", props->ports[i]); for (int i = 0; i < props->types_count; i++) fprintf(fp, "TYPE%s\n", props->types[i]); for (int i = 0; i < props->stations_count; i++) fprintf(fp, "STATION%s\n", props->stations[i]); for (int i = 0; i < props->ios_count; i++) fprintf(fp, "%s\n", props->ios[i]); for (int i = 0; i < props->comments_count; i++) fprintf(fp, "* %s\n", props->comments[i]); fclose(fp); } void free_properties(QLCProperties* props) { for (int i = 0; i < props->ports_count; i++) free(props->ports[i]); free(props->ports); for (int i = 0; i < props->types_count; i++) free(props->types[i]); free(props->types); for (int i = 0; i < props->stations_count; i++) free(props->stations[i]); free(props->stations); for (int i = 0; i < props->ios_count; i++) free(props->ios[i]); free(props->ios); for (int i = 0; i < props->comments_count; i++) free(props->comments[i]); free(props->comments); free(props); } // Example usage // int main() { // QLCProperties* props = create_properties(); // read_and_decode("example.qlc", props); // print_properties(props); // write("new.qlc", props); // free_properties(props); // return 0; // } // ===== end task-588 .QLC ===== // ===== task-590 .QSS [C++] ===== #include #include #include #include #include #include class QSSHandler { private: std::unordered_set supported_properties = { "accent-color", "alternate-background-color", "background", "background-attachment", "background-clip", "background-color", "background-image", "background-origin", "background-position", "background-repeat", "border", "border-bottom", "border-bottom-color", "border-bottom-left-radius", "border-bottom-right-radius", "border-bottom-style", "border-bottom-width", "border-color", "border-image", "border-left", "border-left-color", "border-left-style", "border-left-width", "border-radius", "border-right", "border-right-color", "border-right-style", "border-right-width", "border-style", "border-top", "border-top-color", "border-top-left-radius", "border-top-right-radius", "border-top-style", "border-top-width", "bottom", "button-layout", "color", "dialogbuttonbox-buttons-have-icons", "font", "font-family", "font-size", "font-style", "font-weight", "gridline-color", "height", "image", "image-position", "left", "lineedit-password-character", "lineedit-password-mask-delay", "margin", "margin-bottom", "margin-left", "margin-right", "margin-top", "max-height", "max-width", "messagebox-text-interaction-flags", "min-height", "min-width", "opacity", "outline", "outline-color", "outline-offset", "outline-radius", "outline-bottom-left-radius", "outline-bottom-right-radius", "outline-style", "outline-top-left-radius", "outline-top-right-radius", "padding", "padding-bottom", "padding-left", "padding-right", "padding-top", "paint-alternating-row-colors-for-empty-area", "position", "selection-background-color", "selection-color", "show-decoration-selected", "spacing", "subcontrol-origin", "subcontrol-position", "text-align", "text-decoration", "titletext-align", "top", "width" }; std::unordered_map properties; public: void openAndDecode(const std::string& filepath) { if (filepath.substr(filepath.find_last_of(".") + 1) != "qss") { throw std::invalid_argument("File must have .qss extension."); } std::ifstream file(filepath); if (!file.is_open()) { throw std::runtime_error("File not found."); } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); std::regex regex(R"(([\w-]+)\s*:\s*([^;]+);)"); std::sregex_iterator iter(content.begin(), content.end(), regex); std::sregex_iterator end; for (; iter != end; ++iter) { std::string prop = iter->str(1); if (supported_properties.count(prop)) { properties[prop] = iter->str(2); } } } void printProperties() const { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& filepath, const std::string& selector = "*", const std::unordered_map& new_properties = {}) { for (const auto& pair : new_properties) { if (supported_properties.count(pair.first)) { properties[pair.first] = pair.second; } } std::ofstream file(filepath); if (!file.is_open()) { throw std::runtime_error("Unable to write file."); } file << selector << " {\n"; for (const auto& pair : properties) { file << " " << pair.first << ": " << pair.second << ";\n"; } file << "}\n"; file.close(); } }; // ===== end task-590 .QSS ===== // ===== task-591 .QT [C] ===== #include #include #include #include typedef struct { uint32_t size; char type[5]; // Properties as union/variants; simplified to strings for print char props[1024]; } AtomProps; AtomProps properties[1000]; int prop_count = 0; FILE *file; long pos = 0; uint32_t read_uint32() { uint32_t val; fread(&val, 4, 1, file); return __builtin_bswap32(val); // Big-endian } uint64_t read_uint64() { uint64_t val; fread(&val, 8, 1, file); return __builtin_bswap64(val); } uint8_t read_byte() { uint8_t val; fread(&val, 1, 1, file); return val; } uint16_t read_uint16() { uint16_t val; fread(&val, 2, 1, file); return __builtin_bswap16(val); } uint32_t read_uint24() { uint8_t buf[3]; fread(buf, 3, 1, file); return (buf[0] << 16) | (buf[1] << 8) | buf[2]; } float read_fixed() { int32_t val; fread(&val, 4, 1, file); val = __builtin_bswap32(val); return ((val >> 16) & 0xFFFF) + (val & 0xFFFF) / 65536.0f; } char* read_str(int len) { char *s = malloc(len + 1); fread(s, len, 1, file); s[len] = '\0'; return s; } long read_time(int version) { if (version == 1) { uint64_t t; fread(&t, 8, 1, file); return __builtin_bswap64(t); } else { uint32_t t; fread(&t, 4, 1, file); return __builtin_bswap32(t); } } long read_duration(int version) { return version == 1 ? read_uint64() : read_uint32(); } void parse_atom() { long start_pos = pos; uint32_t size = read_uint32(); pos += 4; if (size == 1) { size = read_uint64(); pos += 8; } char type[5]; fread(type, 4, 1, file); type[4] = '\0'; pos += 4; long end_pos = pos + size - 8; printf("Atom: %s (size: %u, pos: %ld)\n", type, size, start_pos); char prop_str[1024] = {0}; if (strcmp(type, "ftyp") == 0) { char *major = read_str(4); uint32_t minor = read_uint32(); // Compat loop (simplified) sprintf(prop_str, "Major: %s, Minor: %u", major, minor); free(major); printf(" %s\n", prop_str); } else if (strcmp(type, "mvhd") == 0) { uint8_t version = read_byte(); uint32_t flags = read_uint24(); long ctime = read_time(version); long mtime = read_time(version); uint32_t timescale = read_uint32(); long duration = read_duration(version); float rate = read_fixed(); float volume = read_fixed(); read_uint16(); // reserved // Matrix (9 floats) float matrix[9]; for (int i = 0; i < 9; i++) matrix[i] = read_fixed(); // ... other fields sprintf(prop_str, "Timescale: %u, Duration: %ld, Rate: %.2f", timescale, duration, rate); printf(" %s\n", prop_str); } // Similar for tkhd, mdhd, etc. (implement as above) // For containers: while (pos < end_pos) parse_atom(); // Skip: fseek(file, end_pos - pos, SEEK_CUR); fseek(file, end_pos - pos, SEEK_CUR); pos = end_pos; // Store properties[prop_count].size = size; strcpy(properties[prop_count].type, type); strcpy(properties[prop_count].props, prop_str); prop_count++; } void parse_and_print(const char *filename) { file = fopen(filename, "rb"); if (!file) return; while (pos < 0 || ftell(file) < 0) { // Approx length parse_atom(); } fclose(file); printf("\nParsing complete.\n"); } void write(const char *output_filename) { FILE *out = fopen(output_filename, "wb"); if (!out) return; // Basic write loop over properties (simplified) for (int i = 0; i < prop_count; i++) { fwrite(&properties[i].size, 4, 1, out); // Big-endian swap if needed fwrite(properties[i].type, 4, 1, out); // Write props data (extend) } fclose(out); printf("Write complete (basic).\n"); } int main(int argc, char **argv) { if (argc < 2) return 1; parse_and_print(argv[1]); write("output.qt"); return 0; } // ===== end task-591 .QT ===== // ===== task-592 .QTVR [C] ===== #include #include #include #include typedef struct { uint16_t majorVersion; uint16_t minorVersion; uint32_t nameAtomID; uint32_t defaultNodeID; uint32_t vrWorldFlags; uint32_t reserved1; uint32_t reserved2; uint16_t stringUsage; uint16_t stringLength; char* theString; uint32_t imagingMode; uint32_t imagingValidFlags; uint32_t correction; uint32_t quality; uint32_t directDraw; uint32_t imagingProperties[6]; char nodeType[5]; uint32_t locationFlags; uint32_t locationData; uint32_t nodeID; uint32_t commentAtomID; uint32_t cursorID[3]; float bestPan; char hotSpotType[5]; // Add more as needed } QTVRProperties; typedef struct { FILE* file; char* filepath; QTVRProperties props; } QTVRParser; QTVRParser* createQTVRParser(const char* filepath) { QTVRParser* parser = malloc(sizeof(QTVRParser)); parser->filepath = strdup(filepath); parser->file = NULL; memset(&parser->props, 0, sizeof(QTVRProperties)); return parser; } void destroyQTVRParser(QTVRParser* parser) { if (parser->file) fclose(parser->file); free(parser->filepath); if (parser->props.theString) free(parser->props.theString); free(parser); } uint32_t readUInt32(FILE* file) { uint32_t val; fread(&val, 4, 1, file); return __builtin_bswap32(val); // BE to LE if needed } uint16_t readUInt16(FILE* file) { uint16_t val; fread(&val, 2, 1, file); return __builtin_bswap16(val); } void readOSType(FILE* file, char* buf) { fread(buf, 1, 4, file); buf[4] = '\0'; } float readFloat(FILE* file) { uint32_t val = readUInt32(file); float f; memcpy(&f, &val, 4); return f; } void readString(FILE* file, char* buf, int len) { fread(buf, 1, len, file); buf[len] = '\0'; } void parseAtom(QTVRParser* parser) { long start = ftell(parser->file); uint32_t size = readUInt32(parser->file); char type[5]; readOSType(parser->file, type); long end = start + size; if (strcmp(type, "moov") == 0 || strcmp(type, "trak") == 0 || strcmp(type, "mdia") == 0 || strcmp(type, "minf") == 0 || strcmp(type, "stbl") == 0) { while (ftell(parser->file) < end) { parseAtom(parser); } } else if (strcmp(type, "vrsc") == 0) { parser->props.majorVersion = readUInt16(parser->file); parser->props.minorVersion = readUInt16(parser->file); parser->props.nameAtomID = readUInt32(parser->file); parser->props.defaultNodeID = readUInt32(parser->file); parser->props.vrWorldFlags = readUInt32(parser->file); parser->props.reserved1 = readUInt32(parser->file); parser->props.reserved2 = readUInt32(parser->file); } else if (strcmp(type, "vrsg") == 0) { parser->props.stringUsage = readUInt16(parser->file); parser->props.stringLength = readUInt16(parser->file); parser->props.theString = malloc(parser->props.stringLength + 1); readString(parser->file, parser->props.theString, parser->props.stringLength); } else if (strcmp(type, "impn") == 0) { parser->props.majorVersion = readUInt16(parser->file); parser->props.minorVersion = readUInt16(parser->file); parser->props.imagingMode = readUInt32(parser->file); parser->props.imagingValidFlags = readUInt32(parser->file); parser->props.correction = readUInt32(parser->file); parser->props.quality = readUInt32(parser->file); parser->props.directDraw = readUInt32(parser->file); for (int i = 0; i < 6; i++) { parser->props.imagingProperties[i] = readUInt32(parser->file); } parser->props.reserved1 = readUInt32(parser->file); parser->props.reserved2 = readUInt32(parser->file); } else if (strcmp(type, "nloc") == 0) { parser->props.majorVersion = readUInt16(parser->file); parser->props.minorVersion = readUInt16(parser->file); readOSType(parser->file, parser->props.nodeType); parser->props.locationFlags = readUInt32(parser->file); parser->props.locationData = readUInt32(parser->file); parser->props.reserved1 = readUInt32(parser->file); parser->props.reserved2 = readUInt32(parser->file); } else if (strcmp(type, "ndhd") == 0) { parser->props.majorVersion = readUInt16(parser->file); parser->props.minorVersion = readUInt16(parser->file); readOSType(parser->file, parser->props.nodeType); parser->props.nodeID = readUInt32(parser->file); parser->props.nameAtomID = readUInt32(parser->file); parser->props.commentAtomID = readUInt32(parser->file); parser->props.reserved1 = readUInt32(parser->file); parser->props.reserved2 = readUInt32(parser->file); } else if (strcmp(type, "hsin") == 0) { parser->props.majorVersion = readUInt16(parser->file); parser->props.minorVersion = readUInt16(parser->file); readOSType(parser->file, parser->props.hotSpotType); parser->props.nameAtomID = readUInt32(parser->file); parser->props.commentAtomID = readUInt32(parser->file); for (int i = 0; i < 3; i++) { parser->props.cursorID[i] = readUInt32(parser->file); } parser->props.bestPan = readFloat(parser->file); } else { fseek(parser->file, end, SEEK_SET); } } void readQTVR(QTVRParser* parser) { parser->file = fopen(parser->filepath, "rb"); if (!parser->file) return; fseek(parser->file, 0, SEEK_END); long file_size = ftell(parser->file); fseek(parser->file, 0, SEEK_SET); while (ftell(parser->file) < file_size) { parseAtom(parser); } fclose(parser->file); parser->file = NULL; } void printProperties(QTVRParser* parser) { printf("majorVersion: %u\n", parser->props.majorVersion); printf("minorVersion: %u\n", parser->props.minorVersion); printf("nameAtomID: %u\n", parser->props.nameAtomID); // Print others similarly if (parser->props.theString) printf("theString: %s\n", parser->props.theString); // etc. } void writeQTVR(QTVRParser* parser, const char* new_filepath) { // Placeholder: copy file, full write rebuilds atoms FILE* in = fopen(parser->filepath, "rb"); FILE* out = fopen(new_filepath, "wb"); char buf[1024]; size_t len; while ((len = fread(buf, 1, 1024, in)) > 0) { fwrite(buf, 1, len, out); } fclose(in); fclose(out); } // Usage: // QTVRParser* parser = createQTVRParser("sample.qtvr"); // readQTVR(parser); // printProperties(parser); // writeQTVR(parser, "output.qtvr"); // destroyQTVRParser(parser); // ===== end task-592 .QTVR ===== // ===== task-593 .R [C] ===== #include #include #include #include #include typedef struct { char *path; struct stat statbuf; } RFile; RFile* rfile_new(const char *path) { RFile *rf = malloc(sizeof(RFile)); rf->path = strdup(path); if (stat(path, &rf->statbuf) != 0) { perror("stat"); free(rf); return NULL; } return rf; } void rfile_free(RFile *rf) { free(rf->path); free(rf); } char* rfile_read(RFile *rf) { FILE *f = fopen(rf->path, "r"); if (!f) { perror("fopen"); return NULL; } fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); char *content = malloc(size + 1); fread(content, 1, size, f); content[size] = '\0'; fclose(f); return content; } void rfile_write(RFile *rf, const char *content) { FILE *f = fopen(rf->path, "w"); if (!f) { perror("fopen"); return; } fprintf(f, "%s", content); fclose(f); // Update stat after write stat(rf->path, &rf->statbuf); } void rfile_print_properties(RFile *rf) { printf("Inode number: %ld\n", rf->statbuf.st_ino); printf("Device ID: %ld\n", rf->statbuf.st_dev); printf("Mode (permissions): %o\n", rf->statbuf.st_mode); printf("Number of hard links: %ld\n", rf->statbuf.st_nlink); printf("User ID (UID): %d\n", rf->statbuf.st_uid); printf("Group ID (GID): %d\n", rf->statbuf.st_gid); printf("File size: %ld bytes\n", rf->statbuf.st_size); printf("Last access time: %s", ctime(&rf->statbuf.st_atime)); printf("Last modification time: %s", ctime(&rf->statbuf.st_mtime)); printf("Last status change time: %s", ctime(&rf->statbuf.st_ctime)); } // Example usage: // int main() { // RFile *rf = rfile_new("example.R"); // if (!rf) return 1; // char *content = rfile_read(rf); // printf("%s\n", content); // free(content); // rfile_write(rf, "print(\"Hello from R\")\n"); // rfile_print_properties(rf); // rfile_free(rf); // return 0; // } // ===== end task-593 .R ===== // ===== task-594 .ROO [C] ===== #include #include #include #include typedef struct { uint8_t *data; size_t size; } RARParser; uint16_t read_uint16_le(const uint8_t *buf, size_t offset) { return (buf[offset + 1] << 8) | buf[offset]; } uint32_t read_uint32_le(const uint8_t *buf, size_t offset) { return (buf[offset + 3] << 24) | (buf[offset + 2] << 16) | (buf[offset + 1] << 8) | buf[offset]; } void parse_rar(RARParser *p) { printf("Parsing .R00 file...\n"); size_t offset = 0; // Find marker uint8_t marker[] = {0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x00}; size_t marker_pos = -1; for (size_t i = 0; i < p->size - 6; i++) { if (memcmp(&p->data[i], marker, 7) == 0) { marker_pos = i; break; } } if (marker_pos == -1) { printf("Error: No RAR marker found\n"); return; } offset = marker_pos + 7; // Archive header uint16_t head_crc = read_uint16_le(p->data, offset); offset += 2; uint8_t head_type = p->data[offset]; offset += 1; if (head_type != 0x73) { printf("Error: No archive header\n"); return; } uint16_t head_flags = read_uint16_le(p->data, offset); offset += 2; uint16_t head_size = read_uint16_le(p->data, offset); offset += 2; printf("Archive Properties:\n"); printf(" volume: %d\n", !!(head_flags & 0x0001)); printf(" locked: %d\n", !!(head_flags & 0x0004)); printf(" solid: %d\n", !!(head_flags & 0x0008)); printf(" recovery: %d\n", !!(head_flags & 0x0040)); printf(" first_volume: %d\n", !!(head_flags & 0x0100)); offset += 6; // Skip reserved if (head_size > 13) { printf(" comment_size: %d\n", head_size - 13); } printf(" split_continuation: 1\n"); // For .R00 printf(" parsed_bytes: %zu\n", offset); // Placeholder for file entries printf("\nFile Entry Properties (from first volume recommended):\n"); printf(" file_name: (path/to/file)\n"); printf(" unpacked_size: 1024\n"); printf(" packed_size: 512\n"); printf(" host_os: 2 (Windows)\n"); printf(" file_attributes: 0x20 (Archive)\n"); printf(" modification_time: 2025-11-12 12:00:00\n"); printf(" crc32: 0x12345678\n"); printf(" unpacking_version: 29\n"); printf(" compression_method: 0x33 (Normal)\n"); printf(" dictionary_size: 1024 KB\n"); printf(" solid: 0\n"); printf(" encryption: 0\n"); printf(" unicode: 1\n"); } int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: ./rar_parser \n"); return 1; } FILE *f = fopen(argv[1], "rb"); if (!f) { perror("Error opening file"); return 1; } fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); RARParser p = {data, size}; parse_rar(&p); free(data); return 0; } // ===== end task-594 .ROO ===== // ===== task-595 .R01 [C++] ===== #include #include #include #include class R01Handler { private: std::string filename; std::vector data; public: R01Handler(const std::string& fn) : filename(fn) {} void read() { std::ifstream file(filename, std::ios::binary); if (file) { data = std::vector((std::istreambuf_iterator(file)), std::istreambuf_iterator()); } } void decodeAndPrint() { if (data.empty()) read(); size_t pos = 0; std::cout << "Magic Signature: "; for (int i = 0; i < 7; ++i) std::cout << std::hex << std::setfill('0') << std::setw(2) << (int)data[pos++] << " "; std::cout << std::dec << std::endl; while (pos < data.size()) { unsigned short crc16 = *(unsigned short*)(&data[pos]); pos += 2; unsigned char type = data[pos++]; unsigned short flags = *(unsigned short*)(&data[pos]); pos += 2; unsigned short size = *(unsigned short*)(&data[pos]); pos += 2; std::cout << "Header CRC16: 0x" << std::hex << crc16 << std::dec << std::endl; std::cout << "Header Type: 0x" << std::hex << (int)type << std::dec << std::endl; std::cout << "Header Flags: 0x" << std::hex << flags << std::dec << std::endl; std::cout << "Header Size: " << size << std::endl; if (flags & 0x8000) { unsigned int addSize = *(unsigned int*)(&data[pos]); pos += 4; std::cout << "Add Size: " << addSize << std::endl; } if (type == 0x73) { // Main header unsigned short highPosAv = *(unsigned short*)(&data[pos]); pos += 2; unsigned int posAv = *(unsigned int*)(&data[pos]); pos += 4; std::cout << "HighPosAV: " << highPosAv << std::endl; std::cout << "PosAV: " << posAv << std::endl; if (flags & 0x0200) { unsigned char encryptVer = data[pos++]; std::cout << "EncryptVer: " << (int)encryptVer << std::endl; } } else if (type == 0x74) { // File header unsigned int packSize = *(unsigned int*)(&data[pos]); pos += 4; unsigned int unpSize = *(unsigned int*)(&data[pos]); pos += 4; unsigned char hostOS = data[pos++]; unsigned int fileCRC = *(unsigned int*)(&data[pos]); pos += 4; unsigned int fileTime = *(unsigned int*)(&data[pos]); pos += 4; unsigned char unpVer = data[pos++]; unsigned char method = data[pos++]; unsigned short nameSize = *(unsigned short*)(&data[pos]); pos += 2; unsigned int fileAttr = *(unsigned int*)(&data[pos]); pos += 4; std::cout << "PackSize: " << packSize << std::endl; std::cout << "UnpSize: " << unpSize << std::endl; std::cout << "HostOS: " << (int)hostOS << std::endl; std::cout << "FileCRC: 0x" << std::hex << fileCRC << std::dec << std::endl; std::cout << "FileTime: " << fileTime << std::endl; std::cout << "UnpVer: " << (int)unpVer << std::endl; std::cout << "Method: 0x" << std::hex << (int)method << std::dec << std::endl; std::cout << "NameSize: " << nameSize << std::endl; std::cout << "FileAttr: 0x" << std::hex << fileAttr << std::dec << std::endl; if (flags & 0x0100) { unsigned int highPackSize = *(unsigned int*)(&data[pos]); pos += 4; unsigned int highUnpSize = *(unsigned int*)(&data[pos]); pos += 4; std::cout << "HighPackSize: " << highPackSize << std::endl; std::cout << "HighUnpSize: " << highUnpSize << std::endl; } std::string fileName(data.begin() + pos, data.begin() + pos + nameSize); pos += nameSize; std::cout << "FileName: " << fileName << std::endl; if (flags & 0x0400) { std::cout << "Salt: "; for (int i = 0; i < 8; ++i) std::cout << std::hex << std::setfill('0') << std::setw(2) << (int)data[pos++] << " "; std::cout << std::dec << std::endl; } if (flags & 0x1000) { unsigned short extFlags = *(unsigned short*)(&data[pos]); pos += 2; std::cout << "ExtTime Flags: 0x" << std::hex << extFlags << std::dec << std::endl; // Further parsing omitted } } pos += size - 7 - ((flags & 0x8000) ? 4 : 0); } } void write(const std::string& outputFilename, const std::vector& sampleData) { std::ofstream file(outputFilename, std::ios::binary); if (!file) return; unsigned char sig[7] = {0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x00}; file.write((char*)sig, 7); // Main header (dummy) unsigned char mainHeader[13] = {0}; // CRC, type 0x73, flags 0, size 13, HighPosAV 0, PosAV 0, EncryptVer 0 mainHeader[2] = 0x73; mainHeader[5] = 13; // Low byte of size file.write((char*)mainHeader, 13); // File header std::string name = "sample.txt"; size_t headerSize = 32 + name.size(); std::vector fileHeader(headerSize, 0); fileHeader[2] = 0x74; // Type *(unsigned short*)(&fileHeader[5]) = headerSize; // Size *(unsigned int*)(&fileHeader[7]) = sampleData.size(); // PackSize *(unsigned int*)(&fileHeader[11]) = sampleData.size(); // UnpSize fileHeader[15] = 2; // HostOS fileHeader[24] = 29; // UnpVer fileHeader[25] = 0x30; // Method *(unsigned short*)(&fileHeader[26]) = name.size(); // NameSize name.copy((char*)&fileHeader[32], name.size()); file.write((char*)fileHeader.data(), headerSize); file.write((char*)sampleData.data(), sampleData.size()); std::cout << "Wrote sample .R01 to " << outputFilename << std::endl; } }; // ===== end task-595 .R01 ===== // ===== task-596 .R2D [C] ===== #include #include #include typedef struct { char *filepath; char *content; } R2DFile; R2DFile* createR2DFile(const char *filepath) { R2DFile *r2d = (R2DFile*)malloc(sizeof(R2DFile)); r2d->filepath = strdup(filepath); r2d->content = NULL; return r2d; } void readFile(R2DFile *r2d) { FILE *file = fopen(r2d->filepath, "r"); if (file == NULL) { perror("Error opening file"); return; } fseek(file, 0, SEEK_END); long size = ftell(file); fseek(file, 0, SEEK_SET); r2d->content = (char*)malloc(size + 1); fread(r2d->content, 1, size, file); r2d->content[size] = '\0'; fclose(file); } void decodeAndPrint(R2DFile *r2d) { if (r2d->content == NULL) { readFile(r2d); } printf("Plain text content (database entries):\n"); printf("%s\n", r2d->content); } void writeFile(R2DFile *r2d, const char *newContent) { FILE *file = fopen(r2d->filepath, "w"); if (file == NULL) { perror("Error opening file"); return; } fprintf(file, "%s", newContent); fclose(file); free(r2d->content); r2d->content = strdup(newContent); } void destroyR2DFile(R2DFile *r2d) { free(r2d->filepath); free(r2d->content); free(r2d); } // Example usage: // int main() { // R2DFile *r2d = createR2DFile("example.r2d"); // decodeAndPrint(r2d); // writeFile(r2d, "New database entries"); // destroyR2DFile(r2d); // return 0; // } // ===== end task-596 .R2D ===== // ===== task-597 .R3D [C++] ===== #include #include #include #include #include #include class R3DFile { private: std::string filepath; std::map properties; uint32_t readUInt32BE(std::ifstream& f) { uint32_t val; f.read(reinterpret_cast(&val), 4); return __builtin_bswap32(val); // Assuming little-endian host } uint32_t readUInt32LE(std::ifstream& f) { uint32_t val; f.read(reinterpret_cast(&val), 4); return val; } float readFloat(std::ifstream& f) { float val; f.read(reinterpret_cast(&val), 4); return val; } std::string readString(std::ifstream& f, size_t length) { char* buf = new char[length + 1]; f.read(buf, length); buf[length] = '\0'; std::string str(buf); delete[] buf; size_t nullPos = str.find('\0'); if (nullPos != std::string::npos) str = str.substr(0, nullPos); return str; } void parse() { std::ifstream f(filepath, std::ios::binary); if (!f) throw std::runtime_error("File open failed"); uint32_t headerSize = readUInt32BE(f); std::string magic = readString(f, 4); if (magic != "RED1") throw std::runtime_error("Invalid .R3D file"); properties["Magic Number"] = magic; while (f.tellg() < headerSize) { uint32_t atomSize = readUInt32BE(f); std::string atomType = readString(f, 4); std::streampos atomStart = f.tellg() - static_cast(8); if (atomType == "REDV") { properties["Video Version"] = std::to_string(readUInt32BE(f)); properties["Model ID"] = std::to_string(readUInt32BE(f)); properties["Frame Number"] = std::to_string(readUInt32BE(f)); f.seekg(128, std::ios::cur); properties["Image Width"] = std::to_string(readUInt32LE(f)); properties["Image Height"] = std::to_string(readUInt32LE(f)); f.seekg(18, std::ios::cur); properties["Timescale"] = std::to_string(readUInt32LE(f)); } else if (atomType == "REDA") { properties["Audio Version"] = std::to_string(readUInt32BE(f)); properties["Audio Channels"] = std::to_string(readUInt32BE(f)); properties["Audio Sample Rate"] = std::to_string(readUInt32BE(f)); } else if (atomType == "RED1") { properties["Project Name"] = readString(f, 32); properties["Clip Name"] = readString(f, 32); properties["Camera Model"] = readString(f, 16); } else if (atomType == "RDVO") { properties["Data Offset"] = std::to_string(readUInt32BE(f)); } f.seekg(atomStart + atomSize); } f.close(); } public: R3DFile(const std::string& filepath) : filepath(filepath) { parse(); } std::map readProperties() { return properties; } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& outputPath) { std::ifstream src(filepath, std::ios::binary); std::ofstream dst(outputPath, std::ios::binary); dst << src.rdbuf(); // Full write would modify fields in-place } }; // Example usage: // int main() { // R3DFile r3d("sample.R3D"); // r3d.printProperties(); // r3d.write("modified.R3D"); // return 0; // } // ===== end task-597 .R3D ===== // ===== task-598 .R8P [C] ===== #include #include #include #include #include // For htons, etc. typedef struct { char *filename; uint8_t *data; size_t data_size; // Properties as a simple array for demo; use a map lib for full. char *prop_keys[40]; char prop_values[40][64]; // Stringified values int prop_count; } R8PHandler; R8PHandler* create_r8p_handler(const char *filename) { R8PHandler *handler = malloc(sizeof(R8PHandler)); handler->filename = strdup(filename); handler->data = NULL; handler->data_size = 0; handler->prop_count = 0; return handler; } void read_r8p(R8PHandler *handler) { FILE *f = fopen(handler->filename, "rb"); if (!f) { perror("Failed to open file"); return; } fseek(f, 0, SEEK_END); handler->data_size = ftell(f); fseek(f, 0, SEEK_SET); handler->data = malloc(handler->data_size); fread(handler->data, 1, handler->data_size, f); fclose(f); decode_r8p(handler); } void decode_r8p(R8PHandler *handler) { uint8_t *data = handler->data; int offset = 0; char buf[64]; uint16_t val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Font Descriptor Size"; strcpy(handler->prop_values[handler->prop_count++], buf); uint8_t val8 = data[offset]; offset += 1; snprintf(buf, sizeof(buf), "%u", val8); handler->prop_keys[handler->prop_count] = "Header Format"; strcpy(handler->prop_values[handler->prop_count++], buf); // Repeat for other fields similarly... val8 = data[offset]; offset += 1; snprintf(buf, sizeof(buf), "%u", val8); handler->prop_keys[handler->prop_count] = "Font Type"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Style MSB"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Baseline Position"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Cell Width"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Cell Height"; strcpy(handler->prop_values[handler->prop_count++], buf); val8 = data[offset]; offset += 1; snprintf(buf, sizeof(buf), "%u", val8); handler->prop_keys[handler->prop_count] = "Orientation"; strcpy(handler->prop_values[handler->prop_count++], buf); val8 = data[offset]; offset += 1; snprintf(buf, sizeof(buf), "%u", val8); handler->prop_keys[handler->prop_count] = "Spacing"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Symbol Set"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Pitch (Default HMI)"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Height"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "xHeight"; strcpy(handler->prop_values[handler->prop_count++], buf); int8_t val_s8 = *(int8_t*)(data + offset); offset += 1; snprintf(buf, sizeof(buf), "%d", val_s8); handler->prop_keys[handler->prop_count] = "Width Type"; strcpy(handler->prop_values[handler->prop_count++], buf); val8 = data[offset]; offset += 1; snprintf(buf, sizeof(buf), "%u", val8); handler->prop_keys[handler->prop_count] = "Style LSB"; strcpy(handler->prop_values[handler->prop_count++], buf); val_s8 = *(int8_t*)(data + offset); offset += 1; snprintf(buf, sizeof(buf), "%d", val_s8); handler->prop_keys[handler->prop_count] = "Stroke Weight"; strcpy(handler->prop_values[handler->prop_count++], buf); val8 = data[offset]; offset += 1; snprintf(buf, sizeof(buf), "%u", val8); handler->prop_keys[handler->prop_count] = "Typeface LSB"; strcpy(handler->prop_values[handler->prop_count++], buf); val8 = data[offset]; offset += 1; snprintf(buf, sizeof(buf), "%u", val8); handler->prop_keys[handler->prop_count] = "Typeface MSB"; strcpy(handler->prop_values[handler->prop_count++], buf); val8 = data[offset]; offset += 1; snprintf(buf, sizeof(buf), "%u", val8); handler->prop_keys[handler->prop_count] = "Serif Style"; strcpy(handler->prop_values[handler->prop_count++], buf); val8 = data[offset]; offset += 1; snprintf(buf, sizeof(buf), "%u", val8); handler->prop_keys[handler->prop_count] = "Quality/Placement"; strcpy(handler->prop_values[handler->prop_count++], buf); int16_t val_s16 = ntohs(*(int16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%d", val_s16); handler->prop_keys[handler->prop_count] = "Underline Position (Distance)"; strcpy(handler->prop_values[handler->prop_count++], buf); val8 = data[offset]; offset += 1; snprintf(buf, sizeof(buf), "%u", val8); handler->prop_keys[handler->prop_count] = "Underline Thickness (Height)"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Text Height"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Text Width"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "First Code"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Last Code / Number of Characters"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Pitch Extended / Height Extended"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Cap Height"; strcpy(handler->prop_values[handler->prop_count++], buf); uint32_t val32 = ntohl(*(uint32_t*)(data + offset)); offset += 4; snprintf(buf, sizeof(buf), "%u", val32); handler->prop_keys[handler->prop_count] = "Font Number"; strcpy(handler->prop_values[handler->prop_count++], buf); char font_name[17]; memcpy(font_name, data + offset, 16); font_name[16] = '\0'; handler->prop_keys[handler->prop_count] = "Font Name"; strcpy(handler->prop_values[handler->prop_count++], font_name); offset += 16; val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "X Resolution"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Y Resolution"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Scale Factor"; strcpy(handler->prop_values[handler->prop_count++], buf); val_s16 = ntohs(*(int16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%d", val_s16); handler->prop_keys[handler->prop_count] = "Master Underline Position"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Master Underline Thickness (Height)"; strcpy(handler->prop_values[handler->prop_count++], buf); val8 = data[offset]; offset += 1; snprintf(buf, sizeof(buf), "%u", val8); handler->prop_keys[handler->prop_count] = "Font Scaling Technology"; strcpy(handler->prop_values[handler->prop_count++], buf); val8 = data[offset]; offset += 1; snprintf(buf, sizeof(buf), "%u", val8); handler->prop_keys[handler->prop_count] = "Variety"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "OR Threshold"; strcpy(handler->prop_values[handler->prop_count++], buf); val_s16 = ntohs(*(int16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%d", val_s16); handler->prop_keys[handler->prop_count] = "Global Italic Angle"; strcpy(handler->prop_values[handler->prop_count++], buf); val16 = ntohs(*(uint16_t*)(data + offset)); offset += 2; snprintf(buf, sizeof(buf), "%u", val16); handler->prop_keys[handler->prop_count] = "Global Intellifont Data Size"; strcpy(handler->prop_values[handler->prop_count++], buf); // Variable fields omitted. } void print_properties(R8PHandler *handler) { for (int i = 0; i < handler->prop_count; i++) { printf("%s: %s\n", handler->prop_keys[i], handler->prop_values[i]); } } void write_r8p(R8PHandler *handler, const char *new_filename) { if (!handler->data) { fprintf(stderr, "No data to write\n"); return; } const char *fname = new_filename ? new_filename : handler->filename; FILE *f = fopen(fname, "wb"); if (!f) { perror("Failed to write file"); return; } fwrite(handler->data, 1, handler->data_size, f); fclose(f); } void destroy_r8p_handler(R8PHandler *handler) { free(handler->data); free(handler->filename); free(handler); } // Example usage: // int main() { // R8PHandler *handler = create_r8p_handler("example.r8p"); // read_r8p(handler); // print_properties(handler); // write_r8p(handler, "output.r8p"); // destroy_r8p_handler(handler); // return 0; // } // ===== end task-598 .R8P ===== // ===== task-599 .RAD [C++] ===== #include #include #include #include #include class RADFile { private: std::map properties; std::vector data; size_t offset = 0; public: RADFile(const std::string& filepath = "") { if (!filepath.empty()) { read(filepath); } } void read(const std::string& filepath) { std::ifstream file(filepath, std::ios::binary); if (file) { file.seekg(0, std::ios::end); data.resize(file.tellg()); file.seekg(0, std::ios::beg); file.read(data.data(), data.size()); parse(); } } void parse() { // Similar parsing logic as Python, using offset and data[offset++] // For example: std::string identifier(data.begin(), data.begin() + 16); offset += 16; properties["identifier"] = identifier; uint8_t version = static_cast(data[offset++]); properties["version"] = version; // Continue with flags, description, instruments, etc. // Implement bit extractions and loops as in other languages. } void printProperties() { // Use recursion or manual print to output properties. std::cout << "Properties:" << std::endl; // Example for identifier: std::cout << "Identifier: " << std::any_cast(properties["identifier"]) << std::endl; // Add for all. } void write(const std::string& filepath) { std::ofstream file(filepath, std::ios::binary); if (file) { std::vector output; // Pack properties into output vector. file.write(output.data(), output.size()); } } }; // ===== end task-599 .RAD ===== // ===== task-600 .RAL [C] ===== #include #include #include #include // For string extraction (may need -lregex) typedef struct { char* filepath; char* signature; char** extracted_strings; int string_count; // Placeholder for other properties char* track_positions; char* article_numbers; // Point to strings char* buildings; char* trees; char* roadbeds; char* other_objects; } RALFileHandler; RALFileHandler* createRALFileHandler(const char* filepath) { RALFileHandler* handler = (RALFileHandler*)malloc(sizeof(RALFileHandler)); handler->filepath = strdup(filepath); handler->signature = NULL; handler->extracted_strings = NULL; handler->string_count = 0; handler->track_positions = strdup("Not decodable without spec"); handler->buildings = strdup("Not decodable"); handler->trees = strdup("Not decodable"); handler->roadbeds = strdup("Not decodable"); handler->other_objects = strdup("Not decodable"); return handler; } void openAndDecode(RALFileHandler* handler) { FILE* f = fopen(handler->filepath, "rb"); if (!f) return; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); char* data = (char*)malloc(size + 1); fread(data, 1, size, f); data[size] = '\0'; fclose(f); // Signature handler->signature = (char*)malloc(5); strncpy(handler->signature, data, 4); handler->signature[4] = '\0'; // Extract strings (simple loop instead of regex for simplicity) // Note: For real regex, compile and match [a-zA-Z0-9\- ]{5,} // Here, dummy extraction of printable strings char* p = data; while (*p) { if (strspn(p, "a-zA-Z0-9- ") >= 5) { char* str = strdup(p); handler->extracted_strings = (char**)realloc(handler->extracted_strings, (handler->string_count + 1) * sizeof(char*)); handler->extracted_strings[handler->string_count++] = str; p += strlen(str); } else { p++; } } handler->article_numbers = "See extracted_strings"; free(data); } void printProperties(const RALFileHandler* handler) { printf("signature: %s\n", handler->signature); printf("extracted_strings: "); for (int i = 0; i < handler->string_count; i++) { printf("%s ", handler->extracted_strings[i]); } printf("\n"); printf("track_positions: %s\n", handler->track_positions); printf("article_numbers: %s\n", handler->article_numbers); printf("buildings: %s\n", handler->buildings); printf("trees: %s\n", handler->trees); printf("roadbeds: %s\n", handler->roadbeds); printf("other_objects: %s\n", handler->other_objects); } void write(RALFileHandler* handler, const char* newData) { // Dummy append FILE* f = fopen(handler->filepath, "ab"); if (f) { fwrite(newData, 1, strlen(newData), f); fclose(f); } printf("File written (appended dummy data).\n"); } void destroyRALFileHandler(RALFileHandler* handler) { free(handler->filepath); free(handler->signature); for (int i = 0; i < handler->string_count; i++) { free(handler->extracted_strings[i]); } free(handler->extracted_strings); free(handler->track_positions); free(handler->buildings); free(handler->trees); free(handler->roadbeds); free(handler->other_objects); free(handler); } // Example usage: // int main() { // RALFileHandler* handler = createRALFileHandler("example.ral"); // openAndDecode(handler); // printProperties(handler); // write(handler, "\x00\x00"); // destroyRALFileHandler(handler); // return 0; // } // ===== end task-600 .RAL ===== // ===== task-601 .RAM [C++] ===== #include #include #include #include #include #include class RAMFile { private: std::string filepath; std::map properties; std::vector urls; public: RAMFile(const std::string& fp) : filepath(fp) {} void openAndDecode() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "File " << filepath << " not found." << std::endl; return; } std::string line; while (std::getline(file, line)) { std::istringstream iss(line); std::string trimmed; std::getline(iss >> std::ws, trimmed); if (!trimmed.empty()) { size_t pos = trimmed.find('='); if (pos != std::string::npos) { std::string key = trimmed.substr(0, pos); std::string value = trimmed.substr(pos + 1); properties[key] = value; } else { urls.push_back(trimmed); } } } file.close(); std::cout << "Decoded .RAM file successfully." << std::endl; } void printProperties() { std::cout << "Properties:" << std::endl; for (const auto& pair : properties) { std::cout << "- " << pair.first << ": " << pair.second << std::endl; } for (size_t i = 0; i < urls.size(); ++i) { std::cout << "- Streaming URL " << (i + 1) << ": " << urls[i] << std::endl; } } void write(const std::string& newFilepath = "") { std::string path = newFilepath.empty() ? filepath : newFilepath; std::ofstream outFile(path); if (!outFile.is_open()) { std::cerr << "Could not write to " << path << "." << std::endl; return; } for (const auto& pair : properties) { outFile << pair.first << "=" << pair.second << "\n"; } for (const auto& url : urls) { outFile << url << "\n"; } outFile.close(); std::cout << "Written to " << path << "." << std::endl; } }; // Example usage: // int main() { // RAMFile ram("example.ram"); // ram.openAndDecode(); // ram.printProperties(); // ram.properties["title"] = "New Title"; // ram.write(); // return 0; // } // ===== end task-601 .RAM ===== // ===== task-602 .RAP [C] ===== #include #include #include typedef struct { unsigned char key[16]; } RapFile; void rap_read(RapFile *rap, const char *filepath) { FILE *f = fopen(filepath, "rb"); if (f == NULL) { perror("Error opening file"); exit(1); } size_t read = fread(rap->key, 1, 16, f); fclose(f); if (read != 16) { fprintf(stderr, "Invalid .RAP file. Must be 16 bytes.\n"); exit(1); } printf("Read .RAP file successfully.\n"); } void rap_decode(const RapFile *rap, char *hex) { hex[0] = '\0'; for (int i = 0; i < 16; i++) { char buf[3]; sprintf(buf, "%02X ", rap->key[i]); strcat(hex, buf); } hex[strlen(hex) - 1] = '\0'; // Remove trailing space } void rap_write(const char *filepath, const unsigned char *newKey) { FILE *f = fopen(filepath, "wb"); if (f == NULL) { perror("Error opening file"); exit(1); } size_t written = fwrite(newKey, 1, 16, f); fclose(f); if (written != 16) { fprintf(stderr, "Error writing file.\n"); exit(1); } printf("Wrote .RAP file successfully.\n"); } void rap_print_properties(const RapFile *rap) { char hex[48]; rap_decode(rap, hex); printf("License Key (hex): %s\n", hex); } int main() { RapFile rap; rap_read(&rap, "example.rap"); rap_print_properties(&rap); // To write unsigned char sampleKey[16] = {0}; rap_write("new.rap", sampleKey); return 0; } // ===== end task-602 .RAP ===== // ===== task-603 .RAR [C++] ===== #include #include #include #include #include #include #include class RarHandler { private: std::string filepath; std::map properties; // Simplified for print uint64_t readVint(std::ifstream& f) { uint64_t val = 0; int shift = 0; uint8_t byte; while (true) { f.read(reinterpret_cast(&byte), 1); val |= (static_cast(byte & 0x7F) << shift); shift += 7; if (!(byte & 0x80)) break; } return val; } public: RarHandler(const std::string& filepath) : filepath(filepath) {} void decodeReadPrint() { std::ifstream f(filepath, std::ios::binary); if (!f) { std::cerr << "File open error" << std::endl; return; } // Signature uint8_t sig[8]; f.read(reinterpret_cast(sig), 8); if (sig[0] != 0x52 || sig[1] != 0x61 || sig[2] != 0x72 || sig[3] != 0x21 || sig[4] != 0x1A || sig[5] != 0x07 || sig[6] != 0x01 || sig[7] != 0x00) { std::cerr << "Invalid RAR signature" << std::endl; return; } std::stringstream ss; for (int i = 0; i < 8; ++i) ss << std::hex << std::setw(2) << std::setfill('0') << static_cast(sig[i]); properties["signature"] = ss.str(); std::vector> headers; while (f) { std::map header; uint32_t crc32; f.read(reinterpret_cast(&crc32), 4); if (f.eof()) break; header["crc32"] = crc32; header["size"] = readVint(f); header["type"] = readVint(f); header["flags"] = readVint(f); if (header["flags"] & 0x0001) header["extra_size"] = readVint(f); if (header["flags"] & 0x0002) header["data_size"] = readVint(f); if (header["type"] == 1) { // Main header["archive_flags"] = readVint(f); if (header["archive_flags"] & 0x0002) header["volume_number"] = readVint(f); } else if (header["type"] == 2 || header["type"] == 3) { // File/Service header["file_flags"] = readVint(f); header["unpacked_size"] = readVint(f); header["attributes"] = readVint(f); if (header["file_flags"] & 0x0002) { uint32_t mtime; f.read(reinterpret_cast(&mtime), 4); header["mtime"] = mtime; } if (header["file_flags"] & 0x0004) { uint32_t crc; f.read(reinterpret_cast(&crc), 4); header["data_crc32"] = crc; } header["compression_info"] = readVint(f); header["host_os"] = readVint(f); uint64_t nameLen = readVint(f); std::vector name(nameLen + 1); f.read(name.data(), nameLen); name[nameLen] = '\0'; // Store name as string (simplified, not in map) std::cout << "Name: " << name.data() << std::endl; // Print separately } else if (header["type"] == 4) { // Encryption header["enc_version"] = readVint(f); header["enc_flags"] = readVint(f); uint8_t kdf; f.read(reinterpret_cast(&kdf), 1); header["kdf_count"] = kdf; uint8_t salt[16]; f.read(reinterpret_cast(salt), 16); // Hex print salt separately std::cout << "Salt: "; for (int i = 0; i < 16; ++i) std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast(salt[i]); std::cout << std::endl; if (header["enc_flags"] & 0x0001) { uint8_t check[12]; f.read(reinterpret_cast(check), 12); // Similar for check } } // Skip extra and data if (header.count("extra_size")) f.seekg(header["extra_size"], std::ios::cur); if (header.count("data_size")) f.seekg(header["data_size"], std::ios::cur); headers.push_back(header); } // Print properties std::cout << "Properties: " << std::endl; for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } std::cout << "Headers: " << std::endl; for (const auto& h : headers) { for (const auto& kv : h) { std::cout << kv.first << ": " << kv.second << std::endl; } std::cout << "---" << std::endl; } } void writeSimpleRar(const std::string& outputPath, const std::vector& fileContent, const std::string& fileName) { std::ofstream f(outputPath, std::ios::binary); if (!f) { std::cerr << "Write error" << std::endl; return; } const uint8_t sig[] = {0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x01, 0x00}; f.write(reinterpret_cast(sig), 8); // Dummy header uint32_t dummy = 0; f.write(reinterpret_cast(&dummy), 4); // Write content f.write(reinterpret_cast(fileContent.data()), fileContent.size()); std::cout << "Wrote simple RAR to " << outputPath << std::endl; } }; // Usage int main() { RarHandler handler("sample.rar"); handler.decodeReadPrint(); std::vector content = {'H', 'e', 'l', 'l', 'o', ' ', 'R', 'A', 'R'}; handler.writeSimpleRar("output.rar", content, "test.txt"); return 0; } // ===== end task-603 .RAR ===== // ===== task-604 .RAS [C] ===== #include #include #include #include // For big-endian conversion if needed struct RasHeader { uint32_t magic; uint32_t width; uint32_t height; uint32_t depth; uint32_t length; uint32_t type; uint32_t color_map_type; uint32_t color_map_length; }; int read_and_decode(const char* file_path, struct RasHeader* header) { FILE* file = fopen(file_path, "rb"); if (!file) { printf("File not found.\n"); return 0; } uint32_t raw_header[8]; if (fread(raw_header, sizeof(uint32_t), 8, file) < 8) { printf("File too small for header.\n"); fclose(file); return 0; } fclose(file); // Convert from big-endian to host header->magic = be32toh(raw_header[0]); if (header->magic != 0x59A66A95) { printf("Invalid .RAS file (wrong magic number).\n"); return 0; } header->width = be32toh(raw_header[1]); header->height = be32toh(raw_header[2]); header->depth = be32toh(raw_header[3]); header->length = be32toh(raw_header[4]); header->type = be32toh(raw_header[5]); header->color_map_type = be32toh(raw_header[6]); header->color_map_length = be32toh(raw_header[7]); print_properties(header); return 1; } void print_properties(const struct RasHeader* header) { printf("MagicNumber: 0x%08X\n", header->magic); printf("Width: %u\n", header->width); printf("Height: %u\n", header->height); printf("Depth: %u\n", header->depth); printf("Length: %u\n", header->length); printf("Type: %u\n", header->type); printf("ColorMapType: %u\n", header->color_map_type); printf("ColorMapLength: %u\n", header->color_map_length); } void write(const char* file_path, uint32_t width, uint32_t height, uint32_t depth, uint32_t type, uint32_t color_map_type, uint32_t color_map_length, const uint8_t* image_data, size_t data_size) { struct RasHeader header = { .magic = 0x59A66A95, .width = width, .height = height, .depth = depth, .length = (uint32_t)data_size, .type = type, .color_map_type = color_map_type, .color_map_length = color_map_length }; FILE* file = fopen(file_path, "wb"); if (!file) { printf("Error opening file for write.\n"); return; } // Convert to big-endian uint32_t raw_header[8] = { htobe32(header.magic), htobe32(header.width), htobe32(header.height), htobe32(header.depth), htobe32(header.length), htobe32(header.type), htobe32(header.color_map_type), htobe32(header.color_map_length) }; fwrite(raw_header, sizeof(uint32_t), 8, file); // Skip color map for simplicity if (image_data) { fwrite(image_data, 1, data_size, file); } fclose(file); printf("File written successfully.\n"); print_properties(&header); } // Example usage: // int main() { // struct RasHeader header; // read_and_decode("example.ras", &header); // uint8_t data[100*100] = {0}; // Simple 100x100 8-bit // write("output.ras", 100, 100, 8, 1, 0, 0, data, sizeof(data)); // return 0; // } // ===== end task-604 .RAS ===== // ===== task-605 .RB [C] ===== #include #include #include #include typedef struct { char name[33]; uint32_t length; uint32_t offset; uint32_t flag; } Entry; typedef struct { uint32_t magic; uint8_t version_major; uint8_t version_minor; char identifier[5]; uint16_t year; uint8_t month; uint8_t day; uint32_t toc_offset; uint32_t file_length; uint32_t num_entries; Entry* entries; } RBFile; RBFile* rb_open(const char* filepath) { FILE* f = fopen(filepath, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); RBFile* rb = malloc(sizeof(RBFile)); memcpy(&rb->magic, data, 4); rb->version_major = data[4]; rb->version_minor = data[5]; memcpy(rb->identifier, data + 6, 4); rb->identifier[4] = '\0'; memcpy(&rb->year, data + 14, 2); rb->month = data[16]; rb->day = data[17]; memcpy(&rb->toc_offset, data + 24, 4); memcpy(&rb->file_length, data + 28, 4); uint32_t toc = rb->toc_offset; memcpy(&rb->num_entries, data + toc, 4); rb->entries = malloc(rb->num_entries * sizeof(Entry)); uint32_t offset = toc + 4; for (uint32_t i = 0; i < rb->num_entries; i++) { memcpy(rb->entries[i].name, data + offset, 32); rb->entries[i].name[32] = '\0'; strrchr(rb->entries[i].name, '\0')[0] = '\0'; // Trim zeros offset += 32; memcpy(&rb->entries[i].length, data + offset, 4); offset += 4; memcpy(&rb->entries[i].offset, data + offset, 4); offset += 4; memcpy(&rb->entries[i].flag, data + offset, 4); offset += 4; } free(data); return rb; } void rb_print_properties(RBFile* rb) { printf("magic: %u\n", rb->magic); printf("version_major: %u\n", rb->version_major); printf("version_minor: %u\n", rb->version_minor); printf("identifier: %s\n", rb->identifier); printf("year: %u\n", rb->year); printf("month: %u\n", rb->month); printf("day: %u\n", rb->day); printf("toc_offset: %u\n", rb->toc_offset); printf("file_length: %u\n", rb->file_length); printf("num_entries: %u\n", rb->num_entries); for (uint32_t i = 0; i < rb->num_entries; i++) { printf("Entry %u: name=%s, length=%u, offset=%u, flag=%u\n", i + 1, rb->entries[i].name, rb->entries[i].length, rb->entries[i].offset, rb->entries[i].flag); } } void rb_write(RBFile* rb, const char* new_filepath, const char* original_filepath) { // Basic copy; full impl rebuilds FILE* src = fopen(original_filepath, "rb"); FILE* dst = fopen(new_filepath ? new_filepath : "example.rb.new", "wb"); uint8_t buf[4096]; size_t len; while ((len = fread(buf, 1, sizeof(buf), src)) > 0) { fwrite(buf, 1, len, dst); } fclose(src); fclose(dst); } void rb_close(RBFile* rb) { free(rb->entries); free(rb); } // Example usage // int main() { // RBFile* rb = rb_open("example.rb"); // rb_print_properties(rb); // rb_write(rb, NULL, "example.rb"); // rb_close(rb); // return 0; // } // ===== end task-605 .RB ===== // ===== task-606 .RBXL [C++] ===== #include #include #include #include #include #include // Placeholder for compression; use lz4/zstd libs in practice class RBXLHandler { private: std::string filepath; std::vector data; std::map properties; // Simplified as strings public: RBXLHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary); if (file) { data.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); decode(); } } void decode() { size_t offset = 0; // File Header std::string magic(reinterpret_cast(data.data() + offset), 8); properties["Magic Number"] = magic; offset += 8; std::string sig; for (size_t i = 0; i < 6; ++i) { sig += std::to_string(data[offset + i]) + " "; } properties["Signature"] = sig; offset += 6; uint16_t version = *reinterpret_cast(data.data() + offset); properties["Version"] = std::to_string(version); offset += 2; int32_t classCount = *reinterpret_cast(data.data() + offset); properties["Class Count"] = std::to_string(classCount); offset += 4; int32_t instanceCount = *reinterpret_cast(data.data() + offset); properties["Instance Count"] = std::to_string(instanceCount); offset += 4; properties["Reserved Header"] = "8 zeros"; offset += 8; // Chunks (basic) std::string chunksStr; while (offset < data.size()) { std::string chunkName(reinterpret_cast(data.data() + offset), 4); offset += 4; uint32_t compLen = *reinterpret_cast(data.data() + offset); offset += 4; uint32_t uncompLen = *reinterpret_cast(data.data() + offset); offset += 4; offset += 4; // reserved size_t dataSize = compLen ? compLen : uncompLen; offset += dataSize; chunksStr += "Chunk: " + chunkName + ", CompLen: " + std::to_string(compLen) + ", UncompLen: " + std::to_string(uncompLen) + "\n"; } properties["Chunks"] = chunksStr; } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& newFilepath) { std::ofstream out(newFilepath, std::ios::binary); out.write(reinterpret_cast(data.data()), data.size()); } }; // Usage: // RBXLHandler handler("example.rbxl"); // handler.read(); // handler.printProperties(); // handler.write("output.rbxl"); // ===== end task-606 .RBXL ===== // ===== task-607 .RC [C++] ===== #include #include #include #include #include #include #include class RCFileHandler { private: std::string filename; std::string content; std::vector> properties; void readAndDecode() { std::ifstream file(filename); if (!file.is_open()) { std::cerr << "Error opening file" << std::endl; return; } std::stringstream ss; ss << file.rdbuf(); content = ss.str(); file.close(); parse(); } void parse() { std::vector resourceTypes = {"ACCELERATORS", "BITMAP", "CURSOR", "DIALOG", "DIALOGEX", "FONT", "HTML", "ICON", "MENU", "MENUEX", "MESSAGETABLE", "POPUP", "PLUGPLAY", "RCDATA", "STRINGTABLE", "TEXTINCLUDE", "TYPELIB", "VERSIONINFO", "VXD"}; std::stringstream ss(content); std::string line; bool inBlock = false; std::map currentProp; std::string params; while (std::getline(ss, line)) { line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); if (line.empty() || line.rfind("//", 0) == 0 || line.rfind("#", 0) == 0) continue; std::stringstream wordStream(line); std::string firstWord; wordStream >> firstWord; std::transform(firstWord.begin(), firstWord.end(), firstWord.begin(), ::toupper); if (std::find(resourceTypes.begin(), resourceTypes.end(), firstWord) != resourceTypes.end()) { if (!currentProp.empty()) { currentProp["params"] = params; properties.push_back(currentProp); currentProp.clear(); params.clear(); } std::string name, temp; wordStream >> name; while (wordStream >> temp) params += temp + " "; currentProp["type"] = firstWord; currentProp["name"] = name; if (line.find("BEGIN") != std::string::npos || line.find("begin") != std::string::npos) inBlock = true; } else if (inBlock) { if (line.find("END") != std::string::npos || line.find("end") != std::string::npos) { inBlock = false; } else { params += line + "\n"; } } } if (!currentProp.empty()) { currentProp["params"] = params; properties.push_back(currentProp); } } public: RCFileHandler(const std::string& fn) : filename(fn) { readAndDecode(); } void printProperties() { for (const auto& prop : properties) { std::cout << "Type: " << prop.at("type") << ", Name: " << prop.at("name") << ", Params: " << prop.at("params") << std::endl; } } void write(const std::string& newFilename) { std::ofstream outFile(newFilename); if (outFile.is_open()) { outFile << content; outFile.close(); } else { std::cerr << "Error writing file" << std::endl; } } }; // Example usage: // int main() { // RCFileHandler handler("example.rc"); // handler.printProperties(); // handler.write("output.rc"); // return 0; // } // ===== end task-607 .RC ===== // ===== task-608 .RDP [C] ===== #include #include #include #define MAX_PROPERTIES 100 #define MAX_KEY_LEN 100 #define MAX_VALUE_LEN 256 typedef struct { char key[MAX_KEY_LEN]; char type; // 'i' or 's' union { int i_val; char s_val[MAX_VALUE_LEN]; } value; } Property; typedef struct { Property properties[MAX_PROPERTIES]; int count; } RdpFile; void init_rdp(RdpFile *rdp) { rdp->count = 0; } void read_rdp(RdpFile *rdp, const char *filepath) { FILE *f = fopen(filepath, "r"); if (!f) { perror("Failed to open file"); return; } char line[512]; while (fgets(line, sizeof(line), f)) { line[strcspn(line, "\n")] = 0; // Strip newline char *parts[3]; char *token = strtok(line, ":"); int i = 0; while (token && i < 3) { parts[i++] = token; token = strtok(NULL, ":"); } if (i == 3) { strncpy(rdp->properties[rdp->count].key, parts[0], MAX_KEY_LEN); rdp->properties[rdp->count].type = parts[1][0]; if (rdp->properties[rdp->count].type == 'i') { rdp->properties[rdp->count].value.i_val = atoi(parts[2]); } else { strncpy(rdp->properties[rdp->count].value.s_val, parts[2], MAX_VALUE_LEN); } rdp->count++; } } fclose(f); } void write_rdp(const RdpFile *rdp, const char *filepath) { FILE *f = fopen(filepath, "w"); if (!f) { perror("Failed to open file"); return; } for (int i = 0; i < rdp->count; i++) { if (rdp->properties[i].type == 'i') { fprintf(f, "%s:%c:%d\n", rdp->properties[i].key, rdp->properties[i].type, rdp->properties[i].value.i_val); } else { fprintf(f, "%s:%c:%s\n", rdp->properties[i].key, rdp->properties[i].type, rdp->properties[i].value.s_val); } } fclose(f); } void print_properties(const RdpFile *rdp) { for (int i = 0; i < rdp->count; i++) { if (rdp->properties[i].type == 'i') { printf("%s: %d\n", rdp->properties[i].key, rdp->properties[i].value.i_val); } else { printf("%s: %s\n", rdp->properties[i].key, rdp->properties[i].value.s_val); } } } // Example usage: // int main() { // RdpFile rdp; // init_rdp(&rdp); // read_rdp(&rdp, "sample.rdp"); // print_properties(&rdp); // write_rdp(&rdp, "output.rdp"); // return 0; // } // ===== end task-608 .RDP ===== // ===== task-609 .RDS [C++] ===== #include #include #include #include #include #include #include #include // For byte swap if needed class RDSHandler { private: std::string filepath; char format; int32_t version; std::string writerVersion; std::string minReaderVersion; std::string nativeEncoding; std::string decodeVersion(int32_t packed) { int major = packed >> 16; int minor = (packed >> 8) & 0xFF; int patch = packed & 0xFF; return std::to_string(major) + "." + std::to_string(minor) + "." + std::to_string(patch); } public: RDSHandler(const std::string& fp) : filepath(fp), format(0), version(0) {} void readAndDecode() { std::ifstream file(filepath, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file"); } file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(reinterpret_cast(data.data()), size); // Check gzip bool isGzip = (data[0] == 0x1F && data[1] == 0x8B); if (isGzip) { z_stream stream; stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; stream.avail_in = size; stream.next_in = data.data(); if (inflateInit2(&stream, 16 + MAX_WBITS) != Z_OK) { // gzip mode throw std::runtime_error("inflateInit failed"); } std::vector decompressed(1024 * 1024); // Assume max size stream.avail_out = decompressed.size(); stream.next_out = decompressed.data(); int ret = inflate(&stream, Z_NO_FLUSH); if (ret != Z_STREAM_END) { inflateEnd(&stream); throw std::runtime_error("Decompression failed"); } size = decompressed.size() - stream.avail_out; data.assign(decompressed.begin(), decompressed.begin() + size); inflateEnd(&stream); } size_t offset = 0; format = static_cast(data[offset++]); if (data[offset++] != 0x0A) { throw std::runtime_error("Invalid RDS format"); } bool isAscii = format == 'A'; bool isBigEndian = format == 'X'; if (isAscii) { std::string text(reinterpret_cast(data.data() + offset), size - offset); std::vector lines; size_t pos = 0; while ((pos = text.find('\n')) != std::string::npos) { std::string line = text.substr(0, pos); if (!line.empty()) lines.push_back(line); text.erase(0, pos + 1); } if (!text.empty()) lines.push_back(text); version = std::stoi(lines[0]); int32_t writerPacked = std::stoi(lines[1]); int32_t minPacked = std::stoi(lines[2]); writerVersion = decodeVersion(writerPacked); minReaderVersion = decodeVersion(minPacked); if (version >= 3) { int encLen = std::stoi(lines[3]); nativeEncoding = lines[4].substr(0, encLen); } else { nativeEncoding = "N/A"; } } else { auto readInt32 = [&](size_t& off) -> int32_t { int32_t val; std::memcpy(&val, data.data() + off, 4); off += 4; if (!isBigEndian) { val = le32toh(val); // Assume host is little, convert if needed } else { val = be32toh(val); } return val; }; version = readInt32(offset); int32_t writerPacked = readInt32(offset); int32_t minPacked = readInt32(offset); writerVersion = decodeVersion(writerPacked); minReaderVersion = decodeVersion(minPacked); if (version >= 3) { int32_t encLen = readInt32(offset); nativeEncoding.assign(reinterpret_cast(data.data() + offset), encLen); offset += encLen; } else { nativeEncoding = "N/A"; } } } void printProperties() { std::cout << "Format: " << format << std::endl; std::cout << "Version: " << version << std::endl; std::cout << "Writer R Version: " << writerVersion << std::endl; std::cout << "Minimum Reader R Version: " << minReaderVersion << std::endl; std::cout << "Native Encoding: " << nativeEncoding << std::endl; } void writeSimpleRds(const std::string& outputPath, bool compress = true) { std::vector header; header.push_back('X'); header.push_back(0x0A); auto addInt32 = [&](int32_t val) { uint32_t beVal = htobe32(val); // Big-endian header.insert(header.end(), reinterpret_cast(&beVal), reinterpret_cast(&beVal) + 4); }; addInt32(3); // version addInt32(262402); // R 4.1.2 addInt32(197888); // Min 3.5.0 std::string enc = "UTF-8"; addInt32(static_cast(enc.length())); header.insert(header.end(), enc.begin(), enc.end()); // Simple INTSXP addInt32(13); addInt32(2); // length addInt32(1); addInt32(2); std::vector data = header; if (compress) { uLongf destLen = compressBound(data.size()); std::vector compressed(destLen); if (compress2(compressed.data(), &destLen, data.data(), data.size(), Z_DEFAULT_COMPRESSION) != Z_OK) { throw std::runtime_error("Compression failed"); } data.assign(compressed.begin(), compressed.begin() + destLen); } std::ofstream out(outputPath, std::ios::binary); out.write(reinterpret_cast(data.data()), data.size()); } }; // Example usage: // int main() { // try { // RDSHandler handler("path/to/file.rds"); // handler.readAndDecode(); // handler.printProperties(); // handler.writeSimpleRds("output.rds"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-609 .RDS ===== // ===== task-610 .RES [C] ===== #include #include #include #include typedef struct { uint32_t dataSize; uint32_t headerSize; char *type; char *name; uint32_t dataVersion; uint16_t memoryFlags; uint16_t languageId; uint32_t version; uint32_t characteristics; uint8_t *data; } Resource; typedef struct { Resource *resources; size_t count; } RESFile; char *read_unicode_or_id(FILE *f, long *pos) { uint16_t first; fread(&first, sizeof(uint16_t), 1, f); *pos += sizeof(uint16_t); if (first == 0xFFFF) { uint16_t id; fread(&id, sizeof(uint16_t), 1, f); *pos += sizeof(uint16_t); char *str = malloc(11); sprintf(str, "%u", id); return str; } else { fseek(f, -sizeof(uint16_t), SEEK_CUR); *pos -= sizeof(uint16_t); char *str = malloc(256); // Max size size_t len = 0; while (true) { uint16_t charCode; fread(&charCode, sizeof(uint16_t), 1, f); *pos += sizeof(uint16_t); if (charCode == 0) break; str[len++] = (char) charCode; // Simplification, assuming ASCII range } str[len] = '\0'; return str; } } void align_to_4(FILE *f, long *pos) { int pad = (4 - (*pos % 4)) % 4; fseek(f, pad, SEEK_CUR); *pos += pad; } RESFile *res_file_open(const char *filename) { RESFile *res = malloc(sizeof(RESFile)); res->resources = NULL; res->count = 0; FILE *f = fopen(filename, "rb"); if (!f) return NULL; long pos = 0; while (!feof(f)) { res->resources = realloc(res->resources, sizeof(Resource) * (res->count + 1)); Resource *r = &res->resources[res->count]; fread(&r->dataSize, sizeof(uint32_t), 1, f); pos += sizeof(uint32_t); fread(&r->headerSize, sizeof(uint32_t), 1, f); pos += sizeof(uint32_t); r->type = read_unicode_or_id(f, &pos); align_to_4(f, &pos); r->name = read_unicode_or_id(f, &pos); align_to_4(f, &pos); fread(&r->dataVersion, sizeof(uint32_t), 1, f); pos += sizeof(uint32_t); fread(&r->memoryFlags, sizeof(uint16_t), 1, f); pos += sizeof(uint16_t); fread(&r->languageId, sizeof(uint16_t), 1, f); pos += sizeof(uint16_t); fread(&r->version, sizeof(uint32_t), 1, f); pos += sizeof(uint32_t); fread(&r->characteristics, sizeof(uint32_t), 1, f); pos += sizeof(uint32_t); r->data = malloc(r->dataSize); fread(r->data, 1, r->dataSize, f); pos += r->dataSize; align_to_4(f, &pos); res->count++; } fclose(f); return res; } void res_file_print_properties(RESFile *res) { for (size_t i = 0; i < res->count; i++) { Resource *r = &res->resources[i]; printf("Resource %zu:\n", i); printf("dataSize: %u\n", r->dataSize); printf("headerSize: %u\n", r->headerSize); printf("type: %s\n", r->type); printf("name: %s\n", r->name); printf("dataVersion: %u\n", r->dataVersion); printf("memoryFlags: %u\n", r->memoryFlags); printf("languageId: %u\n", r->languageId); printf("version: %u\n", r->version); printf("characteristics: %u\n", r->characteristics); printf("\n"); } } void write_unicode_or_id(FILE *f, const char *value, long *pos) { if (strspn(value, "0123456789") == strlen(value)) { uint16_t prefix = 0xFFFF; fwrite(&prefix, sizeof(uint16_t), 1, f); *pos += sizeof(uint16_t); uint16_t id = atoi(value); fwrite(&id, sizeof(uint16_t), 1, f); *pos += sizeof(uint16_t); } else { for (size_t i = 0; i < strlen(value); i++) { uint16_t charCode = (uint16_t) value[i]; fwrite(&charCode, sizeof(uint16_t), 1, f); *pos += sizeof(uint16_t); } uint16_t zero = 0; fwrite(&zero, sizeof(uint16_t), 1, f); *pos += sizeof(uint16_t); } } void align_to_4_write(FILE *f, long *pos) { int pad = (4 - (*pos % 4)) % 4; for (int i = 0; i < pad; i++) { uint8_t zero = 0; fwrite(&zero, 1, 1, f); } *pos += pad; } void res_file_write(RESFile *res, const char *filename) { FILE *f = fopen(filename, "wb"); if (!f) return; long pos = 0; for (size_t i = 0; i < res->count; i++) { Resource *r = &res->resources[i]; long start_pos = pos; fwrite(&r->dataSize, sizeof(uint32_t), 1, f); pos += sizeof(uint32_t); uint32_t placeholder = 0; fwrite(&placeholder, sizeof(uint32_t), 1, f); pos += sizeof(uint32_t); write_unicode_or_id(f, r->type, &pos); align_to_4_write(f, &pos); write_unicode_or_id(f, r->name, &pos); align_to_4_write(f, &pos); fwrite(&r->dataVersion, sizeof(uint32_t), 1, f); pos += sizeof(uint32_t); fwrite(&r->memoryFlags, sizeof(uint16_t), 1, f); pos += sizeof(uint16_t); fwrite(&r->languageId, sizeof(uint16_t), 1, f); pos += sizeof(uint16_t); fwrite(&r->version, sizeof(uint32_t), 1, f); pos += sizeof(uint32_t); fwrite(&r->characteristics, sizeof(uint32_t), 1, f); pos += sizeof(uint32_t); long long header_size = pos - start_pos; fseek(f, start_pos + 4, SEEK_SET); fwrite(&header_size, sizeof(uint32_t), 1, f); fseek(f, pos, SEEK_SET); fwrite(r->data, 1, r->dataSize, f); pos += r->dataSize; align_to_4_write(f, &pos); } fclose(f); } void res_file_close(RESFile *res) { for (size_t i = 0; i < res->count; i++) { free(res->resources[i].type); free(res->resources[i].name); free(res->resources[i].data); } free(res->resources); free(res); } // Example usage // RESFile *res = res_file_open("sample.res"); // res_file_print_properties(res); // res_file_write(res, "output.res"); // res_file_close(res); // ===== end task-610 .RES ===== // ===== task-611 .REX [C] ===== #include #include #include typedef struct { char magic[5]; uint16_t version; uint32_t sample_rate; uint8_t channels; uint8_t bit_depth; uint32_t num_slices; float tempo; uint32_t length_beats; uint32_t *slice_points; } REXFile; REXFile* rex_open(const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) return NULL; REXFile* rex = malloc(sizeof(REXFile)); fread(rex->magic, 1, 4, f); rex->magic[4] = '\0'; fread(&rex->version, sizeof(uint16_t), 1, f); fread(&rex->sample_rate, sizeof(uint32_t), 1, f); fread(&rex->channels, sizeof(uint8_t), 1, f); fread(&rex->bit_depth, sizeof(uint8_t), 1, f); fread(&rex->num_slices, sizeof(uint32_t), 1, f); fread(&rex->tempo, sizeof(float), 1, f); fread(&rex->length_beats, sizeof(uint32_t), 1, f); rex->slice_points = malloc(rex->num_slices * sizeof(uint32_t)); fread(rex->slice_points, sizeof(uint32_t), rex->num_slices, f); fclose(f); return rex; } void rex_print(REXFile* rex) { printf("Magic: %s\n", rex->magic); printf("Version: %u\n", rex->version); printf("Sample Rate: %u Hz\n", rex->sample_rate); printf("Channels: %u\n", rex->channels); printf("Bit Depth: %u\n", rex->bit_depth); printf("Number of Slices: %u\n", rex->num_slices); printf("Original Tempo: %.2f BPM\n", rex->tempo); printf("Length in Beats: %u\n", rex->length_beats); printf("Slice Points: "); for (uint32_t i = 0; i < rex->num_slices; i++) { printf("%u ", rex->slice_points[i]); } printf("\n"); } void rex_write(REXFile* rex, const char* new_filename) { FILE* f = fopen(new_filename, "wb"); if (!f) return; fwrite(rex->magic, 1, 4, f); fwrite(&rex->version, sizeof(uint16_t), 1, f); fwrite(&rex->sample_rate, sizeof(uint32_t), 1, f); fwrite(&rex->channels, sizeof(uint8_t), 1, f); fwrite(&rex->bit_depth, sizeof(uint8_t), 1, f); fwrite(&rex->num_slices, sizeof(uint32_t), 1, f); fwrite(&rex->tempo, sizeof(float), 1, f); fwrite(&rex->length_beats, sizeof(uint32_t), 1, f); fwrite(rex->slice_points, sizeof(uint32_t), rex->num_slices, f); fclose(f); } void rex_close(REXFile* rex) { free(rex->slice_points); free(rex); } // Example usage // int main() { // REXFile* rex = rex_open("sample.rex"); // if (rex) { // rex_print(rex); // rex->tempo = 140.0f; // rex_write(rex, "modified.rex"); // rex_close(rex); // } // return 0; // } // ===== end task-611 .REX ===== // ===== task-612 .REXX [C] ===== #include #include #include #include typedef struct { char* filepath; char* extension; char* mime_type; char* encoding; char* line_endings; bool has_signature; char* content; char* structure; } RexxFileHandler; RexxFileHandler* create_rexx_handler(const char* filepath) { RexxFileHandler* handler = malloc(sizeof(RexxFileHandler)); handler->filepath = strdup(filepath); handler->extension = ".rexx"; handler->mime_type = "text/x-rexx"; handler->encoding = "UTF-8"; // Assumed handler->line_endings = NULL; handler->has_signature = false; handler->content = NULL; handler->structure = "REXX source code text"; return handler; } void read_and_decode(RexxFileHandler* handler) { FILE* file = fopen(handler->filepath, "rb"); if (!file) { perror("Error opening file"); return; } fseek(file, 0, SEEK_END); long size = ftell(file); fseek(file, 0, SEEK_SET); handler->content = malloc(size + 1); fread(handler->content, 1, size, file); handler->content[size] = '\0'; fclose(file); // Find first line char* first_line_end = strstr(handler->content, "\n"); if (!first_line_end) first_line_end = strstr(handler->content, "\r"); char first_line[1024]; if (first_line_end) { strncpy(first_line, handler->content, first_line_end - handler->content); first_line[first_line_end - handler->content] = '\0'; } else { strcpy(first_line, handler->content); } // Check signature char upper_first[1024]; strcpy(upper_first, first_line); for (int i = 0; upper_first[i]; i++) upper_first[i] = toupper(upper_first[i]); handler->has_signature = strncmp(first_line, "/*", 2) == 0 && strstr(upper_first, "REXX") != NULL; // Detect line endings if (strstr(handler->content, "\r\n")) { handler->line_endings = "CRLF"; } else if (strstr(handler->content, "\r")) { handler->line_endings = "CR"; } else { handler->line_endings = "LF"; } } void print_properties(RexxFileHandler* handler) { printf("File Extension: %s\n", handler->extension); printf("MIME Type: %s\n", handler->mime_type); printf("Encoding: %s\n", handler->encoding); printf("Line Endings: %s\n", handler->line_endings); printf("Signature Valid: %s\n", handler->has_signature ? "Yes" : "No"); printf("Content Structure: %s\n", handler->structure); printf("Full Content:\n%s\n", handler->content); } void write_rexx(RexxFileHandler* handler, const char* new_content, bool add_signature_if_missing) { char* content_to_write = strdup(new_content); if (add_signature_if_missing && strncmp(new_content, "/*", 2) != 0) { char* temp = malloc(strlen(new_content) + 12); sprintf(temp, "/* REXX */\n%s", new_content); free(content_to_write); content_to_write = temp; } FILE* file = fopen(handler->filepath, "w"); if (!file) { perror("Error writing file"); free(content_to_write); return; } fprintf(file, "%s", content_to_write); fclose(file); free(content_to_write); } void destroy_rexx_handler(RexxFileHandler* handler) { free(handler->filepath); free(handler->content); free(handler); } // Example usage: // int main() { // RexxFileHandler* handler = create_rexx_handler("example.rexx"); // read_and_decode(handler); // print_properties(handler); // write_rexx(handler, "say \"Hello World\"", true); // destroy_rexx_handler(handler); // return 0; // } // ===== end task-612 .REXX ===== // ===== task-613 .RKT [C++] ===== #include #include #include #include #include #include // Assume Mini-XML library for parsing class RKTFileHandler { private: std::string filename; mxml_node_t* tree; mxml_node_t* root; public: RKTFileHandler(const std::string& fn) : filename(fn), tree(nullptr), root(nullptr) {} ~RKTFileHandler() { if (tree) mxmlDelete(tree); } void openAndDecode() { FILE* fp = fopen(filename.c_str(), "r"); if (!fp) { throw std::runtime_error("File not found."); } tree = mxmlLoadFile(fp, MXML_TEXT_CALLBACK); fclose(fp); if (!tree) { throw std::runtime_error("Error parsing XML."); } root = mxmlFindElement(tree, tree, "RockSimDocument", NULL, NULL, MXML_DESCEND); if (!root) { throw std::runtime_error("Invalid RKT file."); } } std::map readProperties() { if (!root) { throw std::runtime_error("File not opened or decoded."); } std::map properties; // File Version mxml_node_t* version = mxmlFindElement(root, root, "FileVersion", NULL, NULL, MXML_DESCEND_FIRST); properties["FileVersion"] = version ? std::string(mxmlGetText(version, NULL)) : std::string("Unknown"); // Design Information mxml_node_t* designInfo = mxmlFindElement(root, root, "DesignInformation", NULL, NULL, MXML_DESCEND_FIRST); if (designInfo) { properties["DesignInformation"] = extractChildMap(designInfo); } // Rocket Design mxml_node_t* rocketDesign = mxmlFindElement(root, root, "RocketDesign", NULL, NULL, MXML_DESCEND_FIRST); if (rocketDesign) { properties["RocketDesign"] = extractParts(rocketDesign); } // Simulation Results List mxml_node_t* simList = mxmlFindElement(root, root, "SimulationResultsList", NULL, NULL, MXML_DESCEND_FIRST); if (simList) { std::vector> sims; mxml_node_t* sim = mxmlFindElement(simList, simList, "SimulationResult", NULL, NULL, MXML_DESCEND); while (sim) { sims.push_back(extractChildMap(sim)); sim = mxmlFindElement(sim, simList, "SimulationResult", NULL, NULL, MXML_NO_DESCEND); } properties["SimulationResultsList"] = sims; } return properties; } std::map extractChildMap(mxml_node_t* node) { std::map map; mxml_node_t* child = mxmlGetFirstChild(node); while (child) { if (mxmlGetType(child) == MXML_ELEMENT) { map[mxmlGetElement(child)] = std::string(mxmlGetText(child, NULL)); } child = mxmlGetNextSibling(child); } return map; } std::map>> extractParts(mxml_node_t* node) { std::map>> parts; mxml_node_t* child = mxmlGetFirstChild(node); while (child) { if (mxmlGetType(child) == MXML_ELEMENT) { std::string tag = mxmlGetElement(child); std::map partData; // Attributes (Mini-XML attr access) const char* attr_name; for (int i = 0; (attr_name = mxmlElementGetAttrByIndex(child, i, NULL)); ++i) { partData[attr_name] = std::string(mxmlElementGetAttr(child, attr_name)); } partData["text"] = std::string(mxmlGetText(child, NULL)); // Subchildren mxml_node_t* sub = mxmlGetFirstChild(child); while (sub) { if (mxmlGetType(sub) == MXML_ELEMENT) { partData[mxmlGetElement(sub)] = std::string(mxmlGetText(sub, NULL)); } sub = mxmlGetNextSibling(sub); } parts[tag].push_back(partData); } child = mxmlGetNextSibling(child); } return parts; } void printProperties() { auto props = readProperties(); std::cout << "RKT Properties:" << std::endl; // Printing is simplified; use recursion or loops for nested maps for (const auto& [key, value] : props) { std::cout << key << ": [complex value]" << std::endl; // Expand as needed } } void write(const std::string& newFilename = "") { if (!tree) { throw std::runtime_error("No data to write."); } std::string outFile = newFilename.empty() ? filename : newFilename; FILE* fp = fopen(outFile.c_str(), "w"); if (!fp) { throw std::runtime_error("Cannot write file."); } mxmlSaveFile(tree, fp, MXML_NO_CALLBACK); fclose(fp); } }; // Example usage: // int main() { // try { // RKTFileHandler handler("example.rkt"); // handler.openAndDecode(); // handler.printProperties(); // handler.write("modified.rkt"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-613 .RKT ===== // ===== task-614 .RM [C++] ===== #include #include #include #include #include #include #include #include // For big-endian on little-endian systems class RMParser { private: std::string filename; std::map>> properties; // Flexible for lists uint32_t readDword(std::ifstream& f) { uint32_t val; f.read(reinterpret_cast(&val), 4); #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ return __bswap_32(val); #else return val; #endif } uint16_t readWord(std::ifstream& f) { uint16_t val; f.read(reinterpret_cast(&val), 2); #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ return __bswap_16(val); #else return val; #endif } uint8_t readByte(std::ifstream& f) { uint8_t val; f.read(reinterpret_cast(&val), 1); return val; } std::string readString(std::ifstream& f, size_t length) { std::string str(length, '\0'); f.read(&str[0], length); return str; } struct Chunk { std::string type; uint32_t size; uint16_t version; }; Chunk parseChunk(std::ifstream& f) { char type[5] = {0}; f.read(type, 4); Chunk chunk; chunk.type = type; chunk.size = readDword(f); chunk.version = readWord(f); return chunk; } void parseRMF(std::ifstream& f) { uint32_t fileVersion = readDword(f); uint32_t numHeaders = readDword(f); std::map rmfProps; rmfProps["File Version"] = std::to_string(fileVersion); rmfProps["Number of Headers"] = std::to_string(numHeaders); properties["RMF"].push_back(rmfProps); } void parsePROP(std::ifstream& f) { uint32_t maxBitrate = readDword(f); uint32_t avgBitrate = readDword(f); uint32_t maxPacketSize = readDword(f); uint32_t avgPacketSize = readDword(f); uint32_t numPackets = readDword(f); uint32_t duration = readDword(f); uint32_t preroll = readDword(f); uint32_t indxOffset = readDword(f); uint32_t dataOffset = readDword(f); uint16_t numStreams = readWord(f); uint16_t flags = readWord(f); std::map propProps; propProps["Max Bitrate"] = std::to_string(maxBitrate); propProps["Avg Bitrate"] = std::to_string(avgBitrate); propProps["Max Packet Size"] = std::to_string(maxPacketSize); propProps["Avg Packet Size"] = std::to_string(avgPacketSize); propProps["Num Packets"] = std::to_string(numPackets); propProps["Duration (ms)"] = std::to_string(duration); propProps["Preroll (ms)"] = std::to_string(preroll); propProps["INDX Offset"] = std::to_string(indxOffset); propProps["DATA Offset"] = std::to_string(dataOffset); propProps["Num Streams"] = std::to_string(numStreams); propProps["Flags"] = std::to_string(flags); properties["PROP"].push_back(propProps); } void parseMDPR(std::ifstream& f) { uint16_t streamNum = readWord(f); uint32_t maxBitrate = readDword(f); uint32_t avgBitrate = readDword(f); uint32_t maxPacketSize = readDword(f); uint32_t avgPacketSize = readDword(f); uint32_t startOffset = readDword(f); uint32_t preroll = readDword(f); uint32_t duration = readDword(f); uint8_t descLen = readByte(f); std::string desc = readString(f, descLen); uint8_t mimeLen = readByte(f); std::string mime = readString(f, mimeLen); uint32_t typeSize = readDword(f); f.seekg(typeSize, std::ios::cur); std::map streamProps; streamProps["Stream Num"] = std::to_string(streamNum); streamProps["Max Bitrate"] = std::to_string(maxBitrate); streamProps["Avg Bitrate"] = std::to_string(avgBitrate); streamProps["Max Packet Size"] = std::to_string(maxPacketSize); streamProps["Avg Packet Size"] = std::to_string(avgPacketSize); streamProps["Start Offset (ms)"] = std::to_string(startOffset); streamProps["Preroll (ms)"] = std::to_string(preroll); streamProps["Duration (ms)"] = std::to_string(duration); streamProps["Description"] = desc; streamProps["Mime Type"] = mime; streamProps["Type-Specific Size"] = std::to_string(typeSize); properties["MDPR"].push_back(streamProps); } void parseCONT(std::ifstream& f) { uint16_t titleLen = readWord(f); std::string title = readString(f, titleLen); uint16_t authorLen = readWord(f); std::string author = readString(f, authorLen); uint16_t copyrightLen = readWord(f); std::string copyright = readString(f, copyrightLen); uint16_t commentLen = readWord(f); std::string comment = readString(f, commentLen); std::map contProps; contProps["Title"] = title; contProps["Author"] = author; contProps["Copyright"] = copyright; contProps["Comment"] = comment; properties["CONT"].push_back(contProps); } public: void read() { std::ifstream f(filename, std::ios::binary); if (!f) return; while (f) { Chunk chunk = parseChunk(f); if (chunk.type == ".RMF" || chunk.type == ".RMP") { parseRMF(f); } else if (chunk.type == "PROP") { parsePROP(f); } else if (chunk.type == "MDPR") { parseMDPR(f); } else if (chunk.type == "CONT") { parseCONT(f); } else { f.seekg(chunk.size - 10, std::ios::cur); } } f.close(); } void printProperties() { for (const auto& [chunk, propList] : properties) { std::cout << chunk << ":" << std::endl; for (size_t i = 0; i < propList.size(); ++i) { if (propList.size() > 1) std::cout << " Stream " << i << ":" << std::endl; for (const auto& [key, val] : propList[i]) { std::cout << " " << key << ": " << val << std::endl; } } } } void write(const std::string& outputFilename) { std::ofstream out(outputFilename, std::ios::binary); if (!out) return; // Write .RMF if (properties.count("RMF")) { auto& rmf = properties["RMF"][0]; out.write(".RMF", 4); uint32_t size = 18; out.write(reinterpret_cast(&size), 4); // No bswap for write, assume LE and adjust if needed uint16_t ver = 0; out.write(reinterpret_cast(&ver), 2); uint32_t fileVer = std::stoul(rmf.at("File Version")); out.write(reinterpret_cast(&fileVer), 4); uint32_t numHdrs = std::stoul(rmf.at("Number of Headers")); out.write(reinterpret_cast(&numHdrs), 4); } // Write PROP if (properties.count("PROP")) { auto& p = properties["PROP"][0]; out.write("PROP", 4); uint32_t size = 50; out.write(reinterpret_cast(&size), 4); uint16_t ver = 0; out.write(reinterpret_cast(&ver), 2); uint32_t val = std::stoul(p.at("Max Bitrate")); out.write(reinterpret_cast(&val), 4); val = std::stoul(p.at("Avg Bitrate")); out.write(reinterpret_cast(&val), 4); val = std::stoul(p.at("Max Packet Size")); out.write(reinterpret_cast(&val), 4); val = std::stoul(p.at("Avg Packet Size")); out.write(reinterpret_cast(&val), 4); val = std::stoul(p.at("Num Packets")); out.write(reinterpret_cast(&val), 4); val = std::stoul(p.at("Duration (ms)")); out.write(reinterpret_cast(&val), 4); val = std::stoul(p.at("Preroll (ms)")); out.write(reinterpret_cast(&val), 4); val = std::stoul(p.at("INDX Offset")); out.write(reinterpret_cast(&val), 4); val = std::stoul(p.at("DATA Offset")); out.write(reinterpret_cast(&val), 4); uint16_t sVal = std::stoul(p.at("Num Streams")); out.write(reinterpret_cast(&sVal), 2); sVal = std::stoul(p.at("Flags")); out.write(reinterpret_cast(&sVal), 2); } // Write MDPR(s) if (properties.count("MDPR")) { for (const auto& stream : properties["MDPR"]) { std::string desc = stream.at("Description"); std::string mime = stream.at("Mime Type"); uint32_t typeSize = std::stoul(stream.at("Type-Specific Size")); uint32_t mdprSize = 38 + desc.size() + mime.size() + typeSize + 10; out.write("MDPR", 4); out.write(reinterpret_cast(&mdprSize), 4); uint16_t ver = 0; out.write(reinterpret_cast(&ver), 2); uint16_t sNum = std::stoul(stream.at("Stream Num")); out.write(reinterpret_cast(&sNum), 2); uint32_t val = std::stoul(stream.at("Max Bitrate")); out.write(reinterpret_cast(&val), 4); val = std::stoul(stream.at("Avg Bitrate")); out.write(reinterpret_cast(&val), 4); val = std::stoul(stream.at("Max Packet Size")); out.write(reinterpret_cast(&val), 4); val = std::stoul(stream.at("Avg Packet Size")); out.write(reinterpret_cast(&val), 4); val = std::stoul(stream.at("Start Offset (ms)")); out.write(reinterpret_cast(&val), 4); val = std::stoul(stream.at("Preroll (ms)")); out.write(reinterpret_cast(&val), 4); val = std::stoul(stream.at("Duration (ms)")); out.write(reinterpret_cast(&val), 4); uint8_t len = desc.size(); out.write(reinterpret_cast(&len), 1); out.write(desc.c_str(), desc.size()); len = mime.size(); out.write(reinterpret_cast(&len), 1); out.write(mime.c_str(), mime.size()); out.write(reinterpret_cast(&typeSize), 4); // Placeholder for (uint32_t i = 0; i < typeSize; ++i) out.put(0); } } // Write CONT if (properties.count("CONT")) { auto& c = properties["CONT"][0]; std::string title = c.at("Title"); std::string author = c.at("Author"); std::string copyright = c.at("Copyright"); std::string comment = c.at("Comment"); uint32_t contSize = 10 + 8 + title.size() + author.size() + copyright.size() + comment.size(); out.write("CONT", 4); out.write(reinterpret_cast(&contSize), 4); uint16_t ver = 0; out.write(reinterpret_cast(&ver), 2); uint16_t len = title.size(); out.write(reinterpret_cast(&len), 2); out.write(title.c_str(), title.size()); len = author.size(); out.write(reinterpret_cast(&len), 2); out.write(author.c_str(), author.size()); len = copyright.size(); out.write(reinterpret_cast(&len), 2); out.write(copyright.c_str(), copyright.size()); len = comment.size(); out.write(reinterpret_cast(&len), 2); out.write(comment.c_str(), comment.size()); } out.close(); } }; int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "Usage: " << argv[0] << " input.rm [output.rm]" << std::endl; return 1; } RMParser parser(argv[1]); parser.read(); parser.printProperties(); if (argc > 2) { parser.write(argv[2]); } return 0; } // ===== end task-614 .RM ===== // ===== task-615 .RMD [C++] ===== #include #include #include #include #include class RMDHandler { private: std::string filepath; std::map properties; std::string content; std::string yamlHeader; public: RMDHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "File " << filepath << " not found." << std::endl; return; } std::string line; content = ""; while (std::getline(file, line)) { content += line + "\n"; } file.close(); std::regex yamlRegex(R"(---\s*([\s\S]*?)\s*---)"); std::smatch match; if (std::regex_search(content, match, yamlRegex) && match.size() > 1) { yamlHeader = match[1].str(); // Simple parsing: assume key: value lines std::istringstream iss(yamlHeader); while (std::getline(iss, line)) { size_t colonPos = line.find(':'); if (colonPos != std::string::npos) { std::string key = line.substr(0, colonPos); std::string value = line.substr(colonPos + 1); // Trim spaces key.erase(0, key.find_first_not_of(" \t")); key.erase(key.find_last_not_of(" \t") + 1); value.erase(0, value.find_first_not_of(" \t")); value.erase(value.find_last_not_of(" \t") + 1); properties[key] = value; } } } else { std::cout << "No YAML header found." << std::endl; } } void printProperties() { if (properties.empty()) { std::cout << "No properties loaded." << std::endl; return; } for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::map& newProperties) { for (const auto& pair : newProperties) { properties[pair.first] = pair.second; } std::string newYaml = ""; for (const auto& pair : properties) { newYaml += pair.first + ": " + pair.second + "\n"; } std::regex replaceRegex(R"(---\s*[\s\S]*?\s*---)"); std::string newContent = std::regex_replace(content, replaceRegex, "---\n" + newYaml + "---"); std::ofstream outFile(filepath); if (outFile.is_open()) { outFile << newContent; outFile.close(); std::cout << "File written to " << filepath << std::endl; } else { std::cerr << "Unable to write file." << std::endl; } } }; // Example usage: // int main() { // RMDHandler handler("sample.Rmd"); // handler.read(); // handler.printProperties(); // std::map newProps = {{"new_key", "new_value"}}; // handler.write(newProps); // return 0; // } // ===== end task-615 .RMD ===== // ===== task-616 .RMVB [C++] ===== #include #include #include #include #include #include #include class RMVBFile { private: std::string filepath; std::map properties; // Simplified to string for print std::vector> dataChunks; std::vector> otherChunks; uint32_t readDWord(std::ifstream& f) { uint32_t val; f.read(reinterpret_cast(&val), 4); return __builtin_bswap32(val); // Big-endian } uint16_t readWord(std::ifstream& f) { uint16_t val; f.read(reinterpret_cast(&val), 2); return __builtin_bswap16(val); } uint8_t readByte(std::ifstream& f) { uint8_t val; f.read(reinterpret_cast(&val), 1); return val; } std::string readString(std::ifstream& f, int len) { std::vector buf(len); f.read(buf.data(), len); return std::string(buf.begin(), buf.end()); } std::string readBinary(std::ifstream& f, int len) { std::vector buf(len); f.read(buf.data(), len); std::stringstream ss; for (char c : buf) ss << std::hex << std::setw(2) << std::setfill('0') << (int)(unsigned char)c << " "; return ss.str(); } public: RMVBFile(const std::string& filepath) : filepath(filepath) {} void decode() { std::ifstream f(filepath, std::ios::binary); if (!f) return; while (f) { char type[5] = {0}; f.read(type, 4); if (f.eof()) break; uint32_t size = readDWord(f); uint16_t version = readWord(f); if (std::strcmp(type, ".RMF") == 0) { properties["file_version"] = std::to_string(readDWord(f)); properties["num_headers"] = std::to_string(readDWord(f)); } else if (std::strcmp(type, "PROP") == 0) { properties["max_bit_rate"] = std::to_string(readDWord(f)); properties["avg_bit_rate"] = std::to_string(readDWord(f)); properties["max_packet_size"] = std::to_string(readDWord(f)); properties["avg_packet_size"] = std::to_string(readDWord(f)); properties["num_packets"] = std::to_string(readDWord(f)); properties["duration"] = std::to_string(readDWord(f)); properties["preroll"] = std::to_string(readDWord(f)); properties["index_offset"] = std::to_string(readDWord(f)); properties["data_offset"] = std::to_string(readDWord(f)); properties["num_streams"] = std::to_string(readWord(f)); uint16_t flags = readWord(f); properties["flags"] = std::to_string(flags); properties["save_allowed"] = std::to_string((flags & 1) != 0); properties["perfect_play"] = std::to_string((flags & 2) != 0); properties["live_broadcast"] = std::to_string((flags & 4) != 0); } else if (std::strcmp(type, "CONT") == 0) { properties["title"] = readString(f, readWord(f)); properties["author"] = readString(f, readWord(f)); properties["copyright"] = readString(f, readWord(f)); properties["comment"] = readString(f, readWord(f)); } else if (std::strcmp(type, "MDPR") == 0) { uint16_t streamNum = readWord(f); std::string streamKey = "stream_" + std::to_string(streamNum) + "_"; properties[streamKey + "max_bit_rate"] = std::to_string(readDWord(f)); properties[streamKey + "avg_bit_rate"] = std::to_string(readDWord(f)); properties[streamKey + "max_packet_size"] = std::to_string(readDWord(f)); properties[streamKey + "avg_packet_size"] = std::to_string(readDWord(f)); properties[streamKey + "start_time"] = std::to_string(readDWord(f)); properties[streamKey + "preroll"] = std::to_string(readDWord(f)); properties[streamKey + "duration"] = std::to_string(readDWord(f)); properties[streamKey + "stream_name"] = readString(f, readByte(f)); properties[streamKey + "mime_type"] = readString(f, readByte(f)); uint32_t tsLen = readDWord(f); properties[streamKey + "type_specific_data"] = readBinary(f, tsLen); } else if (std::strcmp(type, "DATA") == 0) { std::streampos pos = f.tellg(); f.seekg(pos - 10); std::vector chunk(size); f.read(chunk.data(), size); dataChunks.push_back(chunk); } else { std::streampos pos = f.tellg(); f.seekg(pos - 10); std::vector chunk(size); f.read(chunk.data(), size); otherChunks.push_back(chunk); } } } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& newFilepath) { std::ofstream f(newFilepath, std::ios::binary); if (!f) return; // Write .RMF f.write(".RMF", 4); uint32_t sz = __builtin_bswap32(18); f.write(reinterpret_cast(&sz), 4); uint16_t ver = __builtin_bswap16(0); f.write(reinterpret_cast(&ver), 2); uint32_t fv = __builtin_bswap32(std::stoul(properties["file_version"])); f.write(reinterpret_cast(&fv), 4); uint32_t nh = __builtin_bswap32(std::stoul(properties["num_headers"])); f.write(reinterpret_cast(&nh), 4); // Write PROP f.write("PROP", 4); sz = __builtin_bswap32(50); f.write(reinterpret_cast(&sz), 4); ver = __builtin_bswap16(0); f.write(reinterpret_cast(&ver), 2); uint32_t mbr = __builtin_bswap32(std::stoul(properties["max_bit_rate"])); f.write(reinterpret_cast(&mbr), 4); uint32_t abr = __builtin_bswap32(std::stoul(properties["avg_bit_rate"])); f.write(reinterpret_cast(&abr), 4); uint32_t mps = __builtin_bswap32(std::stoul(properties["max_packet_size"])); f.write(reinterpret_cast(&mps), 4); uint32_t aps = __builtin_bswap32(std::stoul(properties["avg_packet_size"])); f.write(reinterpret_cast(&aps), 4); uint32_t np = __builtin_bswap32(std::stoul(properties["num_packets"])); f.write(reinterpret_cast(&np), 4); uint32_t dur = __builtin_bswap32(std::stoul(properties["duration"])); f.write(reinterpret_cast(&dur), 4); uint32_t pr = __builtin_bswap32(std::stoul(properties["preroll"])); f.write(reinterpret_cast(&pr), 4); uint32_t io = __builtin_bswap32(std::stoul(properties["index_offset"])); f.write(reinterpret_cast(&io), 4); uint32_t doff = __builtin_bswap32(std::stoul(properties["data_offset"])); f.write(reinterpret_cast(&doff), 4); uint16_t ns = __builtin_bswap16(std::stoul(properties["num_streams"])); f.write(reinterpret_cast(&ns), 2); uint16_t fl = __builtin_bswap16(std::stoul(properties["flags"])); f.write(reinterpret_cast(&fl), 2); // Write CONT if present if (properties.count("title")) { std::string title = properties["title"]; std::string author = properties["author"]; std::string copyright = properties["copyright"]; std::string comment = properties["comment"]; uint32_t contSize = 10 + 8 + title.size() + author.size() + copyright.size() + comment.size(); f.write("CONT", 4); contSize = __builtin_bswap32(contSize); f.write(reinterpret_cast(&contSize), 4); ver = __builtin_bswap16(0); f.write(reinterpret_cast(&ver), 2); uint16_t tl = __builtin_bswap16(title.size()); f.write(reinterpret_cast(&tl), 2); f.write(title.c_str(), title.size()); uint16_t al = __builtin_bswap16(author.size()); f.write(reinterpret_cast(&al), 2); f.write(author.c_str(), author.size()); uint16_t cl = __builtin_bswap16(copyright.size()); f.write(reinterpret_cast(&cl), 2); f.write(copyright.c_str(), copyright.size()); uint16_t cm = __builtin_bswap16(comment.size()); f.write(reinterpret_cast(&cm), 2); f.write(comment.c_str(), comment.size()); } // Write MDPR (scan for streams) for (auto it = properties.begin(); it != properties.end(); ++it) { if (it->first.find("stream_") == 0 && it->first.find("max_bit_rate") != std::string::npos) { size_t pos = it->first.find('_'); size_t pos2 = it->first.find('_', pos + 1); std::string streamNumStr = it->first.substr(pos + 1, pos2 - pos - 1); std::string streamKey = "stream_" + streamNumStr + "_"; std::string name = properties[streamKey + "stream_name"]; std::string mime = properties[streamKey + "mime_type"]; std::string tsHex = properties[streamKey + "type_specific_data"]; std::vector tsData; std::stringstream ss(tsHex); std::string byteStr; while (ss >> byteStr) { tsData.push_back(static_cast(std::stoi(byteStr, nullptr, 16))); } uint32_t mdprSize = 10 + 38 + 1 + name.size() + 1 + mime.size() + 4 + tsData.size(); f.write("MDPR", 4); mdprSize = __builtin_bswap32(mdprSize); f.write(reinterpret_cast(&mdprSize), 4); ver = __builtin_bswap16(0); f.write(reinterpret_cast(&ver), 2); uint16_t sn = __builtin_bswap16(std::stoi(streamNumStr)); f.write(reinterpret_cast(&sn), 2); uint32_t mbr = __builtin_bswap32(std::stoi(properties[streamKey + "max_bit_rate"])); f.write(reinterpret_cast(&mbr), 4); uint32_t abr = __builtin_bswap32(std::stoi(properties[streamKey + "avg_bit_rate"])); f.write(reinterpret_cast(&abr), 4); uint32_t mps = __builtin_bswap32(std::stoi(properties[streamKey + "max_packet_size"])); f.write(reinterpret_cast(&mps), 4); uint32_t aps = __builtin_bswap32(std::stoi(properties[streamKey + "avg_packet_size"])); f.write(reinterpret_cast(&aps), 4); uint32_t st = __builtin_bswap32(std::stoi(properties[streamKey + "start_time"])); f.write(reinterpret_cast(&st), 4); uint32_t pr = __builtin_bswap32(std::stoi(properties[streamKey + "preroll"])); f.write(reinterpret_cast(&pr), 4); uint32_t dur = __builtin_bswap32(std::stoi(properties[streamKey + "duration"])); f.write(reinterpret_cast(&dur), 4); uint8_t nl = name.size(); f.write(reinterpret_cast(&nl), 1); f.write(name.c_str(), name.size()); uint8_t ml = mime.size(); f.write(reinterpret_cast(&ml), 1); f.write(mime.c_str(), mime.size()); uint32_t tsl = __builtin_bswap32(tsData.size()); f.write(reinterpret_cast(&tsl), 4); f.write(tsData.data(), tsData.size()); } } // Write other chunks for (const auto& chunk : otherChunks) { f.write(chunk.data(), chunk.size()); } // Write data chunks for (const auto& chunk : dataChunks) { f.write(chunk.data(), chunk.size()); } } }; // Example usage // int main() { // RMVBFile rmvb("sample.rmvb"); // rmvb.decode(); // rmvb.printProperties(); // rmvb.properties["duration"] = "100000"; // rmvb.write("modified.rmvb"); // return 0; // } // ===== end task-616 .RMVB ===== // ===== task-617 .ROB [C] ===== #include #include #include #include #define MAX_LINE 4096 #define MAX_KEYS 100 #define MAX_VALUES 1000 typedef struct { char *key; char **values; int value_count; } Property; typedef struct { Property properties[MAX_KEYS]; int prop_count; } RobFile; void init_rob_file(RobFile *rob) { rob->prop_count = 0; } void free_rob_file(RobFile *rob) { for (int i = 0; i < rob->prop_count; i++) { free(rob->properties[i].key); for (int j = 0; j < rob->properties[i].value_count; j++) { free(rob->properties[i].values[j]); } free(rob->properties[i].values); } } int load_rob_file(RobFile *rob, const char *filename) { FILE *fp = fopen(filename, "r"); if (!fp) return -1; char line[MAX_LINE]; char current_line[MAX_LINE] = {0}; while (fgets(line, MAX_LINE, fp)) { char *trimmed = line; while (isspace(*trimmed)) trimmed++; if (*trimmed == '#' || *trimmed == '\0') continue; size_t len = strlen(trimmed); if (trimmed[len - 1] == '\n') trimmed[--len] = '\0'; if (trimmed[len - 1] == '\\') { trimmed[len - 1] = ' '; strcat(current_line, trimmed); continue; } strcat(current_line, trimmed); // Parse parts char *parts[MAX_VALUES]; int part_count = 0; char *p = current_line; while (*p) { while (isspace(*p)) p++; if (!*p) break; if (*p == '"') { p++; char *start = p; while (*p && *p != '"') p++; if (*p) p++; int plen = p - start - 1; parts[part_count] = malloc(plen + 1); strncpy(parts[part_count++], start, plen); parts[part_count - 1][plen] = '\0'; } else { char *start = p; while (*p && !isspace(*p)) p++; int plen = p - start; parts[part_count] = malloc(plen + 1); strncpy(parts[part_count++], start, plen); parts[part_count - 1][plen] = '\0'; } } if (part_count > 0) { Property *prop = &rob->properties[rob->prop_count++]; prop->key = parts[0]; prop->values = malloc((part_count - 1) * sizeof(char*)); prop->value_count = part_count - 1; for (int i = 1; i < part_count; i++) { prop->values[i - 1] = parts[i]; } } current_line[0] = '\0'; } fclose(fp); return 0; } void print_rob_properties(const RobFile *rob) { printf("{\n"); for (int i = 0; i < rob->prop_count; i++) { const Property *prop = &rob->properties[i]; printf(" \"%s\": [", prop->key); for (int j = 0; j < prop->value_count; j++) { printf("\"%s\"", prop->values[j]); if (j < prop->value_count - 1) printf(", "); } printf("]"); if (i < rob->prop_count - 1) printf(",\n"); else printf("\n"); } printf("}\n"); } int write_rob_file(const RobFile *rob, const char *filename) { FILE *fp = fopen(filename, "w"); if (!fp) return -1; for (int i = 0; i < rob->prop_count; i++) { const Property *prop = &rob->properties[i]; fprintf(fp, "%s", prop->key); for (int j = 0; j < prop->value_count; j++) { if (strchr(prop->values[j], ' ')) { fprintf(fp, " \"%s\"", prop->values[j]); } else { fprintf(fp, " %s", prop->values[j]); } } fprintf(fp, "\n"); } fclose(fp); return 0; } // Example usage: // int main() { // RobFile rob; // init_rob_file(&rob); // if (load_rob_file(&rob, "example.rob") == 0) { // print_rob_properties(&rob); // write_rob_file(&rob, "output.rob"); // } // free_rob_file(&rob); // return 0; // } // ===== end task-617 .ROB ===== // ===== task-618 .ROL [C++] ===== #include #include #include #include #include #include struct TempoEvent { uint16_t atTick; float multiplier; }; struct NoteEvent { uint16_t note; uint16_t duration; }; struct TimbreEvent { uint16_t atTick; char instName[10]; // null-terminated uint8_t filler; uint16_t unknown; }; struct VolumeEvent { uint16_t atTick; float volume; }; struct PitchEvent { uint16_t atTick; float pitch; }; struct Voice { char voice_trackName[16]; // null-terminated uint16_t nTicks; std::vector noteEvents; char timbre_trackName[16]; std::vector timbreEvents; char volume_trackName[16]; std::vector volumeEvents; char pitch_trackName[16]; std::vector pitchEvents; }; class ROLFile { public: uint16_t majorVersion = 0; uint16_t minorVersion = 4; char signature[41] = "\\roll\\default"; // null-terminated uint16_t tickBeat = 120; uint16_t beatMeasure = 4; uint16_t scaleY = 0; uint16_t scaleX = 0; uint8_t reserved = 0; uint8_t isMelodic = 1; uint16_t counters[45] = {0}; uint8_t filler[38] = {0}; // Tempo char tempo_trackName[16] = " Tempo"; float basicTempo = 120.0f; std::vector tempoEvents; // Voices Voice voices[11]; ROLFile(const std::string& filename = "") { for (int i = 0; i < 11; ++i) { sprintf(voices[i].voice_trackName, " Voix %02d", i); voices[i].nTicks = 0; sprintf(voices[i].timbre_trackName, " Timbre %02d", i); sprintf(voices[i].volume_trackName, " Volume %02d", i); sprintf(voices[i].pitch_trackName, " Pitch %02d", i); } if (!filename.empty()) { read(filename); } } void read(const std::string& filename) { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) return; size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(reinterpret_cast(data.data()), size); size_t offset = 0; majorVersion = *reinterpret_cast(&data[offset]); offset += 2; minorVersion = *reinterpret_cast(&data[offset]); offset += 2; memcpy(signature, &data[offset], 40); signature[40] = '\0'; offset += 40; tickBeat = *reinterpret_cast(&data[offset]); offset += 2; beatMeasure = *reinterpret_cast(&data[offset]); offset += 2; scaleY = *reinterpret_cast(&data[offset]); offset += 2; scaleX = *reinterpret_cast(&data[offset]); offset += 2; reserved = data[offset++]; isMelodic = data[offset++]; for (int i = 0; i < 45; ++i) { counters[i] = *reinterpret_cast(&data[offset]); offset += 2; } memcpy(filler, &data[offset], 38); offset += 38; // Tempo memcpy(tempo_trackName, &data[offset], 15); tempo_trackName[15] = '\0'; offset += 15; basicTempo = *reinterpret_cast(&data[offset]); offset += 4; uint16_t nTempo = *reinterpret_cast(&data[offset]); offset += 2; tempoEvents.clear(); for (uint16_t i = 0; i < nTempo; ++i) { TempoEvent evt; evt.atTick = *reinterpret_cast(&data[offset]); offset += 2; evt.multiplier = *reinterpret_cast(&data[offset]); offset += 4; tempoEvents.push_back(evt); } // Voices for (int v = 0; v < 11; ++v) { // Voice memcpy(voices[v].voice_trackName, &data[offset], 15); voices[v].voice_trackName[15] = '\0'; offset += 15; voices[v].nTicks = *reinterpret_cast(&data[offset]); offset += 2; voices[v].noteEvents.clear(); uint32_t sumDur = 0; while (sumDur < voices[v].nTicks && offset < size) { NoteEvent evt; evt.note = *reinterpret_cast(&data[offset]); offset += 2; evt.duration = *reinterpret_cast(&data[offset]); offset += 2; voices[v].noteEvents.push_back(evt); sumDur += evt.duration; if (sumDur >= voices[v].nTicks) break; } // Timbre memcpy(voices[v].timbre_trackName, &data[offset], 15); voices[v].timbre_trackName[15] = '\0'; offset += 15; uint16_t nTim = *reinterpret_cast(&data[offset]); offset += 2; voices[v].timbreEvents.clear(); for (uint16_t i = 0; i < nTim; ++i) { TimbreEvent evt; evt.atTick = *reinterpret_cast(&data[offset]); offset += 2; memcpy(evt.instName, &data[offset], 9); evt.instName[9] = '\0'; offset += 9; evt.filler = data[offset++]; evt.unknown = *reinterpret_cast(&data[offset]); offset += 2; voices[v].timbreEvents.push_back(evt); } // Volume memcpy(voices[v].volume_trackName, &data[offset], 15); voices[v].volume_trackName[15] = '\0'; offset += 15; uint16_t nVol = *reinterpret_cast(&data[offset]); offset += 2; voices[v].volumeEvents.clear(); for (uint16_t i = 0; i < nVol; ++i) { VolumeEvent evt; evt.atTick = *reinterpret_cast(&data[offset]); offset += 2; evt.volume = *reinterpret_cast(&data[offset]); offset += 4; voices[v].volumeEvents.push_back(evt); } // Pitch memcpy(voices[v].pitch_trackName, &data[offset], 15); voices[v].pitch_trackName[15] = '\0'; offset += 15; uint16_t nPitch = *reinterpret_cast(&data[offset]); offset += 2; voices[v].pitchEvents.clear(); for (uint16_t i = 0; i < nPitch; ++i) { PitchEvent evt; evt.atTick = *reinterpret_cast(&data[offset]); offset += 2; evt.pitch = *reinterpret_cast(&data[offset]); offset += 4; voices[v].pitchEvents.push_back(evt); } } // Update counters counters[44] = tempoEvents.size(); for (int i = 0; i < 11; ++i) { counters[i] = voices[i].nTicks; counters[11 + i] = voices[i].timbreEvents.size(); counters[22 + i] = voices[i].volumeEvents.size(); counters[33 + i] = voices[i].pitchEvents.size(); } } void printProperties() const { std::cout << "Header:" << std::endl; std::cout << "majorVersion: " << majorVersion << std::endl; std::cout << "minorVersion: " << minorVersion << std::endl; std::cout << "signature: " << signature << std::endl; std::cout << "tickBeat: " << tickBeat << std::endl; std::cout << "beatMeasure: " << beatMeasure << std::endl; std::cout << "scaleY: " << scaleY << std::endl; std::cout << "scaleX: " << scaleX << std::endl; std::cout << "reserved: " << static_cast(reserved) << std::endl; std::cout << "isMelodic: " << static_cast(isMelodic) << std::endl; std::cout << "counters: ["; for (int i = 0; i < 45; ++i) { std::cout << counters[i] << (i < 44 ? ", " : ""); } std::cout << "]" << std::endl; std::cout << "filler: (38 bytes of padding)" << std::endl; std::cout << "\nTempo Track:" << std::endl; std::cout << "trackName: " << tempo_trackName << std::endl; std::cout << "basicTempo: " << basicTempo << std::endl; std::cout << "nEvents: " << tempoEvents.size() << std::endl; std::cout << "tempoEvents:" << std::endl; for (const auto& evt : tempoEvents) { std::cout << " - atTick: " << evt.atTick << ", multiplier: " << evt.multiplier << std::endl; } for (int i = 0; i < 11; ++i) { std::cout << "\nVoice Track " << i << ":" << std::endl; std::cout << "trackName: " << voices[i].voice_trackName << std::endl; std::cout << "nTicks: " << voices[i].nTicks << std::endl; std::cout << "noteEvents:" << std::endl; for (const auto& evt : voices[i].noteEvents) { std::cout << " - note: " << evt.note << ", duration: " << evt.duration << std::endl; } std::cout << "\nTimbre Track " << i << ":" << std::endl; std::cout << "trackName: " << voices[i].timbre_trackName << std::endl; std::cout << "nEvents: " << voices[i].timbreEvents.size() << std::endl; std::cout << "timbreEvents:" << std::endl; for (const auto& evt : voices[i].timbreEvents) { std::cout << " - atTick: " << evt.atTick << ", instName: " << evt.instName << ", filler: " << static_cast(evt.filler) << ", unknown: " << evt.unknown << std::endl; } std::cout << "\nVolume Track " << i << ":" << std::endl; std::cout << "trackName: " << voices[i].volume_trackName << std::endl; std::cout << "nEvents: " << voices[i].volumeEvents.size() << std::endl; std::cout << "volumeEvents:" << std::endl; for (const auto& evt : voices[i].volumeEvents) { std::cout << " - atTick: " << evt.atTick << ", volume: " << evt.volume << std::endl; } std::cout << "\nPitch Track " << i << ":" << std::endl; std::cout << "trackName: " << voices[i].pitch_trackName << std::endl; std::cout << "nEvents: " << voices[i].pitchEvents.size() << std::endl; std::cout << "pitchEvents:" << std::endl; for (const auto& evt : voices[i].pitchEvents) { std::cout << " - atTick: " << evt.atTick << ", pitch: " << evt.pitch << std::endl; } } } void write(const std::string& filename) const { std::ofstream file(filename, std::ios::binary); if (!file) return; // Header file.write(reinterpret_cast(&majorVersion), 2); file.write(reinterpret_cast(&minorVersion), 2); char sigPadded[40]; memset(sigPadded, 0, 40); strcpy(sigPadded, signature); file.write(sigPadded, 40); file.write(reinterpret_cast(&tickBeat), 2); file.write(reinterpret_cast(&beatMeasure), 2); file.write(reinterpret_cast(&scaleY), 2); file.write(reinterpret_cast(&scaleX), 2); file.write(reinterpret_cast(&reserved), 1); file.write(reinterpret_cast(&isMelodic), 1); for (int i = 0; i < 45; ++i) { file.write(reinterpret_cast(&counters[i]), 2); } file.write(reinterpret_cast(filler), 38); // Tempo char namePadded[15]; memset(namePadded, 0, 15); strcpy(namePadded, tempo_trackName); file.write(namePadded, 15); file.write(reinterpret_cast(&basicTempo), 4); uint16_t nTempo = tempoEvents.size(); file.write(reinterpret_cast(&nTempo), 2); for (const auto& evt : tempoEvents) { file.write(reinterpret_cast(&evt.atTick), 2); file.write(reinterpret_cast(&evt.multiplier), 4); } // Voices for (int v = 0; v < 11; ++v) { // Voice memset(namePadded, 0, 15); strcpy(namePadded, voices[v].voice_trackName); file.write(namePadded, 15); file.write(reinterpret_cast(&voices[v].nTicks), 2); for (const auto& evt : voices[v].noteEvents) { file.write(reinterpret_cast(&evt.note), 2); file.write(reinterpret_cast(&evt.duration), 2); } // Timbre memset(namePadded, 0, 15); strcpy(namePadded, voices[v].timbre_trackName); file.write(namePadded, 15); uint16_t nTim = voices[v].timbreEvents.size(); file.write(reinterpret_cast(&nTim), 2); for (const auto& evt : voices[v].timbreEvents) { file.write(reinterpret_cast(&evt.atTick), 2); char instPadded[9]; memset(instPadded, 0, 9); strcpy(instPadded, evt.instName); file.write(instPadded, 9); file.write(reinterpret_cast(&evt.filler), 1); file.write(reinterpret_cast(&evt.unknown), 2); } // Volume memset(namePadded, 0, 15); strcpy(namePadded, voices[v].volume_trackName); file.write(namePadded, 15); uint16_t nVol = voices[v].volumeEvents.size(); file.write(reinterpret_cast(&nVol), 2); for (const auto& evt : voices[v].volumeEvents) { file.write(reinterpret_cast(&evt.atTick), 2); file.write(reinterpret_cast(&evt.volume), 4); } // Pitch memset(namePadded, 0, 15); strcpy(namePadded, voices[v].pitch_trackName); file.write(namePadded, 15); uint16_t nPitch = voices[v].pitchEvents.size(); file.write(reinterpret_cast(&nPitch), 2); for (const auto& evt : voices[v].pitchEvents) { file.write(reinterpret_cast(&evt.atTick), 2); file.write(reinterpret_cast(&evt.pitch), 4); } } } }; // ===== end task-618 .ROL ===== // ===== task-619 .RPM [C] ===== #include #include #include #include #include // For beXXtoh typedef struct { uint32_t magic; uint8_t major; uint8_t minor; uint16_t type; uint16_t archnum; char name[66]; uint16_t osnum; uint16_t signature_type; uint8_t reserved[16]; } Lead; typedef struct { uint32_t magic; // 24-bit uint8_t version; uint8_t reserved[4]; uint32_t index_count; uint32_t store_size; // Dynamic: indexes (tag/type/offset/count) and data // For simplicity, print during parse } HeaderSection; void print_properties(const char* filepath) { FILE* fp = fopen(filepath, "rb"); if (!fp) { perror("fopen"); return; } // Parse Lead Lead lead; fread(&lead.magic, 4, 1, fp); lead.magic = be32toh(lead.magic); fread(&lead.major, 1, 1, fp); fread(&lead.minor, 1, 1, fp); fread(&lead.type, 2, 1, fp); lead.type = be16toh(lead.type); fread(&lead.archnum, 2, 1, fp); lead.archnum = be16toh(lead.archnum); fread(lead.name, 66, 1, fp); fread(&lead.osnum, 2, 1, fp); lead.osnum = be16toh(lead.osnum); fread(&lead.signature_type, 2, 1, fp); lead.signature_type = be16toh(lead.signature_type); fread(lead.reserved, 16, 1, fp); printf("Lead Section:\n"); printf(" Magic: 0x%X\n", lead.magic); printf(" Version: %u.%u\n", lead.major, lead.minor); printf(" Type: %u\n", lead.type); printf(" Archnum: %u\n", lead.archnum); printf(" Name: %s\n", lead.name); printf(" Osnum: %u\n", lead.osnum); printf(" Signature Type: %u\n", lead.signature_type); // Parse Header (Signature and Header) auto parse_header = [](FILE* fp, const char* section_name) { uint32_t magic; fread(&magic, 4, 1, fp); magic = be32toh(magic) >> 8; uint8_t version; fread(&version, 1, 1, fp); uint8_t reserved[4]; fread(reserved, 4, 1, fp); uint32_t index_count; fread(&index_count, 4, 1, fp); index_count = be32toh(index_count); uint32_t store_size; fread(&store_size, 4, 1, fp); store_size = be32toh(store_size); printf("\n%s Section:\n", section_name); printf(" Magic: 0x%X\n", magic); printf(" Version: %u\n", version); printf(" Index Count: %u\n", index_count); printf(" Store Size: %u\n", store_size); // Indexes (dynamic alloc omitted; read and print) for (uint32_t i = 0; i < index_count; i++) { uint32_t tag, type, off, count; fread(&tag, 4, 1, fp); tag = be32toh(tag); fread(&type, 4, 1, fp); type = be32toh(type); fread(&off, 4, 1, fp); off = be32toh(off); fread(&count, 4, 1, fp); count = be32toh(count); printf(" Entry %u: Tag=%u, Type=%u, Offset=%u, Count=%u\n", i, tag, type, off, count); } // Store data parsing omitted for brevity (seek and read based on type) fseek(fp, store_size, SEEK_CUR); long cur = ftell(fp); while (cur % 8 != 0) { fseek(fp, 1, SEEK_CUR); cur++; } }; parse_header(fp, "Signature"); parse_header(fp, "Header"); // Payload not printed fclose(fp); } void write_rpm(const char* filepath, const char* new_filepath) { // Placeholder: copy after print print_properties(filepath); FILE* in = fopen(filepath, "rb"); FILE* out = fopen(new_filepath, "wb"); char buf[4096]; size_t n; while ((n = fread(buf, 1, sizeof(buf), in)) > 0) { fwrite(buf, 1, n, out); } fclose(in); fclose(out); } int main() { print_properties("example.rpm"); write_rpm("example.rpm", "modified.rpm"); return 0; } // ===== end task-619 .RPM ===== // ===== task-620 .RS [C] ===== #include #include #include #include // For htonl/ntohl (big-endian conversion) #define MAGIC 0x59a66a95 #define HEADER_SIZE 32 typedef struct { uint32_t magic; uint32_t width; uint32_t height; uint32_t depth; uint32_t length; uint32_t type; uint32_t map_type; uint32_t map_length; uint8_t *color_map; uint8_t *image_data; } RSFile; RSFile* rsfile_create(const char *filepath) { RSFile *rs = malloc(sizeof(RSFile)); if (rs == NULL) return NULL; rs->color_map = NULL; rs->image_data = NULL; // Read immediately or separately; here we leave for read function return rs; } void rsfile_read(RSFile *rs, const char *filepath) { FILE *f = fopen(filepath, "rb"); if (!f) { perror("Failed to open file"); return; } uint32_t header[8]; if (fread(header, sizeof(uint32_t), 8, f) != 8) { fprintf(stderr, "File too small for header\n"); fclose(f); return; } // Convert from big-endian for (int i = 0; i < 8; i++) { header[i] = ntohl(header[i]); } rs->magic = header[0]; if (rs->magic != MAGIC) { fprintf(stderr, "Invalid magic number\n"); fclose(f); return; } rs->width = header[1]; rs->height = header[2]; rs->depth = header[3]; rs->length = header[4]; rs->type = header[5]; rs->map_type = header[6]; rs->map_length = header[7]; rs->color_map = malloc(rs->map_length); if (rs->color_map && fread(rs->color_map, 1, rs->map_length, f) != rs->map_length) { free(rs->color_map); rs->color_map = NULL; } rs->image_data = malloc(rs->length); if (rs->image_data && fread(rs->image_data, 1, rs->length, f) != rs->length) { free(rs->image_data); rs->image_data = NULL; } fclose(f); } void rsfile_print_properties(const RSFile *rs) { if (rs->magic == 0) { fprintf(stderr, "File not read yet\n"); return; } printf("Magic Number: 0x%08x\n", rs->magic); printf("Width: %u\n", rs->width); printf("Height: %u\n", rs->height); printf("Depth: %u\n", rs->depth); printf("Length: %u\n", rs->length); printf("Type: %u\n", rs->type); printf("Color Map Type: %u\n", rs->map_type); printf("Color Map Length: %u\n", rs->map_length); } void rsfile_write(const RSFile *rs, const char *new_filepath) { if (rs->magic == 0) { fprintf(stderr, "No data to write\n"); return; } FILE *f = fopen(new_filepath, "wb"); if (!f) { perror("Failed to open file for writing"); return; } uint32_t header[8] = { htonl(rs->magic), htonl(rs->width), htonl(rs->height), htonl(rs->depth), htonl(rs->length), htonl(rs->type), htonl(rs->map_type), htonl(rs->map_length) }; fwrite(header, sizeof(uint32_t), 8, f); if (rs->color_map) fwrite(rs->color_map, 1, rs->map_length, f); if (rs->image_data) fwrite(rs->image_data, 1, rs->length, f); fclose(f); } void rsfile_destroy(RSFile *rs) { free(rs->color_map); free(rs->image_data); free(rs); } // Example usage: // int main() { // RSFile *rs = rsfile_create("example.rs"); // rsfile_read(rs, "example.rs"); // rsfile_print_properties(rs); // rsfile_write(rs, "modified.rs"); // rsfile_destroy(rs); // return 0; // } // ===== end task-620 .RS ===== // ===== task-621 .RSA [C] ===== #include #include #include #include // Simple BigInt simulation using strings for large numbers typedef struct { char *str; // Hex string for simplicity } BigInt; typedef struct { char *filepath; BigInt version; BigInt modulus; BigInt publicExponent; BigInt privateExponent; BigInt prime1; BigInt prime2; BigInt exponent1; BigInt exponent2; BigInt coefficient; } RSAFileHandler; RSAFileHandler* rsa_create(const char* filepath) { RSAFileHandler* handler = malloc(sizeof(RSAFileHandler)); handler->filepath = strdup(filepath); handler->version.str = NULL; // Initialize others to NULL return handler; } void rsa_destroy(RSAFileHandler* handler) { free(handler->filepath); free(handler->version.str); // Free others free(handler); } char* read_file(const char* filepath) { FILE* f = fopen(filepath, "r"); if (!f) return NULL; fseek(f, 0, SEEK_END); long len = ftell(f); fseek(f, 0, SEEK_SET); char* content = malloc(len + 1); fread(content, 1, len, f); content[len] = 0; fclose(f); return content; } char* base64_decode(const char* input, size_t* out_len) { // Simple base64 decode (omit implementation for brevity, assume available or implement) // Placeholder *out_len = 0; return NULL; } int read_and_decode(RSAFileHandler* handler) { char* content = read_file(handler->filepath); if (!content) return 1; // Strip PEM (simple string replace, omit details) // Assume pem is base64 part size_t der_len; uint8_t* der = (uint8_t*)base64_decode(pem, &der_len); // Assume pem extracted if (!der) return 1; size_t pos = 0; uint8_t read_byte() { return der[pos++]; } size_t read_length() { size_t len = read_byte(); if (len & 0x80) { size_t bytes = len & 0x7F; len = 0; while (bytes--) len = (len << 8) | read_byte(); } return len; } char* read_integer() { if (read_byte() != 0x02) return NULL; size_t len = read_length(); char* hex = malloc(len * 2 + 1); char* p = hex; for (size_t i = 0; i < len; i++) p += sprintf(p, "%02x", read_byte()); *p = 0; return hex; } if (read_byte() != 0x30) return 1; read_length(); handler->version.str = read_integer(); handler->modulus.str = read_integer(); handler->publicExponent.str = read_integer(); handler->privateExponent.str = read_integer(); handler->prime1.str = read_integer(); handler->prime2.str = read_integer(); handler->exponent1.str = read_integer(); handler->exponent2.str = read_integer(); handler->coefficient.str = read_integer(); free(der); free(content); return 0; } void print_properties(RSAFileHandler* handler) { printf("version: %s\n", handler->version.str); // Print others similarly } int write_rsa(RSAFileHandler* handler, const char* new_filepath) { // Similar to encode, but omitted for brevity - implement DER encode and base64 PEM return 0; } // Example: // int main() { // RSAFileHandler* handler = rsa_create("sample.rsa"); // if (read_and_decode(handler) == 0) { // print_properties(handler); // write_rsa(handler, "new.rsa"); // } // rsa_destroy(handler); // return 0; // } // ===== end task-621 .RSA ===== // ===== task-622 .RSL [C++] ===== #include #include #include #include "tinyxml2.h" // Assume tinyxml2 library is included for XML parsing using namespace tinyxml2; class RSLFileHandler { private: std::string filename; XMLDocument doc; public: RSLFileHandler(const std::string& fn) : filename(fn) {} void openAndRead() { XMLError error = doc.LoadFile(filename.c_str()); if (error != XML_SUCCESS) { throw std::runtime_error("Failed to load file."); } } void printProperties() { if (doc.RootElement() == nullptr) { throw std::runtime_error("File not opened or parsed."); } traverse(doc.RootElement(), 0); } void traverse(XMLElement* node, int level) { std::string indent(level * 2, ' '); std::cout << indent << "Element: " << node->Name() << std::endl; for (const XMLAttribute* attr = node->FirstAttribute(); attr; attr = attr->Next()) { std::cout << indent << " Attribute: " << attr->Name() << " = " << attr->Value() << std::endl; } const char* text = node->GetText(); if (text && std::string(text).find_first_not_of(" \t\n\r") != std::string::npos) { std::cout << indent << " Content: " << text << std::endl; } for (XMLElement* child = node->FirstChildElement(); child; child = child->NextSiblingElement()) { traverse(child, level + 1); } } void write(const std::string& newFilename) { if (doc.RootElement() == nullptr) { throw std::runtime_error("No data to write."); } doc.SaveFile((newFilename.empty() ? filename : newFilename).c_str()); } }; // Example usage: // int main() { // try { // RSLFileHandler handler("example.rsl"); // handler.openAndRead(); // handler.printProperties(); // handler.write("output.rsl"); // } catch (const std::exception& e) { // std::cerr << "Error: " << e.what() << std::endl; // } // return 0; // } // ===== end task-622 .RSL ===== // ===== task-624 .RSLS [C] ===== #include #include #include #include typedef struct { char filepath[256]; int file_size; char content_status[16]; int is_valid_placeholder; char file_name[256]; char extension[8]; char purpose[64]; } RSLSProperties; typedef struct { char filepath[256]; RSLSProperties props; } RSLSFile; void read_and_decode(RSLSFile *rsls) { FILE *file = fopen(rsls->filepath, "rb"); if (!file) { printf("Error: File does not exist.\n"); return; } fseek(file, 0, SEEK_END); rsls->props.file_size = ftell(file); fseek(file, 0, SEEK_SET); char *buffer = malloc(rsls->props.file_size + 1); fread(buffer, 1, rsls->props.file_size, file); buffer[rsls->props.file_size] = '\0'; fclose(file); free(buffer); char *ext = strrchr(rsls->filepath, '.'); if (!ext || strcmp(ext, ".rsls") != 0) { printf("Error: File does not have .rsls extension.\n"); return; } strcpy(rsls->props.file_name, strrchr(rsls->filepath, '/') ? strrchr(rsls->filepath, '/') + 1 : rsls->filepath); strcpy(rsls->props.extension, ".rsls"); strcpy(rsls->props.purpose, "Resilio Sync placeholder for selective sync"); strcpy(rsls->props.content_status, rsls->props.file_size == 0 ? "Empty" : "Non-empty"); rsls->props.is_valid_placeholder = (rsls->props.file_size == 0); rsls->props_print(); } void (RSLSProperties *props) print() { // Note: Typo in original, corrected to function pointer style for simplicity printf("=== .RSLS File Properties ===\n"); printf("File Name: %s\n", props->file_name); printf("File Size: %d bytes\n", props->file_size); printf("Content: %s\n", props->content_status); printf("Is Valid Placeholder: %s\n", props->is_valid_placeholder ? "Yes" : "No"); printf("Extension: %s\n", props->extension); printf("Purpose: %s\n", props->purpose); printf("==============================\n"); } void write(RSLSFile *rsls, char *output_path) { if (strlen(output_path) > 0 && strcmp(output_path + strlen(output_path) - 5, ".rsls") != 0) { strcat(output_path, ".rsls"); } FILE *out = fopen(output_path, "wb"); if (out) { fclose(out); // Write 0 bytes by closing immediately printf("Valid .RSLS placeholder written to %s\n", output_path); strcpy(rsls->filepath, output_path); read_and_decode(rsls); // Validate } else { printf("Error writing file.\n"); } } int main(int argc, char *argv[]) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } RSLSFile rsls = {0}; strcpy(rsls.filepath, argv[1]); read_and_decode(&rsls); // Example write: char out[] = "new.rsls"; write(&rsls, out); return 0; } // ===== end task-624 .RSLS ===== // ===== task-625 .RSM [C] ===== #include #include #include #include typedef struct { char signature[4]; uint32_t lfoDir; uint16_t cbDirHeader; uint16_t cbDirEntry; uint16_t cDir; uint32_t lfoNextDir; uint32_t flags; struct { uint16_t type; uint16_t iMod; uint32_t lfo; uint32_t cb; } subsections[32]; // Assume max 32 subsections } RSMProperties; const char *get_subsection_name(uint16_t id) { switch (id) { case 0x0120: return "sstModule"; case 0x0121: return "sstTypes"; case 0x0122: return "sstPublic"; case 0x0123: return "sstPublicSym"; case 0x0124: return "sstSymbols"; case 0x0127: return "sstSrcModule"; case 0x0128: return "sstLibraries"; case 0x0129: return "sstGlobalSym"; case 0x012A: return "sstGlobalPub"; case 0x012B: return "sstGlobalTypes"; case 0x012D: return "sstSegMap"; case 0x012E: return "sstSegName"; case 0x0133: return "sstFileIndex"; case 0x0134: return "sstStaticSym"; default: return "Unknown"; } } void print_properties(RSMProperties *props) { printf("RSM File Properties:\n"); printf("Signature: %.4s\n", props->signature); printf("Directory Offset: %u\n", props->lfoDir); printf("Directory Header:\n"); printf(" - cbDirHeader: %u\n", props->cbDirHeader); printf(" - cbDirEntry: %u\n", props->cbDirEntry); printf(" - cDir: %u\n", props->cDir); printf(" - lfoNextDir: %u\n", props->lfoNextDir); printf(" - flags: %u\n", props->flags); printf("Subsections:\n"); for (int i = 0; i < props->cDir; i++) { printf(" - Type: %s (0x%04X), Module: %u, Offset: %u, Size: %u\n", get_subsection_name(props->subsections[i].type), props->subsections[i].type, props->subsections[i].iMod, props->subsections[i].lfo, props->subsections[i].cb); } } void read_rsm(const char *filename, RSMProperties *props) { FILE *f = fopen(filename, "rb"); if (!f) { perror("File open error"); return; } fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); int pos = 0; memcpy(props->signature, data + pos, 4); pos += 4; props->lfoDir = *(uint32_t *)(data + pos); pos = props->lfoDir; props->cbDirHeader = *(uint16_t *)(data + pos); pos += 2; props->cbDirEntry = *(uint16_t *)(data + pos); pos += 2; props->cDir = *(uint16_t *)(data + pos); pos += 2; props->lfoNextDir = *(uint32_t *)(data + pos); pos += 4; props->flags = *(uint32_t *)(data + pos); pos += 4; for (int i = 0; i < props->cDir; i++) { props->subsections[i].type = *(uint16_t *)(data + pos); pos += 2; props->subsections[i].iMod = *(uint16_t *)(data + pos); pos += 2; props->subsections[i].lfo = *(uint32_t *)(data + pos); pos += 4; props->subsections[i].cb = *(uint32_t *)(data + pos); pos += 4; } free(data); print_properties(props); } void write_skeleton(const char *output_filename) { FILE *f = fopen(output_filename, "wb"); if (!f) { perror("File write error"); return; } // Skeleton: NB05, lfoDir=20, dummy header and entry fwrite("NB05", 1, 4, f); fwrite("\x00\x00\x00\x14", 1, 4, f); // lfoDir = 20 fwrite("\x14\x00\x0C\x00\x01\x00\x00\x00\x00\x00", 1, 10, f); // Header fwrite("\x20\x01\x00\x00\x18\x00\x00\x00\x00\x00\x00\x00", 1, 12, f); // Dummy sstModule entry fclose(f); printf("Wrote skeleton .RSM to %s\n", output_filename); } int main() { RSMProperties props = {0}; read_rsm("example.rsm", &props); write_skeleton("skeleton.rsm"); return 0; } // ===== end task-625 .RSM ===== // ===== task-626 .RST [C] ===== #include #include #include #include #define STD_HEADER_SIZE 100 #define RST_HEADER_SIZE 80 typedef struct { int32_t std_header[STD_HEADER_SIZE]; int32_t rst_header[RST_HEADER_SIZE]; int32_t *dof_array; int num_dof; char *filename; } RSTFile; void rst_read(RSTFile *rst, const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) { perror("Error opening file"); return; } rst->filename = strdup(filename); // Read standard header fread(rst->std_header, sizeof(int32_t), STD_HEADER_SIZE, f); // Read RST header fread(rst->rst_header, sizeof(int32_t), RST_HEADER_SIZE, f); // Read DOF array rst->num_dof = rst->rst_header[4]; rst->dof_array = malloc(rst->num_dof * sizeof(int32_t)); fread(rst->dof_array, sizeof(int32_t), rst->num_dof, f); fclose(f); printf("RST file loaded successfully.\n"); } void rst_print_properties(RSTFile *rst) { if (rst->std_header[0] == 0) { printf("No data loaded. Call rst_read() first.\n"); return; } printf("Standard Header Properties:\n"); printf("File Number: %d\n", rst->std_header[0]); printf("File Format: %d\n", rst->std_header[1]); printf("Creation Time: %d\n", rst->std_header[2]); printf("Creation Date: %d\n", rst->std_header[3]); printf("Unit System: %d\n", rst->std_header[4]); printf("Release Level: %d\n", rst->std_header[9]); uint64_t max_len = ((uint64_t)rst->std_header[97] << 32) | rst->std_header[96]; printf("Maximum File Length: %lu\n", max_len); printf("\nRST Header Properties:\n"); printf("Max Node: %d\n", rst->rst_header[1]); printf("Num Nodes: %d\n", rst->rst_header[2]); printf("Max Datasets: %d\n", rst->rst_header[3]); printf("DOFs per Node: %d\n", rst->rst_header[4]); printf("Max Element: %d\n", rst->rst_header[5]); printf("Num Elements: %d\n", rst->rst_header[6]); printf("Analysis Type: %d\n", rst->rst_header[7]); printf("Num Datasets: %d\n", rst->rst_header[8]); printf("Unit System: %d\n", rst->rst_header[20]); printf("Complex Flag: %d\n", rst->rst_header[31]); printf("Precision Key: %d\n", rst->rst_header[29]); printf("Available Data Bits: %d\n", rst->rst_header[34]); printf("XFEM Key: %d\n", rst->rst_header[37]); printf("Global Nodes: %d\n", rst->rst_header[39]); printf("\nDOF Array:\n"); for (int i = 0; i < rst->num_dof; i++) { printf("%d ", rst->dof_array[i]); } printf("\n"); } void rst_write(RSTFile *rst, const char *output_filename) { if (rst->std_header[0] == 0) { fprintf(stderr, "No data to write.\n"); return; } FILE *f = fopen(output_filename, "wb"); if (!f) { perror("Error writing file"); return; } // Write standard header fwrite(rst->std_header, sizeof(int32_t), STD_HEADER_SIZE, f); // Write RST header fwrite(rst->rst_header, sizeof(int32_t), RST_HEADER_SIZE, f); // Write DOF fwrite(rst->dof_array, sizeof(int32_t), rst->num_dof, f); fclose(f); printf("Basic headers written to %s.\n", output_filename); } void rst_free(RSTFile *rst) { free(rst->dof_array); free(rst->filename); } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } RSTFile rst = {0}; rst_read(&rst, argv[1]); rst_print_properties(&rst); // rst_write(&rst, "output.rst"); rst_free(&rst); return 0; } // ===== end task-626 .RST ===== // ===== task-627 .RTF [C++] ===== #include #include #include #include #include #include class RtfHandler { private: std::string filepath; std::string text; std::map properties; public: void open(const std::string& fp) { filepath = fp; std::ifstream file(filepath); if (file) { std::string line; while (std::getline(file, line)) { text += line + "\n"; } file.close(); decodeProperties(); } } void decodeProperties() { // RTF Version std::regex versionRegex(R"(\\rtf(\d+))"); std::smatch match; if (std::regex_search(text, match, versionRegex)) { properties["RTF Version"] = match[1]; } else { properties["RTF Version"] = "Unknown"; } // Character Set std::regex charsetRegex(R"(\\ (ansi|mac|pc|pca))"); if (std::regex_search(text, match, charsetRegex)) { properties["Character Set"] = match[1]; } else { properties["Character Set"] = "Unknown"; } // ANSI Code Page std::regex ansicpgRegex(R"(\\ansicpg(\d+))"); if (std::regex_search(text, match, ansicpgRegex)) { properties["ANSI Code Page"] = match[1]; } else { properties["ANSI Code Page"] = "Unknown"; } // Default Font std::regex deffRegex(R"(\\deff(\d+))"); if (std::regex_search(text, match, deffRegex)) { properties["Default Font"] = match[1]; } else { properties["Default Font"] = "Unknown"; } // Default Language std::regex deflangRegex(R"(\\deflang(\d+))"); if (std::regex_search(text, match, deflangRegex)) { properties["Default Language"] = match[1]; } else { properties["Default Language"] = "Unknown"; } // Font Table std::regex fonttblRegex(R"(\{\\fonttbl([^}]+)\})"); if (std::regex_search(text, match, fonttblRegex)) { std::string fontStr = match[1]; // Simple split by ';' std::string fonts; size_t pos = 0; while ((pos = fontStr.find(";")) != std::string::npos) { fonts += fontStr.substr(0, pos) + ", "; fontStr.erase(0, pos + 1); } fonts += fontStr; properties["Font Table"] = fonts; } else { properties["Font Table"] = "Unknown"; } // Color Table std::regex colortblRegex(R"(\{\\colortbl([^}]+)\})"); if (std::regex_search(text, match, colortblRegex)) { std::string colorStr = match[1]; std::string colors; size_t pos = 0; while ((pos = colorStr.find(";")) != std::string::npos) { colors += colorStr.substr(0, pos) + ", "; colorStr.erase(0, pos + 1); } colors += colorStr; properties["Color Table"] = colors; } else { properties["Color Table"] = "Unknown"; } // Stylesheet std::regex stylesheetRegex(R"(\{\\stylesheet([^}]+)\})"); if (std::regex_search(text, match, stylesheetRegex)) { properties["Stylesheet"] = match[1]; } else { properties["Stylesheet"] = "Unknown"; } // \info group std::regex infoRegex(R"(\{\\info([^}]+)\})"); if (std::regex_search(text, match, infoRegex)) { std::string infoText = match[1]; std::regex titleRegex(R"(\{\\title([^}]+)\})"); if (std::regex_search(infoText, match, titleRegex)) { properties["Title"] = match[1]; } else { properties["Title"] = "Unknown"; } std::regex subjectRegex(R"(\{\\subject([^}]+)\})"); if (std::regex_search(infoText, match, subjectRegex)) { properties["Subject"] = match[1]; } else { properties["Subject"] = "Unknown"; } std::regex authorRegex(R"(\{\\author([^}]+)\})"); if (std::regex_search(infoText, match, authorRegex)) { properties["Author"] = match[1]; } else { properties["Author"] = "Unknown"; } std::regex keywordsRegex(R"(\{\\keywords([^}]+)\})"); if (std::regex_search(infoText, match, keywordsRegex)) { properties["Keywords"] = match[1]; } else { properties["Keywords"] = "Unknown"; } std::regex commentRegex(R"(\{\\comment([^}]+)\})"); if (std::regex_search(infoText, match, commentRegex)) { properties["Comment"] = match[1]; } else { properties["Comment"] = "Unknown"; } std::regex operatorRegex(R"(\{\\operator([^}]+)\})"); if (std::regex_search(infoText, match, operatorRegex)) { properties["Operator"] = match[1]; } else { properties["Operator"] = "Unknown"; } std::regex creatimRegex(R"(\{\\creatim \\yr(\d+) \\mo(\d+) \\dy(\d+) \\hr(\d+) \\min(\d+)\})"); if (std::regex_search(infoText, match, creatimRegex)) { properties["Creation Time"] = match[1] + "-" + match[2] + "-" + match[3] + " " + match[4] + ":" + match[5]; } else { properties["Creation Time"] = "Unknown"; } std::regex revtimRegex(R"(\{\\revtim \\yr(\d+) \\mo(\d+) \\dy(\d+) \\hr(\d+) \\min(\d+)\})"); if (std::regex_search(infoText, match, revtimRegex)) { properties["Revision Time"] = match[1] + "-" + match[2] + "-" + match[3] + " " + match[4] + ":" + match[5]; } else { properties["Revision Time"] = "Unknown"; } std::regex printimRegex(R"(\{\\printim \\yr(\d+) \\mo(\d+) \\dy(\d+) \\hr(\d+) \\min(\d+)\})"); if (std::regex_search(infoText, match, printimRegex)) { properties["Print Time"] = match[1] + "-" + match[2] + "-" + match[3] + " " + match[4] + ":" + match[5]; } else { properties["Print Time"] = "Unknown"; } std::regex buptimRegex(R"(\{\\buptim \\yr(\d+) \\mo(\d+) \\dy(\d+) \\hr(\d+) \\min(\d+)\})"); if (std::regex_search(infoText, match, buptimRegex)) { properties["Backup Time"] = match[1] + "-" + match[2] + "-" + match[3] + " " + match[4] + ":" + match[5]; } else { properties["Backup Time"] = "Unknown"; } std::regex edminsRegex(R"(\\edmins(\d+))"); if (std::regex_search(infoText, match, edminsRegex)) { properties["Total Editing Time"] = match[1]; } else { properties["Total Editing Time"] = "Unknown"; } std::regex nofpagesRegex(R"(\\nofpages(\d+))"); if (std::regex_search(infoText, match, nofpagesRegex)) { properties["Number of Pages"] = match[1]; } else { properties["Number of Pages"] = "Unknown"; } std::regex nofwordsRegex(R"(\\nofwords(\d+))"); if (std::regex_search(infoText, match, nofwordsRegex)) { properties["Number of Words"] = match[1]; } else { properties["Number of Words"] = "Unknown"; } std::regex nofcharsRegex(R"(\\nofchars(\d+))"); if (std::regex_search(infoText, match, nofcharsRegex)) { properties["Number of Characters"] = match[1]; } else { properties["Number of Characters"] = "Unknown"; } std::regex nofcharswsRegex(R"(\\nofcharsws(\d+))"); if (std::regex_search(infoText, match, nofcharswsRegex)) { properties["Number of Characters with Spaces"] = match[1]; } else { properties["Number of Characters with Spaces"] = "Unknown"; } std::regex vernRegex(R"(\\vern(\d+))"); if (std::regex_search(infoText, match, vernRegex)) { properties["Internal Version"] = match[1]; } else { properties["Internal Version"] = "Unknown"; } std::regex idRegex(R"(\\id(\d+))"); if (std::regex_search(infoText, match, idRegex)) { properties["Document ID"] = match[1]; } else { properties["Document ID"] = "Unknown"; } } else { std::vector keys = {"Title", "Subject", "Author", "Keywords", "Comment", "Operator", "Creation Time", "Revision Time", "Print Time", "Backup Time", "Total Editing Time", "Number of Pages", "Number of Words", "Number of Characters", "Number of Characters with Spaces", "Internal Version", "Document ID"}; for (const auto& key : keys) { properties[key] = "Unknown"; } } } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& outputPath = "") { std::string out = outputPath.empty() ? filepath : outputPath; std::ofstream file(out); if (file) { file << text; file.close(); } } }; // Example usage: // int main() { // RtfHandler handler; // handler.open("sample.rtf"); // handler.printProperties(); // handler.write("output.rtf"); // return 0; // } // ===== end task-627 .RTF ===== // ===== task-628 .RUA [C] ===== #include #include #include #include #include typedef struct { char *filepath; xmlDocPtr doc; } RuaFileHandler; RuaFileHandler* rua_create(const char *filepath) { RuaFileHandler *handler = malloc(sizeof(RuaFileHandler)); handler->filepath = strdup(filepath); handler->doc = NULL; return handler; } void rua_read(RuaFileHandler *handler) { if (strstr(handler->filepath, ".rua") == NULL) { fprintf(stderr, "Invalid .RUA file.\n"); return; } handler->doc = xmlReadFile(handler->filepath, NULL, 0); if (handler->doc == NULL || strcmp((const char*)handler->doc->children->name, "feedback") != 0) { fprintf(stderr, "Not a valid DMARC .RUA file.\n"); } } void traverse_and_print(xmlNode *node, char *path) { if (node == NULL) return; char new_path[1024]; snprintf(new_path, sizeof(new_path), "%s%s%s", path, strlen(path) > 0 ? "." : "", node->name); if (node->type == XML_ELEMENT_NODE) { if (node->children && node->children->type == XML_TEXT_NODE && node->children->content) { printf("%s: %s\n", new_path, node->children->content); } else { xmlNode *child = node->children; while (child) { traverse_and_print(child, new_path); child = child->next; } } } } void rua_decode_and_print(RuaFileHandler *handler) { if (handler->doc == NULL) rua_read(handler); traverse_and_print(handler->doc->children, ""); } void rua_write(RuaFileHandler *handler) { // Simple example write; in real use, build from data xmlDocPtr new_doc = xmlNewDoc(BAD_CAST "1.0"); xmlNodePtr root = xmlNewNode(NULL, BAD_CAST "feedback"); xmlDocSetRootElement(new_doc, root); xmlNewChild(root, NULL, BAD_CAST "version", BAD_CAST "1.0"); // Add more nodes as needed... xmlSaveFormatFileEnc(handler->filepath, new_doc, "UTF-8", 1); xmlFreeDoc(new_doc); } void rua_destroy(RuaFileHandler *handler) { if (handler->doc) xmlFreeDoc(handler->doc); free(handler->filepath); free(handler); } // Example usage: // int main() { // RuaFileHandler *handler = rua_create("example.rua"); // rua_read(handler); // rua_decode_and_print(handler); // rua_write(handler); // rua_destroy(handler); // return 0; // } // ===== end task-628 .RUA ===== // ===== task-629 .RUN [C++] ===== #include #include #include #include #include #include #include // For chmod class RunFileHandler { private: std::string filename; std::map properties; int skip = 0; std::vector payload; public: RunFileHandler(const std::string& fn) : filename(fn) {} void read() { std::ifstream file(filename, std::ios::binary); if (!file) { std::cerr << "Failed to open file." << std::endl; return; } std::vector content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); std::string textContent(content.begin(), content.end()); std::vector lines; std::string line; for (char c : textContent) { if (c == '\n') { lines.push_back(line); line.clear(); } else { line += c; } } if (!line.empty()) lines.push_back(line); std::regex assignRegex(R"((\w+)=["']?(.*?)["']?$)"); std::smatch match; for (const auto& ln : lines) { std::string trimmed = ln; // Trim whitespace (simplified) trimmed.erase(0, trimmed.find_first_not_of(" \t")); trimmed.erase(trimmed.find_last_not_of(" \t") + 1); if (trimmed.rfind("skip=", 0) == 0) { skip = std::stoi(trimmed.substr(5)); break; } if (std::regex_match(trimmed, match, assignRegex) && trimmed[0] != '#') { properties[match[1]] = match[2]; } } std::string headerText; for (int i = 0; i < skip - 1; ++i) { headerText += lines[i] + "\n"; } size_t headerLength = headerText.size(); payload.assign(content.begin() + headerLength, content.end()); } void printProperties() const { if (properties.empty()) { std::cout << "No properties found. Call read() first." << std::endl; return; } for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } std::cout << "skip: " << skip << std::endl; } void write(const std::string& newFilename, const std::map& newProperties = {}, const std::vector& newPayload = {}) { for (const auto& pair : newProperties) { properties[pair.first] = pair.second; } if (!newPayload.empty()) { payload = newPayload; } std::string header = "#!/bin/sh\n"; for (const auto& pair : properties) { header += pair.first + "=\"" + pair.second + "\"\n"; } std::vector headerLines = split(header, '\n'); int newSkip = headerLines.size() + 2; // For skip and extraction lines header += "skip=" + std::to_string(newSkip) + "\n"; header += "tail -n +$skip $0 | gunzip | tar x\nexit 0\n"; std::ofstream outFile(newFilename, std::ios::binary); outFile << header; outFile.write(payload.data(), payload.size()); outFile.close(); chmod(newFilename.c_str(), 0755); } private: std::vector split(const std::string& s, char delimiter) { std::vector tokens; std::string token; std::istringstream tokenStream(s); while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; } }; // Example usage: // int main() { // RunFileHandler handler("example.run"); // handler.read(); // handler.printProperties(); // handler.write("new.run"); // return 0; // } // ===== end task-629 .RUN ===== // ===== task-630 .S [C] ===== #include #include #include #include #include #include #include struct SFile { char *filepath; struct stat statbuf; }; struct SFile* SFile_create(const char *filepath) { struct SFile *s = malloc(sizeof(struct SFile)); s->filepath = strdup(filepath); if (stat(filepath, &s->statbuf) != 0) { perror("stat"); free(s->filepath); free(s); return NULL; } return s; } void SFile_destroy(struct SFile *s) { free(s->filepath); free(s); } void SFile_print_properties(struct SFile *s) { char *filename = strrchr(s->filepath, '/'); filename = filename ? filename + 1 : s->filepath; printf("File name: %s\n", filename); printf("File path: %s\n", realpath(s->filepath, NULL)); printf("Size: %ld bytes\n", s->statbuf.st_size); printf("Permissions: %o\n", s->statbuf.st_mode & 0777); printf("Owner UID: %d\n", s->statbuf.st_uid); printf("Group GID: %d\n", s->statbuf.st_gid); printf("Inode number: %ld\n", s->statbuf.st_ino); printf("Number of hard links: %ld\n", s->statbuf.st_nlink); printf("Device ID: %ld\n", s->statbuf.st_dev); printf("Last access time: %s", ctime(&s->statbuf.st_atime)); printf("Last modification time: %s", ctime(&s->statbuf.st_mtime)); printf("Last status change time: %s", ctime(&s->statbuf.st_ctime)); #ifdef __APPLE__ printf("Creation time: %s", ctime(&s->statbuf.st_birthtime)); #else printf("Creation time: Not supported on this system\n"); #endif } char* SFile_read_content(struct SFile *s) { FILE *f = fopen(s->filepath, "r"); if (!f) { perror("fopen"); return NULL; } fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); char *content = malloc(size + 1); fread(content, 1, size, f); content[size] = '\0'; fclose(f); return content; } int SFile_write_content(struct SFile *s, const char *content) { FILE *f = fopen(s->filepath, "w"); if (!f) { perror("fopen"); return -1; } fputs(content, f); fclose(f); return 0; } // Example usage: // int main() { // struct SFile *s = SFile_create("example.S"); // if (s) { // SFile_print_properties(s); // char *content = SFile_read_content(s); // if (content) { // SFile_write_content(s, content); // free(content); // } // SFile_destroy(s); // } // return 0; // } // ===== end task-630 .S ===== // ===== task-631 .S3M [C++] ===== #include #include #include #include #include #include #include class S3MFile { private: std::string filename; std::vector data; std::map properties; // Using string for simplicity in printing std::vector> instruments; std::vector> patterns; uint16_t readUint16LE(size_t &offset) { uint16_t val = (data[offset + 1] << 8) | data[offset]; offset += 2; return val; } uint32_t readUint32LE(size_t &offset) { uint32_t val = (data[offset + 3] << 24) | (data[offset + 2] << 16) | (data[offset + 1] << 8) | data[offset]; offset += 4; return val; } std::string readString(size_t &offset, size_t len) { std::string str(reinterpret_cast(&data[offset]), len); str.erase(std::find(str.begin(), str.end(), '\0'), str.end()); offset += len; return str; } public: S3MFile(const std::string& fn) : filename(fn) { load(); } void load() { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) { std::cerr << "Failed to open file." << std::endl; return; } size_t size = file.tellg(); data.resize(size); file.seekg(0); file.read(reinterpret_cast(data.data()), size); decode(); } void decode() { size_t offset = 0; properties["song_title"] = readString(offset, 28); properties["sig1"] = std::to_string(data[offset++]); properties["type"] = std::to_string(data[offset++]); properties["reserved_header"] = std::to_string(readUint16LE(offset)); uint16_t orderCount = readUint16LE(offset); properties["order_count"] = std::to_string(orderCount); uint16_t instrumentCount = readUint16LE(offset); properties["instrument_count"] = std::to_string(instrumentCount); uint16_t patternPtrCount = readUint16LE(offset); properties["pattern_ptr_count"] = std::to_string(patternPtrCount); properties["flags"] = std::to_string(readUint16LE(offset)); properties["tracker_version"] = std::to_string(readUint16LE(offset)); properties["sample_type"] = std::to_string(readUint16LE(offset)); properties["sig2"] = readString(offset, 4); properties["global_volume"] = std::to_string(data[offset++]); properties["initial_speed"] = std::to_string(data[offset++]); properties["initial_tempo"] = std::to_string(data[offset++]); properties["master_volume"] = std::to_string(data[offset++]); properties["ultra_click_removal"] = std::to_string(data[offset++]); properties["default_pan"] = std::to_string(data[offset++]); offset += 8; // reserved_extended properties["ptr_special"] = std::to_string(readUint16LE(offset)); std::string channelSettings = "["; for (int i = 0; i < 32; i++) { channelSettings += std::to_string(data[offset++]) + (i < 31 ? ", " : ""); } channelSettings += "]"; properties["channel_settings"] = channelSettings; std::string orderList = "["; for (int i = 0; i < orderCount; i++) { orderList += std::to_string(data[offset++]) + (i < orderCount - 1 ? ", " : ""); } orderList += "]"; properties["order_list"] = orderList; std::string instPtrsStr = "["; std::vector instPtrs; for (int i = 0; i < instrumentCount; i++) { uint32_t ptr = readUint16LE(offset) * 16; instPtrs.push_back(ptr); instPtrsStr += std::to_string(ptr) + (i < instrumentCount - 1 ? ", " : ""); } instPtrsStr += "]"; properties["instrument_pointers"] = instPtrsStr; std::string patPtrsStr = "["; std::vector patPtrs; for (int i = 0; i < patternPtrCount; i++) { uint32_t ptr = readUint16LE(offset) * 16; patPtrs.push_back(ptr); patPtrsStr += std::to_string(ptr) + (i < patternPtrCount - 1 ? ", " : ""); } patPtrsStr += "]"; properties["pattern_pointers"] = patPtrsStr; // Instruments for (auto ptr : instPtrs) { std::map inst; offset = ptr; uint8_t type = data[offset++]; inst["type"] = std::to_string(type); inst["filename"] = readString(offset, 12); if (type == 1) { inst["data_ptr_high"] = std::to_string(data[offset++]); inst["data_ptr_low"] = std::to_string(readUint16LE(offset)); inst["length"] = std::to_string(readUint32LE(offset)); inst["loop_start"] = std::to_string(readUint32LE(offset)); inst["loop_end"] = std::to_string(readUint32LE(offset)); inst["volume"] = std::to_string(data[offset++]); inst["reserved_inst"] = std::to_string(data[offset++]); inst["pack"] = std::to_string(data[offset++]); inst["flags_inst"] = std::to_string(data[offset++]); inst["c2_speed"] = std::to_string(readUint32LE(offset)); offset += 12; // internal inst["title"] = readString(offset, 28); inst["sig"] = readString(offset, 4); } else if (type >= 2 && type <= 7) { offset += 3; // reserved_adlib offset += 12; // opl_values inst["volume"] = std::to_string(data[offset++]); inst["disk"] = std::to_string(data[offset++]); inst["reserved_adlib_ext"] = std::to_string(readUint16LE(offset)); inst["c2_speed"] = std::to_string(readUint32LE(offset)); offset += 12; // unused inst["title"] = readString(offset, 28); inst["sig"] = readString(offset, 4); } instruments.push_back(inst); } // Patterns for (auto ptr : patPtrs) { if (ptr == 0) continue; std::map pat; offset = ptr; pat["packed_size"] = std::to_string(readUint16LE(offset)); patterns.push_back(pat); // Skip packed data } } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } for (size_t i = 0; i < instruments.size(); ++i) { std::cout << "\nInstrument " << (i + 1) << ":" << std::endl; for (const auto& instProp : instruments[i]) { std::cout << " " << instProp.first << ": " << instProp.second << std::endl; } } for (size_t i = 0; i < patterns.size(); ++i) { std::cout << "\nPattern " << i << ":" << std::endl; for (const auto& patProp : patterns[i]) { std::cout << " " << patProp.first << ": " << patProp.second << std::endl; } } } void write(const std::string& outputFilename) { std::ofstream outFile(outputFilename, std::ios::binary); if (!outFile) { std::cerr << "Failed to write file." << std::endl; return; } outFile.write(reinterpret_cast(data.data()), data.size()); } }; // Example usage: // int main() { // S3MFile s3m("example.s3m"); // s3m.printProperties(); // s3m.write("output.s3m"); // return 0; // } // ===== end task-631 .S3M ===== // ===== task-632 .S7I [C++] ===== #include #include #include #include class S7IFile { private: std::string filename; std::string content; public: S7IFile(const std::string& fn) : filename(fn), content("") {} void openAndDecode() { // Open and read/decode as text (since .S7I is plain text) std::ifstream file(filename); if (file.is_open()) { std::stringstream buffer; buffer << file.rdbuf(); content = buffer.str(); file.close(); } else { std::cerr << "Error opening file: " << filename << std::endl; } } void printProperties() { if (content.empty()) { openAndDecode(); } std::cout << "Properties of .S7I file (full decoded content):\n" << std::endl; std::cout << content << std::endl; } void write(const std::string& newContent) { std::ofstream file(filename); if (file.is_open()) { file << newContent; file.close(); std::cout << "Written to " << filename << std::endl; } else { std::cerr << "Error writing to file: " << filename << std::endl; } } }; // Example usage: // int main() { // S7IFile s7i("example.s7i"); // s7i.printProperties(); // s7i.write("$ include \"seed7_05.s7i\";\nconst proc: main is func\nbegin\nwriteln(\"hello\");\nend func;"); // return 0; // } // ===== end task-632 .S7I ===== // ===== task-633 .SAIF [C++] ===== #include #include #include #include #include #include #include using namespace std; struct Expr { string keyword; variant>> value; // C++17 variant; simplify if C++11 }; class SAIFParser { private: string content; size_t pos; map>>> properties; public: SAIFParser(const string& filePath) { ifstream file(filePath); string line; stringstream ss; while (getline(file, line)) ss << line << " "; content = ss.str(); content = regex_replace(content, regex("\\s+"), " "); // Requires content = regex_replace(content, regex("^ +| +$"), ""); // Trim pos = 0; properties["header"] = map>>>(); properties["body"] = vector(); } map>>> parse() { if (content.substr(pos, 8) != "(SAIFILE") throw runtime_error("Invalid SAIF file"); skip(8); expect("("); auto& header = get>>>>(properties["header"]); auto& body = get>(properties["body"]); while (pos < content.length() && content[pos] != ')') { Expr expr = parseExpression(); if (expr.keyword == "INSTANCE" || expr.keyword == "NET" || expr.keyword == "PORT") { body.push_back(expr); } else { header[expr.keyword] = expr.value; } } expect(")"); return properties; } Expr parseExpression() { skipWS(); if (content[pos] != '(') throw runtime_error("Expected ("); pos++; skipWS(); string keyword = readToken(); skipWS(); variant>> value; if (isActivityMetric(keyword) || keyword == "DURATION") { value = stod(readToken()); } else if (isHeaderKeyword(keyword)) { value = readToken(); get(value) = get(value).erase(remove(get(value).begin(), get(value).end(), '"'), get(value).end()); } else { map> vmap; while (content[pos] != ')') { Expr sub = parseExpression(); vmap[sub.keyword] = sub.value; } value = vmap; } expect(")"); return {keyword, value}; } bool isActivityMetric(const string& kw) { return kw == "T0" || kw == "T1" || kw == "TX" || kw == "TC" || kw == "IG"; } bool isHeaderKeyword(const string& kw) { return kw == "SAIFVERSION" || kw == "DIRECTION" || kw == "DESIGN" || kw == "DATE" || kw == "VENDOR" || kw == "PROGRAM_NAME" || kw == "VERSION" || kw == "DIVIDER" || kw == "TIMESCALE"; } void skipWS() { while (pos < content.length() && isspace(content[pos])) pos++; } void skip(size_t n) { pos += n; } string readToken() { string token; while (pos < content.length() && !isspace(content[pos]) && content[pos] != '(' && content[pos] != ')') { token += content[pos++]; } return token; } void expect(const string& s) { if (content.substr(pos, s.length()) != s) throw runtime_error("Expected " + s); pos += s.length(); } void printProperties() { // Simple print; extend for JSON-like cout << "Header: " << endl; auto& header = get>>>>(properties["header"]); for (auto& p : header) { cout << p.first << ": " << get(p.second) << endl; // Assume string for simplicity } cout << "Body items: " << get>(properties["body"]).size() << endl; } void write(const map>>>& props, const string& filePath) { ofstream out(filePath); out << "(SAIFILE "; auto& header = get>>(props.at("header")); for (auto& e : header) { out << "(" << e.first << " \"" << get(e.second) << "\") "; } auto& body = get>(props.at("body")); for (auto& item : body) { out << exprToStr(item) << " "; } out << ")" << endl; out.close(); } string exprToStr(const Expr& expr) { stringstream s; s << "(" << expr.keyword; // Handle value types similarly; simplify for string/number if (holds_alternative(expr.value)) { s << " " << get(expr.value); } else if (holds_alternative(expr.value)) { s << " \"" << get(expr.value) << "\""; } // Extend for map s << ")"; return s.str(); } }; // Usage (compile with C++17) // SAIFParser parser("sample.saif"); // auto props = parser.parse(); // parser.printProperties(); // parser.write(props, "output.saif"); // ===== end task-633 .SAIF ===== // ===== task-634 .SASS [C] ===== #include #include #include #include typedef struct { char* filename; uint8_t* data; size_t size; // Properties as array of key-value for simplicity char* keys[100]; char* values[100]; int prop_count; } SassFile; void sass_open(SassFile* self) { FILE* f = fopen(self->filename, "rb"); fseek(f, 0, SEEK_END); self->size = ftell(f); fseek(f, 0, SEEK_SET); self->data = malloc(self->size); fread(self->data, 1, self->size, f); fclose(f); } void sass_decode_read(SassFile* self) { if (!self->data) sass_open(self); uint32_t magic = *(uint32_t*)self->data; if (magic != 0x464c457f) { printf("Invalid ELF file\n"); return; } uint8_t ei_class = self->data[4]; uint8_t ei_data = self->data[5]; int little = ei_data == 1; self->keys[self->prop_count] = strdup("Base Format"); self->values[self->prop_count++] = strdup("ELF"); self->keys[self->prop_count] = strdup("EI_OSABI"); char buf[10]; sprintf(buf, "%d", self->data[7]); self->values[self->prop_count++] = strdup(buf); self->keys[self->prop_count] = strdup("EI_ABIVERSION"); sprintf(buf, "%d", self->data[8]); self->values[self->prop_count++] = strdup(buf); // Parse more with endian handling... // For ELF type, etc., use memcpy and endian conversion if needed } void sass_write(SassFile* self, char* new_filename) { if (!new_filename) { new_filename = malloc(strlen(self->filename) + 5); sprintf(new_filename, "%s.new", self->filename); } FILE* f = fopen(new_filename, "wb"); fwrite(self->data, 1, self->size, f); fclose(f); } void sass_print_properties(SassFile* self) { for (int i = 0; i < self->prop_count; i++) { printf("%s: %s\n", self->keys[i], self->values[i]); } } // Example usage // SassFile sass = {.filename = "example.sass", .prop_count = 0}; // sass_decode_read(&sass); // sass_print_properties(&sass); // sass_write(&sass, NULL); // ===== end task-634 .SASS ===== // ===== task-635 .SAT [C++] ===== #include #include #include #include #include #include class SatFileHandler { private: std::string filepath; std::map properties; std::string content; public: SatFileHandler(const std::string& fp) : filepath(fp) {} void readDecode() { std::ifstream file(filepath); std::stringstream buffer; buffer << file.rdbuf(); content = buffer.str(); file.close(); std::stringstream ss(content); std::vector tokens; std::string token; while (ss >> token) { tokens.push_back(token); } size_t index = 0; properties["Encoded Version Number"] = tokens[index++]; properties["Total Number of Records"] = tokens[index++]; properties["Number of Entities"] = tokens[index++]; properties["History Flag"] = tokens[index++]; // Product ID int len = std::stoi(tokens[index++]); std::string str = ""; while (static_cast(str.length()) < len) { if (!str.empty()) str += " "; str += tokens[index++]; } properties["Product ID"] = str; // ACIS Version len = std::stoi(tokens[index++]); str = ""; while (static_cast(str.length()) < len) { if (!str.empty()) str += " "; str += tokens[index++]; } properties["ACIS Version"] = str; // Date len = std::stoi(tokens[index++]); str = ""; while (static_cast(str.length()) < len) { if (!str.empty()) str += " "; str += tokens[index++]; } properties["Date"] = str; properties["Units"] = tokens[index++]; properties["Resabs"] = tokens[index++]; properties["Resnor"] = tokens[index++]; } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& outputPath) { if (!content.empty()) { std::ofstream outFile(outputPath); outFile << content; outFile.close(); } else { std::cout << "No content to write. Read the file first." << std::endl; } } }; // Example usage: // int main() { // SatFileHandler handler("sample.sat"); // handler.readDecode(); // handler.printProperties(); // handler.write("output.sat"); // return 0; // } // ===== end task-635 .SAT ===== // ===== task-636 .SAV [C] ===== #include #include #include #include typedef struct { char magic[5]; char product[61]; int32_t layout; int32_t num_vars; int32_t compression; int32_t weight_idx; int32_t num_cases; double bias; char date[10]; char time[9]; char label[65]; // Dynamic arrays for variables, etc. (simplified with fixed size for demo) struct Var { char name[9]; int32_t type; int32_t has_label; int32_t n_missing; uint8_t print_fmt[4]; uint8_t write_fmt[4]; char label_str[256]; // Assume max double missing[3]; // Max 3 } variables[100]; // Assume max 100 vars int var_count; // Skip value labels, docs, extensions for brevity in C } SavFile; void read_sav(SavFile *sav, const char *filepath) { FILE *f = fopen(filepath, "rb"); if (!f) return; uint8_t header[176]; fread(header, 1, 176, f); strncpy(sav->magic, (char*)header, 4); sav->magic[4] = 0; strncpy(sav->product, (char*)header + 4, 60); sav->product[60] = 0; memcpy(&sav->layout, header + 64, 4); memcpy(&sav->num_vars, header + 68, 4); memcpy(&sav->compression, header + 72, 4); if (sav->compression == 2) { fprintf(stderr, "ZLIB not supported.\n"); fclose(f); return; } memcpy(&sav->weight_idx, header + 76, 4); memcpy(&sav->num_cases, header + 80, 4); memcpy(&sav->bias, header + 84, 8); strncpy(sav->date, (char*)header + 92, 9); sav->date[9] = 0; strncpy(sav->time, (char*)header + 101, 8); sav->time[8] = 0; strncpy(sav->label, (char*)header + 109, 64); sav->label[64] = 0; sav->var_count = 0; for (int v = 0; v < sav->num_vars; v++) { int32_t tag; fread(&tag, 4, 1, f); if (tag != 2) break; struct Var *var = &sav->variables[sav->var_count++]; fread(&var->type, 4, 1, f); fread(&var->has_label, 4, 1, f); fread(&var->n_missing, 4, 1, f); fread(var->print_fmt, 1, 4, f); fread(var->write_fmt, 1, 4, f); fread(var->name, 1, 8, f); var->name[8] = 0; if (var->has_label) { int32_t label_len; fread(&label_len, 4, 1, f); fread(var->label_str, 1, label_len, f); var->label_str[label_len] = 0; int pad = (4 - (label_len % 4)) % 4; fseek(f, pad, SEEK_CUR); } if (var->n_missing > 0) { for (int m = 0; m < var->n_missing; m++) { if (var->type == 0) { fread(&var->missing[m], 8, 1, f); } else { char miss[9]; fread(miss, 1, 8, f); miss[8] = 0; var->missing[m] = atof(miss); // Simplified } } } } // Skip to terminator for simplicity while (1) { int32_t tag; fread(&tag, 4, 1, f); if (tag == 999) break; // Would parse other tags here fseek(f, -4, SEEK_CUR); // Backtrack for real parsing } fclose(f); } void print_properties(const SavFile *sav) { printf("Header:\n"); printf("- magic: %s\n", sav->magic); printf("- product: %s\n", sav->product); printf("- layout: %d\n", sav->layout); printf("- num_vars: %d\n", sav->num_vars); printf("- compression: %d\n", sav->compression); printf("- weight_idx: %d\n", sav->weight_idx); printf("- num_cases: %d\n", sav->num_cases); printf("- bias: %f\n", sav->bias); printf("- date: %s\n", sav->date); printf("- time: %s\n", sav->time); printf("- label: %s\n", sav->label); printf("\nVariables:\n"); for (int i = 0; i < sav->var_count; i++) { const struct Var *var = &sav->variables[i]; printf("- Name: %s, Type: %d, Label: %s, Missing count: %d\n", var->name, var->type, var->label_str, var->n_missing); printf(" Print Format: %u %u %u %u, Write Format: %u %u %u %u\n", var->print_fmt[0], var->print_fmt[1], var->print_fmt[2], var->print_fmt[3], var->write_fmt[0], var->write_fmt[1], var->write_fmt[2], var->write_fmt[3]); } // Add prints for other properties if parsed } void write_sav(const SavFile *sav, const char *output_path) { FILE *f = fopen(output_path, "wb"); if (!f) return; fwrite("$FL2", 1, 4, f); char product[60] = "@(#) SPSS DATA FILE - Mock - C "; memset(product + 37, ' ', 23); fwrite(product, 1, 60, f); fwrite(&sav->layout, 4, 1, f); int32_t num_vars = 1; fwrite(&num_vars, 4, 1, f); int32_t comp = 0; fwrite(&comp, 4, 1, f); int32_t weight = 0; fwrite(&weight, 4, 1, f); int32_t cases = 0; fwrite(&cases, 4, 1, f); double bias = 100.0; fwrite(&bias, 8, 1, f); fwrite("11 Nov 25 ", 1, 9, f); fwrite("00:00:00", 1, 8, f); char label[64] = "Mock File"; memset(label + 9, ' ', 55); fwrite(label, 1, 64, f); fwrite("\0\0\0", 1, 3, f); // Var int32_t tag = 2; fwrite(&tag, 4, 1, f); int32_t type = 0; fwrite(&type, 4, 1, f); int32_t has_label = 0; fwrite(&has_label, 4, 1, f); int32_t n_missing = 0; fwrite(&n_missing, 4, 1, f); uint8_t fmt[4] = {5, 8, 2, 0}; fwrite(fmt, 1, 4, f); fwrite(fmt, 1, 4, f); fwrite("VAR1 ", 1, 8, f); // Terminator int32_t term = 999; fwrite(&term, 4, 1, f); int32_t one = 1; fwrite(&one, 4, 1, f); fclose(f); } // Example: // int main() { // SavFile sav; // read_sav(&sav, "example.sav"); // print_properties(&sav); // write_sav(&sav, "output.sav"); // return 0; // } // ===== end task-636 .SAV ===== // ===== task-637 .SB [C] ===== #include #include #include #include #include // For leXXtoh if needed, but assuming little-endian host for simplicity typedef struct { uint32_t magic; uint32_t inode_count; uint32_t mod_time; uint32_t block_size; uint32_t frag_count; uint16_t compressor; uint16_t block_log; uint16_t flags; uint16_t id_count; uint16_t version_major; uint16_t version_minor; uint64_t root_inode; uint64_t bytes_used; uint64_t id_table; uint64_t xattr_table; uint64_t inode_table; uint64_t dir_table; uint64_t frag_table; uint64_t export_table; char *filepath; } SBFile; SBFile* sbfile_open(const char *filepath) { SBFile *sb = malloc(sizeof(SBFile)); if (!sb) return NULL; sb->filepath = strdup(filepath); FILE *f = fopen(filepath, "rb"); if (!f) { free(sb); return NULL; } uint8_t data[96]; if (fread(data, 1, 96, f) != 96) { fclose(f); free(sb); return NULL; } fclose(f); memcpy(&sb->magic, data + 0, 4); memcpy(&sb->inode_count, data + 4, 4); memcpy(&sb->mod_time, data + 8, 4); memcpy(&sb->block_size, data + 12, 4); memcpy(&sb->frag_count, data + 16, 4); memcpy(&sb->compressor, data + 20, 2); memcpy(&sb->block_log, data + 22, 2); memcpy(&sb->flags, data + 24, 2); memcpy(&sb->id_count, data + 26, 2); memcpy(&sb->version_major, data + 28, 2); memcpy(&sb->version_minor, data + 30, 2); memcpy(&sb->root_inode, data + 32, 8); memcpy(&sb->bytes_used, data + 40, 8); memcpy(&sb->id_table, data + 48, 8); memcpy(&sb->xattr_table, data + 56, 8); memcpy(&sb->inode_table, data + 64, 8); memcpy(&sb->dir_table, data + 72, 8); memcpy(&sb->frag_table, data + 80, 8); memcpy(&sb->export_table, data + 88, 8); // Assuming host is little-endian; otherwise, use le32toh, etc. return sb; } void sbfile_print_properties(SBFile *sb) { if (!sb) return; printf("magic: %u\n", sb->magic); printf("inode_count: %u\n", sb->inode_count); printf("mod_time: %u\n", sb->mod_time); printf("block_size: %u\n", sb->block_size); printf("frag_count: %u\n", sb->frag_count); printf("compressor: %hu\n", sb->compressor); printf("block_log: %hu\n", sb->block_log); printf("flags: %hu\n", sb->flags); printf("id_count: %hu\n", sb->id_count); printf("version_major: %hu\n", sb->version_major); printf("version_minor: %hu\n", sb->version_minor); printf("root_inode: %llu\n", (unsigned long long)sb->root_inode); printf("bytes_used: %llu\n", (unsigned long long)sb->bytes_used); printf("id_table: %llu\n", (unsigned long long)sb->id_table); printf("xattr_table: %llu\n", (unsigned long long)sb->xattr_table); printf("inode_table: %llu\n", (unsigned long long)sb->inode_table); printf("dir_table: %llu\n", (unsigned long long)sb->dir_table); printf("frag_table: %llu\n", (unsigned long long)sb->frag_table); printf("export_table: %llu\n", (unsigned long long)sb->export_table); } void sbfile_write(SBFile *sb, const char *new_filepath) { if (!sb) return; if (!new_filepath) new_filepath = sb->filepath; FILE *f_orig = fopen(sb->filepath, "rb"); if (!f_orig) return; fseek(f_orig, 0, SEEK_END); long size = ftell(f_orig); fseek(f_orig, 0, SEEK_SET); uint8_t *original_data = malloc(size); fread(original_data, 1, size, f_orig); fclose(f_orig); uint8_t superblock[96] = {0}; memcpy(superblock + 0, &sb->magic, 4); memcpy(superblock + 4, &sb->inode_count, 4); memcpy(superblock + 8, &sb->mod_time, 4); memcpy(superblock + 12, &sb->block_size, 4); memcpy(superblock + 16, &sb->frag_count, 4); memcpy(superblock + 20, &sb->compressor, 2); memcpy(superblock + 22, &sb->block_log, 2); memcpy(superblock + 24, &sb->flags, 2); memcpy(superblock + 26, &sb->id_count, 2); memcpy(superblock + 28, &sb->version_major, 2); memcpy(superblock + 30, &sb->version_minor, 2); memcpy(superblock + 32, &sb->root_inode, 8); memcpy(superblock + 40, &sb->bytes_used, 8); memcpy(superblock + 48, &sb->id_table, 8); memcpy(superblock + 56, &sb->xattr_table, 8); memcpy(superblock + 64, &sb->inode_table, 8); memcpy(superblock + 72, &sb->dir_table, 8); memcpy(superblock + 80, &sb->frag_table, 8); memcpy(superblock + 88, &sb->export_table, 8); FILE *f = fopen(new_filepath, "wb"); if (!f) { free(original_data); return; } fwrite(superblock, 1, 96, f); fwrite(original_data + 96, 1, size - 96, f); fclose(f); free(original_data); } void sbfile_close(SBFile *sb) { if (sb) { free(sb->filepath); free(sb); } } // Example usage: // int main() { // SBFile *sb = sbfile_open("example.sb"); // if (sb) { // sbfile_print_properties(sb); // sb->mod_time = 1234567890; // sbfile_write(sb, NULL); // sbfile_close(sb); // } // return 0; // } // ===== end task-637 .SB ===== // ===== task-638 .SB2 [C] ===== #include #include #include #include #include typedef struct { char* filepath; json_t* properties; // For other files: use a simple array or map, but for simplicity, assume we skip media for write or implement as needed // To keep simple, we'll only handle project.json for print, and copy other files for write } SB2Handler; SB2Handler* sb2_create(const char* filepath) { SB2Handler* handler = malloc(sizeof(SB2Handler)); handler->filepath = strdup(filepath); handler->properties = NULL; return handler; } void sb2_destroy(SB2Handler* handler) { if (handler->properties) json_decref(handler->properties); free(handler->filepath); free(handler); } int sb2_open_and_decode(SB2Handler* handler) { zip_t* za = zip_open(handler->filepath, ZIP_RDONLY, NULL); if (!za) return 1; zip_file_t* zf = zip_fopen(za, "project.json", 0); if (!zf) { zip_close(za); return 1; } zip_stat_t sb; zip_stat(za, "project.json", 0, &sb); char* buffer = malloc(sb.size + 1); zip_fread(zf, buffer, sb.size); buffer[sb.size] = '\0'; zip_fclose(zf); json_error_t error; handler->properties = json_loads(buffer, 0, &error); free(buffer); zip_close(za); return handler->properties ? 0 : 1; } void sb2_print_properties(SB2Handler* handler) { if (handler->properties) { char* dump = json_dumps(handler->properties, JSON_INDENT(4)); printf("%s\n", dump); free(dump); } else { printf("No properties loaded. Call sb2_open_and_decode first.\n"); } } int sb2_write(SB2Handler* handler, const char* new_filepath) { if (!handler->properties) { printf("No properties to write.\n"); return 1; } zip_t* src_za = zip_open(handler->filepath, ZIP_RDONLY, NULL); if (!src_za) return 1; zip_t* dest_za = zip_open(new_filepath, ZIP_CREATE | ZIP_TRUNCATE, NULL); if (!dest_za) { zip_close(src_za); return 1; } // Write project.json char* json_str = json_dumps(handler->properties, 0); zip_source_t* src = zip_source_buffer(dest_za, json_str, strlen(json_str), 0); zip_add(dest_za, "project.json", src); // Copy other files int num_entries = zip_get_num_entries(src_za, 0); for (int i = 0; i < num_entries; i++) { const char* name = zip_get_name(src_za, i, 0); if (strcmp(name, "project.json") == 0) continue; zip_file_t* zf = zip_fopen_index(src_za, i, 0); if (!zf) continue; zip_stat_t sb; zip_stat_index(src_za, i, 0, &sb); char* buffer = malloc(sb.size); zip_fread(zf, buffer, sb.size); zip_fclose(zf); zip_source_t* src_copy = zip_source_buffer(dest_za, buffer, sb.size, 1); zip_add(dest_za, name, src_copy); } free(json_str); zip_close(dest_za); zip_close(src_za); return 0; } // Example usage: // int main() { // SB2Handler* handler = sb2_create("example.sb2"); // if (sb2_open_and_decode(handler) == 0) { // sb2_print_properties(handler); // // Modify: json_object_set(handler->properties, "objName", json_string("Modified Stage")); // sb2_write(handler, "modified.sb2"); // } // sb2_destroy(handler); // return 0; // } // ===== end task-638 .SB2 ===== // ===== task-639 .SB3 [C++] ===== #include #include #include #include #include #include #include class SB3File { private: std::string filepath; std::map properties; std::vector> entries; std::vector data; public: SB3File(const std::string& fp) : filepath(fp) { read(); } void read() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { std::cerr << "Error opening file" << std::endl; return; } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(data.data(), size); // Find EOCD size_t eocdPos = size - 22; while (eocdPos > 0 && *reinterpret_cast(&data[eocdPos]) != 0x06054B50) { eocdPos--; } if (eocdPos == 0) { std::cerr << "Invalid SB3 (ZIP) file" << std::endl; return; } properties["End of central directory signature"] = *reinterpret_cast(&data[eocdPos]); properties["Number of this disk"] = *reinterpret_cast(&data[eocdPos + 4]); properties["Number of the disk with the start of the central directory"] = *reinterpret_cast(&data[eocdPos + 6]); properties["Total number of central directory entries on this disk"] = *reinterpret_cast(&data[eocdPos + 8]); properties["Total number of central directory entries"] = *reinterpret_cast(&data[eocdPos + 10]); properties["Size of the central directory"] = *reinterpret_cast(&data[eocdPos + 12]); properties["Offset of start of central directory"] = *reinterpret_cast(&data[eocdPos + 16]); uint16_t commentLen = *reinterpret_cast(&data[eocdPos + 20]); properties["ZIP file comment length"] = commentLen; // Comment as string (add to map as uint64_t cast or separate string map if needed) // Parse central directory (similar logic) size_t cdPos = properties["Offset of start of central directory"]; for (size_t i = 0; i < properties["Total number of central directory entries"]; ++i) { std::map entry; entry["Central directory file header signature"] = *reinterpret_cast(&data[cdPos]); entry["Version made by"] = *reinterpret_cast(&data[cdPos + 4]); // ... (add all) uint16_t fnLen = *reinterpret_cast(&data[cdPos + 28]); uint16_t extraLen = *reinterpret_cast(&data[cdPos + 30]); uint16_t commLen = *reinterpret_cast(&data[cdPos + 32]); // File name as string (handle separately) cdPos += 46 + fnLen + extraLen + commLen; size_t localPos = entry["Relative offset of local file header"]; entry["Local file header signature"] = *reinterpret_cast(&data[localPos]); // ... entries.push_back(entry); } } void printProperties() { std::cout << "Global Properties:" << std::endl; for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } for (size_t i = 0; i < entries.size(); ++i) { std::cout << "\nEntry " << i << " Properties:" << std::endl; for (const auto& e : entries[i]) { std::cout << e.first << ": " << e.second << std::endl; } } } void write(const std::string& newFilepath = "") { std::string outPath = newFilepath.empty() ? filepath : newFilepath; std::ofstream out(outPath, std::ios::binary); out.write(data.data(), data.size()); std::cout << "Wrote to " << outPath << std::endl; } }; // Example usage: // int main() { // SB3File sb3("example.sb3"); // sb3.printProperties(); // sb3.write("modified.sb3"); // return 0; // } // ===== end task-639 .SB3 ===== // ===== task-640 .SBH [C] ===== #include #include #include #include #include typedef struct { char** includes; int num_includes; char* option_base; struct { char* name; char* dimensions; char* type; int line; } *global_vars; int num_global_vars; struct { char* name; char* type; char* value; int line; } *constants; int num_constants; struct { char* name; struct { char* field_name; char* field_type; } *fields; int num_fields; int line; } *udts; int num_udts; struct { char* decl_type; // Sub or Function char* name; char* lib; char* params; char* return_type; int line; } *declarations; int num_declarations; } SBHProperties; SBHParser* sbh_create() { SBHProperties* props = malloc(sizeof(SBHProperties)); props->includes = NULL; props->num_includes = 0; props->option_base = NULL; props->global_vars = NULL; props->num_global_vars = 0; props->constants = NULL; props->num_constants = 0; props->udts = NULL; props->num_udts = 0; props->declarations = NULL; props->num_declarations = 0; return props; } void sbh_free(SBHProperties* props) { // Free all allocated memory (omitted for brevity; implement as needed) free(props); } void sbh_read_and_parse(SBHProperties* props, const char* filename) { FILE* f = fopen(filename, "r"); if (!f) { perror("File open error"); return; } fseek(f, 0, SEEK_END); long len = ftell(f); fseek(f, 0, SEEK_SET); char* content = malloc(len + 1); fread(content, 1, len, f); content[len] = '\0'; fclose(f); _parse(content, props); free(content); _print_properties(props); } void _parse(char* content, SBHProperties* props) { char* line; char* saveptr; int line_num = 1; regex_t include_regex, option_regex, var_regex, const_regex, type_regex, field_regex, decl_regex; regcomp(&include_regex, "'\\$Include\\s+[\"']([^\"']*)[\"']", REG_ICASE); regcomp(&option_regex, "Option Base\\s+(\\d)", REG_ICASE); regcomp(&var_regex, "(Global|Dim)\\s+([^(\\s]+)(?:\\s*\\(([ ^\\)]+)\\))?\\s*(?:As\\s+([^\\s,]+))?", REG_ICASE); regcomp(&const_regex, "Const\\s+([^\\s=]+)\\s*(?:As\\s+([^\\s=]+))?\\s*=\\s*(.*)", REG_ICASE); regcomp(&decl_regex, "Declare\\s+(Sub|Function)\\s+([^\\s\\(]+)\\s*(?:Lib\\s+\"([^\"]+)\"|BasicLib\\s+\"([^\"]+)\")?\\s*\\(([^\\)]*)\\)\\s*(?:As\\s+([^\\s;]+))?", REG_ICASE); // Simplified; field and type handled in loop char* ptr = strtok_r(content, "\n", &saveptr); bool in_udt = false; SBHProperties_udt current_udt = {0}; while (ptr) { // Remove comments char* comment_pos = strchr(ptr, '\''); if (comment_pos) *comment_pos = '\0'; char line_copy[1024]; strncpy(line_copy, ptr, sizeof(line_copy) - 1); line_copy[sizeof(line_copy) - 1] = '\0'; char* trimmed = line_copy; while (*trimmed == ' ' || *trimmed == '\t') trimmed++; char* end = trimmed + strlen(trimmed) - 1; while (end > trimmed && (*end == ' ' || *end == '\t')) *end-- = '\0'; if (strlen(trimmed) == 0) { ptr = strtok_r(NULL, "\n", &saveptr); line_num++; continue; } regmatch_t matches[10]; if (regexec(&include_regex, trimmed, 10, matches, 0) == 0) { // Add include (allocate and copy) props->num_includes++; props->includes = realloc(props->includes, props->num_includes * sizeof(char*)); props->includes[props->num_includes - 1] = malloc(256); regexec(&include_regex, trimmed, 10, matches, 0); // Extract group 1 (simplified extraction) // ... (use sniprintf for group) } // Similar for other regex matches; add to arrays with realloc // For UDT: if strstr(trimmed, "Type ") == trimmed, in_udt = true; current_udt.name = ... // If "End Type", add to udts // For field: if in_udt and strstr(trimmed, " As "), parse field // Note: Full regex group extraction omitted for brevity; use regoff for positions ptr = strtok_r(NULL, "\n", &saveptr); line_num++; } regfree(&include_regex); // Free other regex } void _print_properties(SBHProperties* props) { // Print as structured text (JSON-like) printf("{\n"); printf(" \"includes\": %d,\n", props->num_includes); // ... print each category printf("}\n"); } void sbh_write(SBHProperties* props, const char* filename) { FILE* f = fopen(filename, "w"); if (!f) return; if (props->option_base) fprintf(f, "Option Base %s\n", props->option_base); // Similar for other categories; fprintf each fclose(f); } // Usage // SBHProperties* props = sbh_create(); // sbh_read_and_parse(props, "sample.sbh"); // sbh_write(props, "output.sbh"); // sbh_free(props); // ===== end task-640 .SBH ===== // ===== task-641 .SBV [C] ===== #include #include #include #include // For regex; compile with -lregex if needed, or use simple string checks #define MAX_LINE 256 #define MAX_ENTRIES 1000 typedef struct { char start[20]; char end[20]; char **text; int text_count; char *speaker; } Entry; typedef struct { char *file_path; Entry *entries; int num_entries; int max_entries; } SBVHandler; SBVHandler *sbv_create(const char *file_path) { SBVHandler *handler = malloc(sizeof(SBVHandler)); handler->file_path = strdup(file_path); handler->entries = malloc(MAX_ENTRIES * sizeof(Entry)); handler->num_entries = 0; handler->max_entries = MAX_ENTRIES; return handler; } void sbv_free(SBVHandler *handler) { for (int i = 0; i < handler->num_entries; i++) { Entry *e = &handler->entries[i]; for (int j = 0; j < e->text_count; j++) { free(e->text[j]); } free(e->text); free(e->speaker); } free(handler->entries); free(handler->file_path); free(handler); } int is_timestamp(const char *line) { // Simple check for HH:MM:SS.mmm,HH:MM:SS.mmm int h1, m1, s1, ms1, h2, m2, s2, ms2; if (sscanf(line, "%d:%d:%d.%d,%d:%d:%d.%d", &h1, &m1, &s1, &ms1, &h2, &m2, &s2, &ms2) == 8) { return 1; } return 0; } void sbv_read(SBVHandler *handler) { FILE *f = fopen(handler->file_path, "r"); if (!f) return; char line[MAX_LINE]; Entry *current = NULL; int in_text = 0; while (fgets(line, MAX_LINE, f)) { // Remove \n line[strcspn(line, "\r\n")] = 0; char *trimmed = line; while (*trimmed == ' ') trimmed++; // Simple trim if (is_timestamp(line)) { if (current) { handler->entries[handler->num_entries++] = *current; } current = malloc(sizeof(Entry)); sscanf(line, "%[^,],%s", current->start, current->end); current->text = malloc(10 * sizeof(char*)); // Assume max 10 lines current->text_count = 0; current->speaker = NULL; in_text = 1; } else if (in_text && strlen(trimmed) == 0) { if (current) { handler->entries[handler->num_entries++] = *current; free(current); current = NULL; } in_text = 0; } else if (in_text && current && strlen(line) > 0) { char *text_line = strdup(line); if (current->text_count == 0 && strncmp(text_line, ">> ", 3) == 0) { // Simple speaker parse: >> NAME: text char *colon = strchr(text_line + 3, ':'); if (colon) { *colon = 0; current->speaker = strdup(text_line + 3); char *text_start = colon + 2; // Skip ": " free(text_line); text_line = strdup(text_start); } } current->text[current->text_count++] = text_line; } } if (current) { handler->entries[handler->num_entries++] = *current; free(current); } fclose(f); } void sbv_print_properties(SBVHandler *handler) { printf("Number of subtitle entries: %d\n\n", handler->num_entries); for (int i = 0; i < handler->num_entries; i++) { Entry *e = &handler->entries[i]; printf("Entry %d:\n", i + 1); printf(" Timestamp: %s -- %s\n", e->start, e->end); if (e->speaker) { printf(" Speaker: %s\n", e->speaker); } printf(" Text:\n"); for (int j = 0; j < e->text_count; j++) { printf(" %s\n", e->text[j]); } printf("\n"); } } void sbv_write(SBVHandler *handler, const char *output_path) { FILE *f = fopen(output_path, "w"); if (!f) return; for (int i = 0; i < handler->num_entries; i++) { Entry *e = &handler->entries[i]; fprintf(f, "%s,%s\n", e->start, e->end); if (e->speaker) { fprintf(f, ">> %s: %s\n", e->speaker, e->text[0]); for (int j = 1; j < e->text_count; j++) { fprintf(f, "%s\n", e->text[j]); } } else { for (int j = 0; j < e->text_count; j++) { fprintf(f, "%s\n", e->text[j]); } } fprintf(f, "\n"); } fclose(f); } int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "Usage: %s [output.sbv]\n", argv[0]); return 1; } SBVHandler *handler = sbv_create(argv[1]); sbv_read(handler); sbv_print_properties(handler); if (argc > 2) { sbv_write(handler, argv[2]); printf("Written to %s\n", argv[2]); } sbv_free(handler); return 0; } // ===== end task-641 .SBV ===== // ===== task-642 .SBX [C] ===== #include #include #include #include typedef struct { uint8_t signature[3]; // 'SBx' uint8_t version; uint16_t crc; uint8_t uid[6]; uint32_t seq; } SBXHeader; // 16 bytes // Full parser/write functions follow the exact layout from the spec // CRC16-CCITT implementation: uint16_t crc16_ccitt(const uint8_t *data, size_t len, uint8_t init) { uint16_t crc = init << 8; for (size_t i = 0; i < len; i++) { crc ^= (data[i] << 8); for (int j = 0; j < 8; j++) crc = (crc & 0x8000) ? (crc << 1) ^ 0x1021 : crc << 1; } return crc; } // load/parse/print/save functions mirror Python version exactly (big-endian via htobe32 etc.) // ===== end task-642 .SBX ===== // ===== task-643 .SCALA [C] ===== #include #include #include #include #define MAX_LINES 10000 #define MAX_LINE_LEN 256 typedef struct { char description[MAX_LINE_LEN]; int note_count; char** pitch_values; // Array of strings; type inferred in print int* pitch_types; // 0: ratio, 1: cents int capacity; } ScalaFile; ScalaFile* scala_new() { ScalaFile* sf = malloc(sizeof(ScalaFile)); sf->description[0] = '\0'; sf->note_count = 0; sf->pitch_values = NULL; sf->pitch_types = NULL; sf->capacity = 0; return sf; } void scala_free(ScalaFile* sf) { if (sf) { for (int i = 0; i < sf->note_count; i++) { free(sf->pitch_values[i]); } free(sf->pitch_values); free(sf->pitch_types); free(sf); } } int read_line(FILE* fp, char* line, int max_len) { if (!fgets(line, max_len, fp)) return 0; // Trim trailing newline and whitespace int len = strlen(line); if (len > 0 && line[len-1] == '\n') line[--len] = '\0'; while (len > 0 && isspace(line[len-1])) line[--len] = '\0'; // Trim leading whitespace char* start = line; while (isspace(*start)) start++; memmove(line, start, strlen(start) + 1); return strlen(line) > 0; } void scala_read(ScalaFile* sf, const char* filepath) { FILE* fp = fopen(filepath, "r"); if (!fp) { fprintf(stderr, "File %s not found.\n", filepath); return; } char line[MAX_LINE_LEN]; char** non_comments = malloc(MAX_LINES * sizeof(char*)); int nc_count = 0; while (read_line(fp, line, MAX_LINE_LEN)) { if (!line[0] || line[0] == '!') continue; non_comments[nc_count] = strdup(line); nc_count++; if (nc_count >= MAX_LINES) break; } fclose(fp); if (nc_count < 2) { fprintf(stderr, "Invalid file: Insufficient non-comment lines.\n"); goto cleanup; } strncpy(sf->description, non_comments[0], MAX_LINE_LEN - 1); sf->description[MAX_LINE_LEN - 1] = '\0'; sf->note_count = atoi(non_comments[1]); if (sf->note_count < 0 || nc_count < 2 + sf->note_count) { fprintf(stderr, "Invalid pitch values or count.\n"); goto cleanup; } sf->capacity = sf->note_count; sf->pitch_values = malloc(sf->note_count * sizeof(char*)); sf->pitch_types = malloc(sf->note_count * sizeof(int)); for (int i = 0; i < sf->note_count; i++) { char* pitch_line = non_comments[2 + i]; char* space_pos = strchr(pitch_line, ' '); if (space_pos) *space_pos = '\0'; // Truncate to first token sf->pitch_values[i] = strdup(pitch_line); if (strchr(pitch_line, '/')) { sf->pitch_types[i] = 0; // ratio } else if (strchr(pitch_line, '.')) { sf->pitch_types[i] = 1; // cents } else { sf->pitch_types[i] = 0; // Append /1 if needed size_t len = strlen(pitch_line); char* new_val = malloc(len + 3); strcpy(new_val, pitch_line); strcat(new_val, "/1"); free(sf->pitch_values[i]); sf->pitch_values[i] = new_val; } } printf("File read successfully.\n"); cleanup: for (int i = 0; i < nc_count; i++) free(non_comments[i]); free(non_comments); } void scala_write(ScalaFile* sf, const char* filepath) { FILE* fp = fopen(filepath, "w"); if (!fp) { fprintf(stderr, "Failed to write to %s.\n", filepath); return; } fprintf(fp, "! Generated .SCALA file\n"); fprintf(fp, "%s\n", sf->description); fprintf(fp, "%d\n", sf->note_count); for (int i = 0; i < sf->note_count; i++) { fprintf(fp, "%s\n", sf->pitch_values[i]); } fclose(fp); printf("File written to %s.\n", filepath); } void scala_print_properties(ScalaFile* sf) { printf("Description: %s\n", sf->description); printf("Number of Notes: %d\n", sf->note_count); printf("Pitch Values:\n"); for (int i = 0; i < sf->note_count; i++) { const char* type_str = sf->pitch_types[i] ? "cents" : "ratio"; printf(" Degree %d: %s (%s)\n", i + 1, sf->pitch_values[i], type_str); } } int main(int argc, char* argv[]) { if (argc < 2) { printf("Usage: %s [output.scl]\n", argv[0]); return 1; } ScalaFile* sf = scala_new(); scala_read(sf, argv[1]); scala_print_properties(sf); if (argc > 2) { scala_write(sf, argv[2]); } scala_free(sf); return 0; } // ===== end task-643 .SCALA ===== // ===== task-644 .SCM [C] ===== #include #include #include #include #include typedef uint32_t u32; typedef uint16_t u16; typedef uint64_t u64; u32 crypt_table[0x500]; void prepare_crypt_table() { u32 seed = 0x00100001, index1 = 0; while (index1 < 0x100) { u32 index2 = index1; for (int i = 0; i < 5; i++, index2 += 0x100) { seed = (seed * 125 + 3) % 0x2AAAAB; u32 temp1 = (seed & 0xFFFF) << 16; seed = (seed * 125 + 3) % 0x2AAAAB; u32 temp2 = seed & 0xFFFF; crypt_table[index2] = temp1 | temp2; } index1++; } } u32 hash_string(const char *s, u32 hash_type) { u32 seed1 = 0x7FED7FED, seed2 = 0xEEEEEEEE; for (int i = 0; s[i]; i++) { int ch = tolower(s[i]); seed1 = crypt_table[(hash_type << 8) + ch] ^ (seed1 + seed2); seed2 = ch + seed1 + seed2 + (seed2 << 5) + 3; } return seed1; } void decrypt_block(uint8_t *data, size_t length, u32 key) { u32 seed = 0xEEEEEEEE; for (size_t i = 0; i < length; i += 4) { seed += crypt_table[0x400 + (key & 0xFF)]; u32 ch = *(u32 *)(data + i) ^ (key + seed); key = ((~key << 21) + 0x11111111) | (key >> 11); seed = ch + seed + (seed << 5) + 3; *(u32 *)(data + i) = ch; } } uint8_t *read_scm(const char *filename, size_t *size) { FILE *f = fopen(filename, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); *size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(*size); fread(data, 1, *size, f); fclose(f); return data; } void print_properties(uint8_t *data, size_t size) { u32 offset = 0; u32 magic = *(u32 *)(data + offset); if (magic != 0x1A1A514D) { fprintf(stderr, "Invalid MPQ magic\n"); return; } u32 header_size = *(u32 *)(data + offset + 4); u32 archive_size = *(u32 *)(data + offset + 8); u16 format_version = *(u16 *)(data + offset + 12); u16 block_size = *(u16 *)(data + offset + 14); u32 hash_table_pos = *(u32 *)(data + offset + 16); u32 block_table_pos = *(u32 *)(data + offset + 20); u32 hash_table_size = *(u32 *)(data + offset + 24); u32 block_table_size = *(u32 *)(data + offset + 28); printf("MPQ Header:\n"); printf(" magic: %u\n", magic); printf(" header_size: %u\n", header_size); printf(" archive_size: %u\n", archive_size); printf(" format_version: %u\n", format_version); printf(" block_size: %u\n", block_size); printf(" hash_table_pos: %u\n", hash_table_pos); printf(" block_table_pos: %u\n", block_table_pos); printf(" hash_table_size: %u\n", hash_table_size); printf(" block_table_size: %u\n", block_table_size); u32 hash_key = hash_string("(hash table)", 0); u32 block_key = hash_string("(block table)", 0); decrypt_block(data + hash_table_pos, hash_table_size * 16, hash_key); decrypt_block(data + block_table_pos, block_table_size * 16, block_key); printf("\nHash Table Entries:\n"); for (u32 i = 0; i < hash_table_size; i++) { u32 off = hash_table_pos + i * 16; u32 name_hash1 = *(u32 *)(data + off); u32 name_hash2 = *(u32 *)(data + off + 4); u16 locale = *(u16 *)(data + off + 8); u16 platform = *(u16 *)(data + off + 10); u32 block_index = *(u32 *)(data + off + 12); if (block_index != 0xFFFFFFFF) { printf(" Entry %u: name_hash1=%u, name_hash2=%u, locale=%u, platform=%u, block_index=%u\n", i, name_hash1, name_hash2, locale, platform, block_index); } } printf("\nBlock Table Entries:\n"); for (u32 i = 0; i < block_table_size; i++) { u32 off = block_table_pos + i * 16; u32 file_pos = *(u32 *)(data + off); u32 comp_size = *(u32 *)(data + off + 4); u32 uncomp_size = *(u32 *)(data + off + 8); u32 flags = *(u32 *)(data + off + 12); printf(" Entry %u: file_position=%u, compressed_size=%u, uncompressed_size=%u, flags=0x%X\n", i, file_pos, comp_size, uncomp_size, flags); } if (format_version >= 1) { u32 ext_offset = offset + header_size; u64 ext_block_pos = *(u64 *)(data + ext_offset); u16 hash_pos_high = *(u16 *)(data + ext_offset + 8); u16 block_pos_high = *(u16 *)(data + ext_offset + 10); printf("Extended Header:\n"); printf(" ext_block_table_pos: %lu\n", ext_block_pos); printf(" hash_table_pos_high: %u\n", hash_pos_high); printf(" block_table_pos_high: %u\n", block_pos_high); } } void write_scm(const uint8_t *data, size_t size, const char *output) { FILE *f = fopen(output, "wb"); if (f) { fwrite(data, 1, size, f); fclose(f); } } int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "Usage: %s [output.scm]\n", argv[0]); return 1; } prepare_crypt_table(); size_t size; uint8_t *data = read_scm(argv[1], &size); if (data) { print_properties(data, size); if (argc > 2) { write_scm(data, size, argv[2]); printf("Written to %s\n", argv[2]); } free(data); } return 0; } // ===== end task-644 .SCM ===== // ===== task-645 .SCR [C] ===== #include #include #include #define FILE_SIZE 6912 #define BITMAP_SIZE 6144 #define BITMAP_OFFSET 0 #define ATTR_OFFSET 6144 #define WIDTH 256 #define HEIGHT 192 #define BYTES_PER_LINE 32 #define ATTR_COLS 32 #define ATTR_ROWS 24 unsigned char *data = NULL; int load_scr(const char *filepath) { FILE *fp = fopen(filepath, "rb"); if (!fp) { perror("File not found"); return 0; } data = (unsigned char *)malloc(FILE_SIZE); if (fread(data, 1, FILE_SIZE, fp) != FILE_SIZE) { free(data); data = NULL; fclose(fp); fprintf(stderr, "Invalid .SCR: Expected %d bytes\n", FILE_SIZE); return 0; } fclose(fp); return 1; } void print_properties() { if (!data) { printf("No data loaded.\n"); return; } printf("ZX Spectrum .SCR Properties:\n"); printf("File Size: %d bytes (valid)\n", FILE_SIZE); printf("Bitmap Offset: %d bytes\n", BITMAP_OFFSET); printf("Bitmap Size: %d bytes\n", BITMAP_SIZE); printf("Pixel Width: %d pixels\n", WIDTH); printf("Pixel Height: %d pixels\n", HEIGHT); printf("Bits per Pixel: 1 bit\n"); printf("Bytes per Scanline: %d bytes\n", BYTES_PER_LINE); printf("Attribute Offset: %d bytes\n", ATTR_OFFSET); printf("Attribute Size: %d bytes\n", FILE_SIZE - ATTR_OFFSET); printf("Attribute Columns: %d\n", ATTR_COLS); printf("Attribute Rows: %d\n", ATTR_ROWS); printf("Palette Size: 8 base colors (15 total with bright)\n"); printf("Compression: None\n"); printf("Header Presence: None\n"); } void write_scr(const char *output_path) { FILE *fp = fopen(output_path, "wb"); if (!fp) { perror("Write failed"); return; } // Blank data unsigned char blank[FILE_SIZE]; memset(blank, 0, FILE_SIZE); if (fwrite(blank, 1, FILE_SIZE, fp) != FILE_SIZE) { perror("Write incomplete"); } else { printf("Wrote valid .SCR to %s\n", output_path); } fclose(fp); } int main(int argc, char *argv[]) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } if (!load_scr(argv[1])) { return 1; } print_properties(); // Example write: write_scr("blank.scr"); free(data); return 0; } // ===== end task-645 .SCR ===== // ===== task-646 .SCSS [C] ===== #include #include #include #include #include #include #define MAX_LINE 1024 #define MAX_CONTENT (1024 * 1024) // 1MB buffer typedef struct { char *filename; long size; int line_count; int char_count; int var_count; int mixin_count; int include_count; int at_rule_count; } ScssProperties; void compute_properties(char *content, ScssProperties *props) { char *line = strtok(content, "\n"); props->line_count = 0; props->char_count = strlen(content); regex_t var_re, mixin_re, include_re, at_rule_re; regcomp(&var_re, "^\\s*\\$[a-zA-Z_-]+:", REG_EXTENDED | REG_NEWLINE); regcomp(&mixin_re, "@mixin\\s+[a-zA-Z_-]+", REG_EXTENDED); regcomp(&include_re, "@include\\s+[a-zA-Z_-]+", REG_EXTENDED); regcomp(&at_rule_re, "^@[a-z-]+", REG_EXTENDED | REG_NEWLINE); props->var_count = 0; regmatch_t match; while (regexec(&var_re, content, 0, &match, 0) == 0) { props->var_count++; content += match.rm_eo; } // Similar for others (simplified; repeat regexec loop) props->mixin_count = 0; // Implement regexec loop analogously props->include_count = 0; props->at_rule_count = 0; regfree(&var_re); regfree(&mixin_re); regfree(&include_re); regfree(&at_rule_re); } void print_properties(ScssProperties *props) { printf("File Name: %s\n", props->filename); printf("File Size (bytes): %ld\n", props->size); printf("Line Count: %d\n", props->line_count); printf("Character Count: %d\n", props->char_count); printf("Encoding: UTF-8\n"); printf("Variable Declarations: %d\n", props->var_count); printf("Mixin Definitions: %d\n", props->mixin_count); printf("Mixin Includes: %d\n", props->include_count); printf("At-Rules: %d\n", props->at_rule_count); } int main(int argc, char *argv[]) { setlocale(LC_ALL, ""); if (argc != 2 || !strstr(argv[1], ".scss")) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } FILE *file = fopen(argv[1], "r"); if (!file) { perror("Error opening file"); return 1; } fseek(file, 0, SEEK_END); long size = ftell(file); fseek(file, 0, SEEK_SET); char *content = malloc(size + 1); fread(content, 1, size, file); content[size] = '\0'; fclose(file); ScssProperties props = { .filename = argv[1], .size = size }; compute_properties(content, &props); print_properties(&props); // Write back (echo) FILE *out = fopen("output.scss", "w"); if (out) { fputs(content, out); fclose(out); printf("Written to: output.scss\n"); } free(content); return 0; } // ===== end task-646 .SCSS ===== // ===== task-647 .SC7 [C] ===== #include #include #include #include #include #include typedef struct { char *filename; struct archive *a; int num_files; // Simplified properties struct; extend as needed } SD7Decoder; void extract_properties(SD7Decoder *decoder) { struct archive_entry *entry; decoder->num_files = 0; while (archive_read_next_header(decoder->a, &entry) == ARCHIVE_OK) { decoder->num_files++; const char *name = archive_entry_pathname(entry); size_t size = archive_entry_size(entry); time_t mtime = archive_entry_mtime(entry); printf("File: %s, Size: %zu, MTime: %s\n", name, size, ctime(&mtime)); // CRC and attributes via archive_entry_* functions la_int64 crc = archive_entry_crc32big(entry); if (crc != 0) printf(" CRC: 0x%llx\n", crc); mode_t attrs = archive_entry_mode(entry); if (attrs & S_IFDIR) printf(" Type: Directory\n"); } printf("Archive Version: 0.4\nNum Folders: 1 (typical)\nCompression: LZMA2\n"); } int open_and_decode(SD7Decoder *decoder) { decoder->a = archive_read_new(); archive_read_support_format_7zip(decoder->a); if (archive_read_open_filename(decoder->a, decoder->filename, 10240) != ARCHIVE_OK) { fprintf(stderr, "Error opening %s: %s\n", decoder->filename, archive_error_string(decoder->a)); return 0; } extract_properties(decoder); return 1; } void write_archive(const char *output_filename) { struct archive *out_a = archive_write_new(); archive_write_support_format_7zip(out_a); archive_write_open_filename(out_a, output_filename); // Example entry; copy from input in full impl struct archive_entry *entry = archive_entry_new(); archive_entry_set_pathname(entry, "dummy.txt"); archive_entry_set_size(entry, 10); archive_write_header(out_a, entry); archive_write_data(out_a, "Dummy", 5); archive_entry_free(entry); archive_write_close(out_a); archive_write_free(out_a); printf("Written to %s\n", output_filename); } int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } SD7Decoder decoder = { argv[1], NULL, 0 }; if (open_and_decode(&decoder)) { // write_archive("output.sd7"); } archive_read_free(decoder.a); return 0; } // ===== end task-647 .SC7 ===== // ===== task-648 .SDF [C] ===== #include #include #include #define MAX_LINE 256 #define MAX_RECORDS 1000 #define MAX_FIELDS 100 typedef struct { char title[81]; char timestamp[81]; char comment[81]; int atoms_count; int bonds_count; struct { char element[4]; double x, y, z; } atoms[1000]; // Assume max 1000 atoms int atoms_num; struct { int atom1, atom2, type; } bonds[1000]; // Assume max 1000 bonds int bonds_num; char data_fields[MAX_FIELDS][81]; // Key-value pairs (simplified) int fields_num; } Record; typedef struct { char *filepath; char *content; Record records[MAX_RECORDS]; int records_num; } SDFHandler; SDFHandler *sdf_handler_new(const char *filepath) { SDFHandler *h = malloc(sizeof(SDFHandler)); h->filepath = strdup(filepath); h->content = NULL; h->records_num = 0; return h; } void sdf_handler_free(SDFHandler *h) { free(h->filepath); free(h->content); free(h); } int sdf_handler_read(SDFHandler *h) { FILE *f = fopen(h->filepath, "r"); if (!f) return -1; fseek(f, 0, SEEK_END); long len = ftell(f); fseek(f, 0, SEEK_SET); h->content = malloc(len + 1); fread(h->content, 1, len, f); h->content[len] = '\0'; fclose(f); char *ptr = h->content; char *next = strstr(ptr, "$$$$"); int rec_idx = 0; while (next && rec_idx < MAX_RECORDS) { *next = '\0'; // Null-terminate record if (strlen(ptr) > 0) { extract_properties(&h->records[rec_idx], ptr); rec_idx++; } ptr = next + 4; next = strstr(ptr, "$$$$"); } h->records_num = rec_idx; return rec_idx; } void extract_properties(Record *rec, char *content) { char *lines[MAX_LINE]; int line_count = 0; char *saveptr; char *line = strtok_r(content, "\n\r", &saveptr); while (line && line_count < MAX_LINE) { lines[line_count++] = line; line = strtok_r(NULL, "\n\r", &saveptr); } // Header if (line_count > 0) strncpy(rec->title, lines[0], 80); if (line_count > 1) strncpy(rec->timestamp, lines[1], 80); if (line_count > 2) strncpy(rec->comment, lines[2], 80); // Counts (simplified) if (line_count > 3) { sscanf(lines[3], "%d %d", &rec->atoms_count, &rec->bonds_count); } // Atoms (basic) int atom_start = 4; rec->atoms_num = 0; for (int i = 0; i < rec->atoms_count && i < 1000 && atom_start + i < line_count; i++) { sscanf(lines[atom_start + i], "%lf %lf %lf %3s", &rec->atoms[i].x, &rec->atoms[i].y, &rec->atoms[i].z, rec->atoms[i].element); rec->atoms_num++; } // Bonds (basic) int bond_start = atom_start + rec->atoms_count; rec->bonds_num = 0; for (int i = 0; i < rec->bonds_count && i < 1000 && bond_start + i < line_count; i++) { sscanf(lines[bond_start + i], "%d %d %d", &rec->bonds[i].atom1, &rec->bonds[i].atom2, &rec->bonds[i].type); rec->bonds_num++; } // Data fields (simplified, assume keys in fields) rec->fields_num = 0; char *key_start = strstr(content, "> <"); while (key_start && rec->fields_num < MAX_FIELDS) { char *key_end = strchr(key_start, '>'); if (key_end) { strncpy(rec->data_fields[rec->fields_num], key_start + 3, key_end - key_start - 3); // Rough extract rec->fields_num++; } key_start = strstr(key_end ? key_end + 1 : key_start + 1, "> <"); } } void sdf_handler_print_properties(SDFHandler *h) { printf("Number of records: %d\n\n", h->records_num); for (int idx = 0; idx < h->records_num; idx++) { Record *rec = &h->records[idx]; printf("--- Record %d ---\n", idx + 1); printf("Title: %s\n", rec->title); printf("Atoms count: %d, Bonds count: %d\n", rec->atoms_count, rec->bonds_count); printf("Sample Atoms (first 3):\n"); for (int j = 0; j < 3 && j < rec->atoms_num; j++) { printf(" %s: (%.4f, %.4f, %.4f)\n", rec->atoms[j].element, rec->atoms[j].x, rec->atoms[j].y, rec->atoms[j].z); } printf("Sample Bonds (first 3):\n"); for (int j = 0; j < 3 && j < rec->bonds_num; j++) { printf(" %d-%d (type %d)\n", rec->bonds[j].atom1, rec->bonds[j].atom2, rec->bonds[j].type); } printf("Data Fields:\n"); for (int j = 0; j < rec->fields_num; j++) { printf(" %s\n", rec->data_fields[j]); } printf("\n"); } } void sdf_handler_write(SDFHandler *h, const char *output_path) { FILE *f = fopen(output_path, "w"); if (!f) return; for (int i = 0; i < h->records_num; i++) { Record *rec = &h->records[i]; fprintf(f, "%s\n", rec->title); fprintf(f, "%s\n", rec->timestamp); fprintf(f, "%s\n", rec->comment); fprintf(f, "%03d%03d000 0 0999 V2000\n", rec->atoms_count, rec->bonds_count); for (int j = 0; j < rec->atoms_num; j++) { fprintf(f, "%10.4f%10.4f%10.4f %-3s 0 0 0 0 0 0 0 0 0 0 0 0\n", rec->atoms[j].x, rec->atoms[j].y, rec->atoms[j].z, rec->atoms[j].element); } for (int j = 0; j < rec->bonds_num; j++) { fprintf(f, "%3d%3d%3d 0 0 0 0\n", rec->bonds[j].atom1, rec->bonds[j].atom2, rec->bonds[j].type); } fprintf(f, "M END\n"); for (int j = 0; j < rec->fields_num; j++) { fprintf(f, "> <%s>\n\n", rec->data_fields[j]); // Values omitted for simplicity } fprintf(f, "$$\n"); } fclose(f); } // Example usage: // int main() { // SDFHandler *h = sdf_handler_new("example.sdf"); // sdf_handler_read(h); // sdf_handler_print_properties(h); // sdf_handler_write(h, "output.sdf"); // sdf_handler_free(h); // return 0; // } // ===== end task-648 .SDF ===== // ===== task-649 .SDNN [C] ===== #include #include #include #include typedef struct { char* filepath; uint8_t* data; size_t data_size; struct { uint32_t version; uint32_t declared_size; } properties; } SDNNFile; void sdnn_read(SDNNFile* file) { FILE* fp = fopen(file->filepath, "rb"); if (!fp) { printf("Error: File not found.\n"); return; } fseek(fp, 0, SEEK_END); file->data_size = ftell(fp); fseek(fp, 0, SEEK_SET); file->data = malloc(file->data_size); fread(file->data, 1, file->data_size, fp); fclose(fp); // Placeholder parse if (file->data_size >= 8) { file->properties.version = (file->data[0] << 24) | (file->data[1] << 16) | (file->data[2] << 8) | file->data[3]; file->properties.declared_size = (file->data[4] << 24) | (file->data[5] << 16) | (file->data[6] << 8) | file->data[7]; } else { printf(" error: File too short for header\n"); } sdnn_print_properties(file); } void sdnn_print_properties(SDNNFile* file) { printf("SDNN File Properties:\n"); printf(" version: %u\n", file->properties.version); printf(" declared_size: %u\n", file->properties.declared_size); printf(" Raw size: %zu bytes\n", file->data_size); } void sdnn_write(SDNNFile* file, const char* output_path) { if (!file->data) { printf("Error: No data to write.\n"); return; } FILE* fp = fopen(output_path, "wb"); if (fp) { fwrite(file->data, 1, file->data_size, fp); fclose(fp); printf("Written to %s\n", output_path); } else { printf("Write error.\n"); } } void sdnn_free(SDNNFile* file) { free(file->data); free(file->filepath); } int main() { SDNNFile file = {strdup("example.sdnn"), NULL, 0, {0, 0}}; sdnn_read(&file); sdnn_write(&file, "output.sdnn"); sdnn_free(&file); return 0; } // ===== end task-649 .SDNN ===== // ===== task-650 .SDS [C++] ===== #include #include #include #include #include class SDSFile { public: int device_id = 0; int sample_number = 0; int significant_bits = 0; int sample_period = 0; int sample_length = 0; int loop_start = 0; int loop_end = 0; int loop_type = 0; std::vector sample_data; void load(const std::string& path) { std::ifstream file(path, std::ios::binary); if (!file) throw std::runtime_error("File not found"); std::vector data((std::istreambuf_iterator(file)), {}); size_t pos = 0; bool header_found = false; int packet_num = 0; sample_data.clear(); while (pos < data.size()) { if (data[pos] == 0xF0) { pos++; if (pos + 3 >= data.size()) break; if (data[pos++] != 0x7E) continue; int dev = data[pos++]; int sub = data[pos++]; std::vector message; while (pos < data.size() && data[pos] != 0xF7) message.push_back(data[pos++]); if (pos < data.size() && data[pos++] == 0xF7) { if (sub == 1 && message.size() == 16 && !header_found) { header_found = true; device_id = dev; sample_number = message[0] + (message[1] << 7); significant_bits = message[2]; sample_period = message[3] + (message[4] << 7) + (message[5] << 14); sample_length = message[6] + (message[7] << 7) + (message[8] << 14); loop_start = message[9] + (message[10] << 7) + (message[11] << 14); loop_end = message[12] + (message[13] << 7) + (message[14] << 14); loop_type = message[15]; } else if (sub == 2 && message.size() == 122 && header_found) { int kk = message[0]; if (kk != packet_num % 128) throw std::runtime_error("Packet mismatch"); unsigned char data_bytes[120]; std::memcpy(data_bytes, &message[1], 120); int checksum = message[121]; int calc = 0x7E ^ dev ^ 0x02 ^ kk; for (int i = 0; i < 120; i++) calc ^= data_bytes[i]; calc &= 0x7F; if (calc != checksum) throw std::runtime_error("Checksum error"); auto unpacked = unpack_packet(data_bytes, 120); sample_data.insert(sample_data.end(), unpacked.begin(), unpacked.end()); packet_num++; } } } else pos++; } if (sample_data.size() != static_cast(sample_length)) throw std::runtime_error("Length mismatch"); } private: int get_bytes_per_word() const { int ee = significant_bits; if (ee == 0) return 0; return ((ee - 1) / 7) + 1; } std::vector unpack_packet(const unsigned char* data_bytes, int len) const { int bpw = get_bytes_per_word(); int points = len / bpw; std::vector samples; int pos = 0; for (int p = 0; p < points; p++) { int value = 0; for (int j = 0; j < bpw; j++) { value = (value << 7) | data_bytes[pos++]; } int shift = bpw * 7 - significant_bits; value >>= shift; samples.push_back(value); } return samples; } public: void save(const std::string& path) const { std::ofstream file(path, std::ios::binary); int bpw = get_bytes_per_word(); int points_per_packet = 120 / bpw; // Header unsigned char header[21] = {0xF0, 0x7E, static_cast(device_id), 0x01}; int idx = 4; header[idx++] = sample_number & 0x7F; header[idx++] = (sample_number >> 7) & 0x7F; header[idx++] = significant_bits & 0x7F; header[idx++] = sample_period & 0x7F; header[idx++] = (sample_period >> 7) & 0x7F; header[idx++] = (sample_period >> 14) & 0x7F; header[idx++] = sample_length & 0x7F; header[idx++] = (sample_length >> 7) & 0x7F; header[idx++] = (sample_length >> 14) & 0x7F; header[idx++] = loop_start & 0x7F; header[idx++] = (loop_start >> 7) & 0x7F; header[idx++] = (loop_start >> 14) & 0x7F; header[idx++] = loop_end & 0x7F; header[idx++] = (loop_end >> 7) & 0x7F; header[idx++] = (loop_end >> 14) & 0x7F; header[idx++] = loop_type & 0x7F; header[idx++] = 0xF7; file.write(reinterpret_cast(header), 21); // Packets for (size_t i = 0; i < sample_data.size(); i += points_per_packet) { size_t chunk_size = std::min(points_per_packet, static_cast(sample_data.size() - i)); unsigned char packed[120] = {0}; pack_packet(&sample_data[i], chunk_size, packed); int kk = static_cast(i / points_per_packet) % 128; int calc = 0x7E ^ device_id ^ 0x02 ^ kk; for (int j = 0; j < 120; j++) calc ^= packed[j]; unsigned char packet[125] = {0xF0, 0x7E, static_cast(device_id), 0x02, static_cast(kk)}; std::memcpy(&packet[5], packed, 120); packet[125] = calc & 0x7F; packet[5 + 120] = calc & 0x7F; packet[5 + 120 + 1] = 0xF7; file.write(reinterpret_cast(packet), 127); } } void pack_packet(const int* samples, size_t num, unsigned char* data_bytes) const { int bpw = get_bytes_per_word(); int pos = 0; for (size_t s = 0; s < num; s++) { int value = samples[s]; int shift = bpw * 7 - significant_bits; int shifted = value << shift; for (int j = bpw - 1; j >= 0; j--) { data_bytes[pos + j] = (shifted >> (j * 7)) & 0x7F; } pos += bpw; } } void print_properties() const { int rate = sample_period > 0 ? 1000000000 / sample_period : 0; std::cout << "Device ID: " << device_id << std::endl; std::cout << "Sample Number: " << sample_number << std::endl; std::cout << "Significant Bits per Sample: " << significant_bits << std::endl; std::cout << "Sample Period (ns): " << sample_period << std::endl; std::cout << "Sample Rate (Hz): " << rate << std::endl; std::cout << "Sample Length (words): " << sample_length << std::endl; std::cout << "Loop Start (words): " << loop_start << std::endl; std::cout << "Loop End (words): " << loop_end << std::endl; std::cout << "Loop Type: " << loop_type << std::endl; std::cout << "Sample Data Length: " << sample_data.size() << std::endl; } }; // Usage: // SDSFile sds; // sds.load("example.sds"); // sds.print_properties(); // sds.sample_number = 1; // sds.save("modified.sds"); // ===== end task-650 .SDS ===== // ===== task-651 .SDTS [C++] ===== #include #include #include #include #include #include // Assume zlib linked for gzip class SDTSHandler { private: std::string filename; std::set properties; std::vector decompressGzip(const std::vector& data) { z_stream zs = {}; inflateInit2(&zs, 16 + MAX_WBITS); // Gzip zs.next_in = reinterpret_cast(const_cast(data.data())); zs.avail_in = data.size(); std::vector out; char buffer[1024]; do { zs.next_out = reinterpret_cast(buffer); zs.avail_out = sizeof(buffer); inflate(&zs, Z_NO_FLUSH); out.insert(out.end(), buffer, buffer + sizeof(buffer) - zs.avail_out); } while (zs.avail_out == 0); inflateEnd(&zs); return out; } public: SDTSHandler(const std::string& fn) : filename(fn) {} void read() { std::ifstream file(filename, std::ios::binary); std::vector compressed((std::istreambuf_iterator(file)), std::istreambuf_iterator()); auto decompressed = decompressGzip(compressed); // Parse TAR size_t pos = 0; while (pos < decompressed.size()) { const char* header = &decompressed[pos]; if (std::string(header, 512) == std::string(512, '\0')) break; std::string name(header, 100); name = name.substr(0, name.find('\0')); if (name.rfind(".DDF") != std::string::npos) { std::string moduleTag = name.substr(name.length() - 8, 4); properties.insert(moduleTag); } long sizeOct = std::stol(std::string(header + 124, 12), nullptr, 8); pos += 512 + ((sizeOct + 511) / 512) * 512; } } void printProperties() { std::cout << "Properties (module tags) found:" << std::endl; for (const auto& prop : properties) { std::cout << prop << std::endl; } } void write(const std::string& outputFilename, const std::vector& modules) { std::ofstream tarFile("temp.tar", std::ios::binary); for (const auto& tag : modules) { std::string dummyName = "dummy" + tag + ".DDF"; std::string dummyContent = "Dummy content for " + tag; std::ofstream dummy(dummyName); dummy << dummyContent; dummy.close(); char header[512] = {}; std::strcpy(header, dummyName.c_str()); std::sprintf(header + 124, "%011lo", dummyContent.length()); tarFile.write(header, 512); std::ifstream dummyIn(dummyName, std::ios::binary); tarFile << dummyIn.rdbuf(); size_t pad = 512 - (dummyContent.length() % 512); if (pad < 512) tarFile.write(std::string(pad, '\0').c_str(), pad); std::remove(dummyName.c_str()); } tarFile.write(std::string(1024, '\0').c_str(), 1024); tarFile.close(); // Compress to gzip gzFile gz = gzopen(outputFilename.c_str(), "wb"); std::ifstream tarIn("temp.tar", std::ios::binary); char buffer[1024]; while (tarIn.read(buffer, sizeof(buffer))) { gzwrite(gz, buffer, tarIn.gcount()); } gzclose(gz); std::remove("temp.tar"); } }; // Example usage: // int main() { // SDTSHandler handler("example.sdts"); // handler.read(); // handler.printProperties(); // handler.write("new.sdts", {"IDEN", "CATD"}); // return 0; // } // ===== end task-651 .SDTS ===== // ===== task-652 .SEC [C] ===== #include #include #include #include // Requires libpcre or similar; for simplicity, use basic string ops typedef struct { char *filename; char *content; char *sectionNumber; char *sectionTitle; char *sectionDate; char **parts; // Dynamic array int partsCount; } SECReader; void initSECReader(SECReader *reader, const char *filename) { reader->filename = strdup(filename); reader->content = NULL; reader->sectionNumber = NULL; reader->sectionTitle = NULL; reader->sectionDate = NULL; reader->parts = NULL; reader->partsCount = 0; } void freeSECReader(SECReader *reader) { free(reader->filename); free(reader->content); free(reader->sectionNumber); free(reader->sectionTitle); free(reader->sectionDate); if (reader->parts) { for (int i = 0; i < reader->partsCount; i++) free(reader->parts[i]); free(reader->parts); } } void readSEC(SECReader *reader) { FILE *file = fopen(reader->filename, "r"); if (!file) { printf("Error: File not found.\n"); return; } fseek(file, 0, SEEK_END); long size = ftell(file); rewind(file); reader->content = malloc(size + 1); fread(reader->content, 1, size, file); reader->content[size] = '\0'; fclose(file); parseProperties(reader); printProperties(reader); } void parseProperties(SECReader *reader) { if (!reader->content) return; // Simple string search for tags (non-regex for portability; assumes no complex nesting) char *pos = reader->content; char *scnStart = strstr(pos, ""); if (scnStart) { scnStart += 5; char *scnEnd = strstr(scnStart, ""); if (scnEnd) { int len = scnEnd - scnStart; reader->sectionNumber = malloc(len + 1); strncpy(reader->sectionNumber, scnStart, len); reader->sectionNumber[len] = '\0'; // Strip inner tags roughly char *inner = strstr(reader->sectionNumber, "<"); if (inner) *inner = '\0'; } } // Similar for STL and DTE (omitted for brevity; replicate pattern) char *stlStart = strstr(reader->content, ""); if (stlStart) { stlStart += 5; char *stlEnd = strstr(stlStart, ""); if (stlEnd) { int len = stlEnd - stlStart; reader->sectionTitle = malloc(len + 1); strncpy(reader->sectionTitle, stlStart, len); reader->sectionTitle[len] = '\0'; char *inner = strstr(reader->sectionTitle, "<"); if (inner) *inner = '\0'; } } // For DTE and parts, implement similarly; for demo, assume extracted // Parts extraction would loop for PART... } void printProperties(SECReader *reader) { printf("Extracted .SEC Properties:\n"); printf("Section Number: %s\n", reader->sectionNumber ? reader->sectionNumber : "N/A"); printf("Section Title: %s\n", reader->sectionTitle ? reader->sectionTitle : "N/A"); printf("Section Date: %s\n", reader->sectionDate ? reader->sectionDate : "N/A"); printf("Parts Present: %s\n", reader->partsCount > 0 ? "Extracted" : "N/A"); // Simplified } void writeSEC(SECReader *reader, const char *outputFilename, const char *modifiedTitle) { if (!reader->content) { printf("Error: Read file first.\n"); return; } if (modifiedTitle) { // Simple replace (basic str replace) char *stlPos = strstr(reader->content, ""); if (stlPos) { char *stlEnd = strstr(stlPos, ""); if (stlEnd) { // Overwrite title (assumes space available; in practice, realloc) int offset = strlen(modifiedTitle); strncpy(stlPos + 5, modifiedTitle, offset); } } } FILE *out = fopen(outputFilename, "w"); if (out) { fputs(reader->content, out); fclose(out); printf("Modified file written to %s\n", outputFilename); } else { printf("Error writing file.\n"); } } int main() { SECReader reader; initSECReader(&reader, "example.sec"); readSEC(&reader); writeSEC(&reader, "modified.sec", "Updated Title"); freeSECReader(&reader); return 0; } // ===== end task-652 .SEC ===== // ===== task-653 .SED [C] ===== #include #include #include #define MAX_LINE 256 #define MAX_SECTIONS 100 #define MAX_PROPS 100 typedef struct { char *key; char *value; } Property; typedef struct { char *name; Property props[MAX_PROPS]; int prop_count; } Section; typedef struct { char *filepath; Section sections[MAX_SECTIONS]; int section_count; } SEDHandler; void load_sed(SEDHandler *handler) { FILE *file = fopen(handler->filepath, "r"); if (!file) { perror("File open error"); return; } char line[MAX_LINE]; char *current_section = NULL; int sec_idx = -1; while (fgets(line, sizeof(line), file)) { line[strcspn(line, "\n")] = 0; // Trim newline char *trimmed = line; while (*trimmed == ' ' || *trimmed == '\t') trimmed++; // Trim leading whitespace if (trimmed[0] == '[' && strrchr(trimmed, ']')) { current_section = strdup(trimmed + 1); current_section[strlen(current_section) - 1] = 0; // Remove ] sec_idx = handler->section_count++; handler->sections[sec_idx].name = current_section; handler->sections[sec_idx].prop_count = 0; } else if (current_section && strchr(trimmed, '=')) { char *eq_pos = strchr(trimmed, '='); *eq_pos = 0; char *key = strdup(trimmed); char *value = strdup(eq_pos + 1); // Trim value trailing spaces char *end = value + strlen(value) - 1; while (end > value && (*end == ' ' || *end == '\t')) end--; *(end + 1) = 0; int prop_idx = handler->sections[sec_idx].prop_count++; handler->sections[sec_idx].props[prop_idx].key = key; handler->sections[sec_idx].props[prop_idx].value = value; } } fclose(file); } void dump_properties(SEDHandler *handler) { printf("SED Properties Dump:\n"); for (int i = 0; i < handler->section_count; i++) { Section *sec = &handler->sections[i]; printf("[%s]\n", sec->name); for (int j = 0; j < sec->prop_count; j++) { printf(" %s: %s\n", sec->props[j].key, sec->props[j].value); } printf("\n"); } } void write_sed(SEDHandler *handler, const char *output_path) { FILE *file = fopen(output_path, "w"); if (!file) { perror("Write error"); return; } for (int i = 0; i < handler->section_count; i++) { Section *sec = &handler->sections[i]; fprintf(file, "[%s]\n", sec->name); for (int j = 0; j < sec->prop_count; j++) { fprintf(file, "%s=%s\n", sec->props[j].key, sec->props[j].value); } fprintf(file, "\n"); } fclose(file); printf("Written to: %s\n", output_path); } int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } SEDHandler handler = { .filepath = argv[1], .section_count = 0 }; load_sed(&handler); dump_properties(&handler); // Example modification: strcpy(handler.sections[0].props[0].value, "New Value"); // write_sed(&handler, "modified.sed"); // Free memory here in production return 0; } // ===== end task-653 .SED ===== // ===== task-654 .SEQ [C] ===== #include #include #include #include // POSIX regex; compile with -lregex if needed typedef struct { char* id; char* seq; int length; } Sequence; typedef struct { Sequence* sequences; int num_seqs; int total_bases; } SeqFile; SeqFile* load_seqfile(const char* filepath) { FILE* file = fopen(filepath, "r"); if (!file) { perror("Error opening file"); return NULL; } // Read entire file fseek(file, 0, SEEK_END); long size = ftell(file); fseek(file, 0, SEEK_SET); char* content = malloc(size + 1); fread(content, 1, size, file); content[size] = '\0'; fclose(file); SeqFile* sf = malloc(sizeof(SeqFile)); sf->sequences = NULL; sf->num_seqs = 0; sf->total_bases = 0; regex_t regex; regcomp(®ex, "^>([^ \n]+)(?: .*)?\\n([ACGTUNacgtun-]*?)(?=>|$)", REG_MULTILINE | REG_EXTENDED); size_t nmatch = 3; regmatch_t pmatch[3]; char* ptr = content; while (regexec(®ex, ptr, nmatch, pmatch, 0) == 0) { // Extract ID int id_len = pmatch[1].rm_eo - pmatch[1].rm_so; sf->sequences = realloc(sf->sequences, (sf->num_seqs + 1) * sizeof(Sequence)); sf->sequences[sf->num_seqs].id = malloc(id_len + 1); strncpy(sf->sequences[sf->num_seqs].id, ptr + pmatch[1].rm_so, id_len); sf->sequences[sf->num_seqs].id[id_len] = '\0'; // Extract and clean seq int seq_len = pmatch[2].rm_eo - pmatch[2].rm_so; char* raw_seq = malloc(seq_len + 1); strncpy(raw_seq, ptr + pmatch[2].rm_so, seq_len); raw_seq[seq_len] = '\0'; // Remove non-seq chars and uppercase (simplified) char* clean_seq = malloc(seq_len + 1); int j = 0; for (int i = 0; i < seq_len; i++) { char c = raw_seq[i]; if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '-' || c == 'N') { clean_seq[j++] = (c >= 'a' && c <= 'z') ? c - 32 : c; } } clean_seq[j] = '\0'; sf->sequences[sf->num_seqs].seq = clean_seq; sf->sequences[sf->num_seqs].length = j; sf->total_bases += j; sf->num_seqs++; free(raw_seq); ptr += pmatch[0].rm_eo; } regfree(®ex); free(content); if (sf->num_seqs == 0) { free(sf); return NULL; } return sf; } void print_properties(SeqFile* sf) { if (!sf) return; double avg = sf->num_seqs ? (double)sf->total_bases / sf->num_seqs : 0; printf("Number of sequences: %d\n", sf->num_seqs); printf("Total bases: %d\n", sf->total_bases); printf("Average length: %.2f\n", avg); for (int i = 0; i < sf->num_seqs; i++) { printf("Sequence ID: %s, Length: %d\n", sf->sequences[i].id, sf->sequences[i].length); } } void write_seqfile(SeqFile* sf, const char* output_path) { FILE* file = fopen(output_path, "w"); if (!file) { perror("Error writing file"); return; } for (int i = 0; i < sf->num_seqs; i++) { fprintf(file, ">%s\n%s\n", sf->sequences[i].id, sf->sequences[i].seq); } fclose(file); printf("Written to %s\n", output_path); } void free_seqfile(SeqFile* sf) { if (!sf) return; for (int i = 0; i < sf->num_seqs; i++) { free(sf->sequences[i].id); free(sf->sequences[i].seq); } free(sf->sequences); free(sf); } int main(int argc, char* argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } SeqFile* sf = load_seqfile(argv[1]); if (!sf) { fprintf(stderr, "Invalid .SEQ file\n"); return 1; } print_properties(sf); // Example: Modify sf->sequences[0].seq = "MODIFIED"; sf->sequences[0].length = 8; // write_seqfile(sf, "modified.seq"); free_seqfile(sf); return 0; } // ===== end task-654 .SEQ ===== // ===== task-655 .SERIES [C] ===== #include #include #include #include #include #define MAX_FILES 100 #define PATH_LEN 256 #define SIG_LEN 12 typedef struct { char signature[SIG_LEN]; uint32_t version; uint32_t num_files; char file_list[MAX_FILES][PATH_LEN]; uint8_t data_type; uint8_t interleave; uint32_t height; uint32_t width; uint32_t bands; uint32_t checksum; } SERIESFile; SERIESFile sf; void read_series(const char* filepath) { FILE* fp = fopen(filepath, "rb"); if (!fp) { perror("File not found"); return; } fread(sf.signature, 1, SIG_LEN, fp); fread(&sf.version, 4, 1, fp); fread(&sf.num_files, 4, 1, fp); for (uint32_t i = 0; i < sf.num_files && i < MAX_FILES; i++) { fread(sf.file_list[i], 1, PATH_LEN, fp); // Trim nulls sf.file_list[i][strcspn(sf.file_list[i], "\0")] = 0; } fread(&sf.data_type, 1, 1, fp); fread(&sf.interleave, 1, 1, fp); fread(&sf.height, 4, 1, fp); fread(&sf.width, 4, 1, fp); fread(&sf.bands, 4, 1, fp); fseek(fp, -4, SEEK_END); fread(&sf.checksum, 4, 1, fp); fclose(fp); print_properties(); } void write_series(const char* output_path) { FILE* fp = fopen(output_path, "wb"); if (!fp) { perror("Write failed"); return; } fwrite(sf.signature, 1, SIG_LEN, fp); fwrite(&sf.version, 4, 1, fp); fwrite(&sf.num_files, 4, 1, fp); for (uint32_t i = 0; i < sf.num_files; i++) { char padded[PATH_LEN] = {0}; strncpy(padded, sf.file_list[i], PATH_LEN - 1); fwrite(padded, 1, PATH_LEN, fp); } fwrite(&sf.data_type, 1, 1, fp); fwrite(&sf.interleave, 1, 1, fp); fwrite(&sf.height, 4, 1, fp); fwrite(&sf.width, 4, 1, fp); fwrite(&sf.bands, 4, 1, fp); sf.checksum = calculate_checksum(); fwrite(&sf.checksum, 4, 1, fp); fclose(fp); printf("Written to %s\n", output_path); } uint32_t calculate_checksum() { uint32_t sum = 0; for (uint32_t i = 0; i < sf.num_files; i++) { for (char* p = sf.file_list[i]; *p; p++) sum += (uint8_t)*p; } return sum; } void print_properties() { printf("=== .SERIES Properties ===\n"); printf("Signature: %s\n", sf.signature); printf("Version: %u\n", sf.version); printf("Num Files: %u\n", sf.num_files); for (uint32_t i = 0; i < sf.num_files; i++) { printf("File %u: %s\n", i + 1, sf.file_list[i]); } printf("Data Type: %u\n", sf.data_type); printf("Interleave: %u\n", sf.interleave); printf("Dimensions: %u x %u\n", sf.height, sf.width); printf("Bands: %u\n", sf.bands); printf("Checksum: %u\n", sf.checksum); } int main(int argc, char* argv[]) { if (argc > 1) { strcpy(sf.signature, "ENVI Series\x00"); // Default read_series(argv[1]); } return 0; } // ===== end task-655 .SERIES ===== // ===== task-656 .SF [C] ===== #include #include #include typedef struct { unsigned char *data; size_t size; size_t offset; } SF2Reader; void init_reader(SF2Reader *r, const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) { perror("File open"); exit(1); } fseek(f, 0, SEEK_END); r->size = ftell(f); fseek(f, 0, SEEK_SET); r->data = malloc(r->size); fread(r->data, 1, r->size, f); fclose(f); r->offset = 0; } char *read_string(SF2Reader *r, int len) { char *s = malloc(len + 1); memcpy(s, r->data + r->offset, len); s[len] = '\0'; r->offset += len; return s; } uint32_t read_uint32le(SF2Reader *r) { uint32_t val = *(uint32_t *)(r->data + r->offset); r->offset += 4; return __builtin_bswap32(val); // For little-endian on big-endian host; adjust if needed } uint16_t read_uint16le(SF2Reader *r) { uint16_t val = *(uint16_t *)(r->data + r->offset); r->offset += 2; return __builtin_bswap16(val); } void read_riff_header(SF2Reader *r) { char *riff = read_string(r, 4); if (strcmp(riff, "RIFF")) { free(riff); exit(1); } free(riff); uint32_t size = read_uint32le(r); char *form = read_string(r, 4); if (strcmp(form, "sfbk")) { free(form); exit(1); } free(form); printf("File Size: %u bytes\n", size); } void parse_info(SF2Reader *r, size_t start, size_t size) { printf("\n--- INFO Chunk ---\n"); size_t off = start + 8; // Skip LIST while (off < start + size) { char sub_id[5]; memcpy(sub_id, r->data + off, 4); sub_id[4] = '\0'; off += 4; uint32_t sub_size = read_uint32le_at(r, off); // Helper to read without advancing off += 4; if (!strcmp(sub_id, "ifil")) { uint16_t major = read_uint16le_at(r, off); uint16_t minor = read_uint16le_at(r, off + 2); printf("Version: %u.%u\n", major, minor); off += 4; } else { char *val = malloc(sub_size + 1); memcpy(val, r->data + off, sub_size); val[sub_size] = '\0'; printf("%s: %s\n", sub_id, val); free(val); off += sub_size; } off += (sub_size % 2); } } uint32_t read_uint32le_at(SF2Reader *r, size_t pos) { return __builtin_bswap32(*(uint32_t *)(r->data + pos)); } uint16_t read_uint16le_at(SF2Reader *r, size_t pos) { return __builtin_bswap16(*(uint16_t *)(r->data + pos)); } // Implement parse_sdta, parse_pdta similarly... void read_chunk(SF2Reader *r) { // Similar loop as JS/Python, calling parse functions // Omitted for brevity; use offset advancement } void decode(SF2Reader *r) { r->offset = 0; read_riff_header(r); read_chunk(r); } void write(SF2Reader *r, const char *out) { FILE *f = fopen(out, "wb"); fwrite(r->data, 1, r->size, f); fclose(f); printf("Written to %s\n", out); } void free_reader(SF2Reader *r) { free(r->data); } int main() { SF2Reader r; init_reader(&r, "example.sf2"); decode(&r); write(&r, "copy.sf2"); free_reader(&r); return 0; } // ===== end task-656 .SF ===== // ===== task-657 .SFB [C] ===== #include #include #include #include typedef struct { char magic[5]; // Null-terminated char version[9]; // Hex string char hybrid_flag[32]; char content_offset[9]; char content_length[9]; char title_name[32]; char title_data_offset[9]; char title_data_length[9]; char disc_content[5]; char disc_title[11]; } SFBProperties; typedef struct { SFBProperties props; FILE* file; } SFBDecoder; void read_sfb(SFBDecoder* decoder, const char* filename) { decoder->file = fopen(filename, "rb"); if (!decoder->file) { perror("Failed to open file"); return; } fseek(decoder->file, 0, SEEK_END); long size = ftell(decoder->file); fseek(decoder->file, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, decoder->file); int offset = 0; // Magic memcpy(decoder->props.magic, data + offset, 4); decoder->props.magic[4] = '\0'; offset += 4; // Version (uint32 BE) uint32_t ver = (data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]; snprintf(decoder->props.version, sizeof(decoder->props.version), "0x%08X", ver); offset += 4; // Hybrid Flag (offset 0x10) offset = 0x10; int end = offset; while (data[end] != 0 && end < size) end++; memcpy(decoder->props.hybrid_flag, data + offset, end - offset); decoder->props.hybrid_flag[end - offset] = '\0'; offset = end + 1; // Content Offset uint32_t co = (data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]; snprintf(decoder->props.content_offset, sizeof(decoder->props.content_offset), "0x%08X", co); offset += 4; // Content Length uint32_t cl = (data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]; snprintf(decoder->props.content_length, sizeof(decoder->props.content_length), "0x%08X", cl); offset += 4; // Title Name end = offset; while (data[end] != 0 && end < size) end++; memcpy(decoder->props.title_name, data + offset, end - offset); decoder->props.title_name[end - offset] = '\0'; offset = end + 1; // Title Data Offset uint32_t tdo = (data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]; snprintf(decoder->props.title_data_offset, sizeof(decoder->props.title_data_offset), "0x%08X", tdo); offset += 4; // Title Data Length uint32_t tdl = (data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]; snprintf(decoder->props.title_data_length, sizeof(decoder->props.title_data_length), "0x%08X", tdl); offset += 4; // Disc Content memcpy(decoder->props.disc_content, data + offset, 4); decoder->props.disc_content[4] = '\0'; offset += 4; // Disc Title memcpy(decoder->props.disc_title, data + offset, 10); decoder->props.disc_title[10] = '\0'; free(data); print_properties(&decoder->props); } void print_properties(SFBProperties* props) { printf("magic: %s\n", props->magic); printf("version: %s\n", props->version); printf("hybrid_flag: %s\n", props->hybrid_flag); printf("content_offset: %s\n", props->content_offset); printf("content_length: %s\n", props->content_length); printf("title_name: %s\n", props->title_name); printf("title_data_offset: %s\n", props->title_data_offset); printf("title_data_length: %s\n", props->title_data_length); printf("disc_content: %s\n", props->disc_content); printf("disc_title: %s\n", props->disc_title); } void write_sfb(SFBDecoder* decoder, const char* output_filename) { // Simplified: copy original FILE* out = fopen(output_filename, "wb"); if (!out) { perror("Failed to write"); return; } fseek(decoder->file, 0, SEEK_SET); char buf[1024]; size_t bytes; while ((bytes = fread(buf, 1, sizeof(buf), decoder->file)) > 0) { fwrite(buf, 1, bytes, out); } fclose(out); printf("Written to %s\n", output_filename); } int main() { SFBDecoder decoder = {0}; read_sfb(&decoder, "PS3_DISC.SFB"); // Replace with file path // write_sfb(&decoder, "output.SFB"); fclose(decoder.file); return 0; } // ===== end task-657 .SFB ===== // ===== task-658 .SFH [C] ===== #include #include #include #define MAX_POINTS 1024 #define MAX_LINE 256 #define FIDUCIAL_COUNT 3 #define TRANSFORM_COUNT 12 typedef struct { char filename[256]; int n_points; double fiducials[FIDUCIAL_COUNT][3]; double surface_points[MAX_POINTS - FIDUCIAL_COUNT][MAX_LINE / 10]; // Flexible for extra int surface_extra[MAX_POINTS - FIDUCIAL_COUNT]; // Number of extra per point double transformation[TRANSFORM_COUNT]; int has_transform; } SFHFile; void read_sfh(SFHFile *sfh) { FILE *fp = fopen(sfh->filename, "r"); if (!fp) { fprintf(stderr, "Error opening file %s\n", sfh->filename); return; } char line[MAX_LINE]; if (!fgets(line, sizeof(line), fp)) { fprintf(stderr, "Error: Empty file.\n"); fclose(fp); return; } sfh->n_points = atoi(line); if (sfh->n_points > MAX_POINTS || sfh->n_points < FIDUCIAL_COUNT) { fprintf(stderr, "Error: Invalid N (%d).\n", sfh->n_points); fclose(fp); return; } for (int i = 0; i < sfh->n_points; i++) { if (!fgets(line, sizeof(line), fp)) { fprintf(stderr, "Error: Insufficient lines.\n"); fclose(fp); return; } char *token = strtok(line, " \t\n"); int col = 0; double vals[32]; // Max cols per line while (token && col < 32) { vals[col++] = atof(token); token = strtok(NULL, " \t\n"); } if (col < 3) { fprintf(stderr, "Error: Invalid point line %d.\n", i + 1); fclose(fp); return; } if (i < FIDUCIAL_COUNT) { for (int j = 0; j < 3; j++) { sfh->fiducials[i][j] = vals[j]; } } else { int idx = i - FIDUCIAL_COUNT; for (int j = 0; j < 3; j++) { sfh->surface_points[idx][j] = vals[j]; } sfh->surface_extra[idx] = col - 3; for (int j = 3; j < col; j++) { sfh->surface_points[idx][j] = vals[j]; } } } // Parse transformation sfh->has_transform = 0; double temp[TRANSFORM_COUNT]; int count = 0; while (fgets(line, sizeof(line), fp) && count < TRANSFORM_COUNT) { char *token = strtok(line, " \t\n"); while (token && count < TRANSFORM_COUNT) { temp[count++] = atof(token); token = strtok(NULL, " \t\n"); } } if (count >= TRANSFORM_COUNT) { sfh->has_transform = 1; for (int j = 0; j < TRANSFORM_COUNT; j++) { sfh->transformation[j] = temp[j]; } } fclose(fp); print_properties(sfh); } void print_properties(SFHFile *sfh) { printf("SFH File Properties:\n"); printf("Total Surface Points (N): %d\n", sfh->n_points); const char *fid_names[] = {"Nasion", "Left Auricular", "Right Auricular"}; for (int i = 0; i < FIDUCIAL_COUNT; i++) { printf("%s: X=%.2f mm, Y=%.2f mm, Z=%.2f mm\n", fid_names[i], sfh->fiducials[i][0], sfh->fiducials[i][1], sfh->fiducials[i][2]); } printf("\nSurface Points (%d points):\n", sfh->n_points - FIDUCIAL_COUNT); for (int i = 0; i < sfh->n_points - FIDUCIAL_COUNT; i++) { printf("Point %d: X=%.2f mm, Y=%.2f mm, Z=%.2f mm", i + 1, sfh->surface_points[i][0], sfh->surface_points[i][1], sfh->surface_points[i][2]); if (sfh->surface_extra[i] > 0) { printf(" (Extra: "); for (int j = 0; j < sfh->surface_extra[i]; j++) { printf("%.2f ", sfh->surface_points[i][3 + j]); } printf(")"); } printf("\n"); } if (sfh->has_transform) { printf("\nCoregistration Affine Transformation (12 params):\n"); for (int i = 0; i < TRANSFORM_COUNT; i++) { printf("Param %d: %.4f\n", i + 1, sfh->transformation[i]); } } } void write_sfh(SFHFile *sfh, const char *output_filename) { FILE *fp = fopen(output_filename, "w"); if (!fp) { fprintf(stderr, "Error opening output file %s\n", output_filename); return; } fprintf(fp, "%d\n", sfh->n_points); for (int i = 0; i < FIDUCIAL_COUNT; i++) { for (int j = 0; j < 3; j++) { fprintf(fp, "%.6f ", sfh->fiducials[i][j]); } fprintf(fp, "\n"); } for (int i = 0; i < sfh->n_points - FIDUCIAL_COUNT; i++) { for (int j = 0; j < 3 + sfh->surface_extra[i]; j++) { fprintf(fp, "%.6f ", sfh->surface_points[i][j]); } fprintf(fp, "\n"); } if (sfh->has_transform) { for (int j = 0; j < TRANSFORM_COUNT; j++) { fprintf(fp, "%.6f ", sfh->transformation[j]); } fprintf(fp, "\n"); } fclose(fp); printf("Properties written to %s\n", output_filename); } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } SFHFile sfh = {0}; strcpy(sfh.filename, argv[1]); read_sfh(&sfh); // Example: write_sfh(&sfh, "output.sfh"); return 0; } // ===== end task-658 .SFH ===== // ===== task-659 .SFX [C] ===== #include #include #include #include #define RAR_SIGNATURE_3X_LEN 7 static const uint8_t RAR_SIGNATURE_3X[RAR_SIGNATURE_3X_LEN] = {0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x00}; typedef struct { uint8_t* data; size_t size; size_t pos; } Buffer; static int find_signature(Buffer* buf) { for (size_t i = 0; i <= buf->size - RAR_SIGNATURE_3X_LEN; i++) { int match = 1; for (int j = 0; j < RAR_SIGNATURE_3X_LEN; j++) { if (buf->data[i + j] != RAR_SIGNATURE_3X[j]) { match = 0; break; } } if (match) return i; } return -1; } static void parse_rar3(Buffer* buf, size_t offset, FILE* out) { buf->pos = offset + RAR_SIGNATURE_3X_LEN; if (buf->data[buf->pos] != 0x73) { fprintf(out, "Invalid archive header.\n"); return; } buf->pos += 1; uint16_t head_flags = *(uint16_t*)(buf->data + buf->pos); buf->pos += 2; uint16_t head_size = *(uint16_t*)(buf->data + buf->pos); buf->pos += 2; buf->pos += 4; // Reserved fprintf(out, "Archive Flags: 0x%04x\n", head_flags); fprintf(out, "Archive Header Size: %u bytes\n", head_size); fprintf(out, "\nFile Properties:\n"); while (buf->pos < buf->size) { buf->pos += 2; // CRC uint8_t head_type = buf->data[buf->pos]; buf->pos += 1; uint16_t head_flags2 = *(uint16_t*)(buf->data + buf->pos); buf->pos += 2; uint16_t head_size2 = *(uint16_t*)(buf->data + buf->pos); buf->pos += 2; if (head_type == 0x74) { uint32_t pack_size = *(uint32_t*)(buf->data + buf->pos); buf->pos += 4; uint32_t unp_size = *(uint32_t*)(buf->data + buf->pos); buf->pos += 4; uint8_t host_os = buf->data[buf->pos]; buf->pos += 1; uint32_t file_crc = *(uint32_t*)(buf->data + buf->pos); buf->pos += 4; uint32_t ftime = *(uint32_t*)(buf->data + buf->pos); buf->pos += 4; uint8_t unp_ver = buf->data[buf->pos]; buf->pos += 1; uint8_t method = buf->data[buf->pos]; buf->pos += 1; uint16_t name_size = *(uint16_t*)(buf->data + buf->pos); buf->pos += 2; char name[1024] = {0}; memcpy(name, buf->data + buf->pos, name_size > 1023 ? 1023 : name_size); buf->pos += name_size; uint32_t attr = *(uint32_t*)(buf->data + buf->pos); buf->pos += 4; int is_dir = (head_flags2 & 0xE000) == 0xE000; fprintf(out, "- Name: %s\n", name); fprintf(out, " Packed Size: %u\n", pack_size); fprintf(out, " Unpacked Size: %u\n", unp_size); fprintf(out, " CRC32: 0x%08x\n", file_crc); fprintf(out, " Host OS: %u\n", host_os); fprintf(out, " mtime (DOS): %u\n", ftime); fprintf(out, " Attributes: 0x%08x\n", attr); fprintf(out, " Directory: %s\n", is_dir ? "true" : "false"); fprintf(out, " Method: %u\n", method); fprintf(out, " Unpack Ver: %u\n", unp_ver); buf->pos += pack_size; // Skip data } else { buf->pos += head_size2 - 7; } } } static void parse_file(const char* filename) { FILE* fp = fopen(filename, "rb"); if (!fp) { perror("Error opening file"); return; } fseek(fp, 0, SEEK_END); size_t size = ftell(fp); fseek(fp, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, fp); fclose(fp); Buffer buf = {data, size, 0}; int sig_offset = find_signature(&buf); if (sig_offset == -1) { printf("No RAR signature found.\n"); free(data); return; } printf("SFX Stub Offset: %d\n", sig_offset); parse_rar3(&buf, sig_offset, stdout); free(data); } static void write_file(const char* input, const char* output) { FILE* in = fopen(input, "rb"); FILE* out = fopen(output, "wb"); if (!in || !out) { perror("Error in write"); if (in) fclose(in); if (out) fclose(out); return; } uint8_t buf[4096]; size_t n; while ((n = fread(buf, 1, sizeof(buf), in)) > 0) { fwrite(buf, 1, n, out); } fclose(in); fclose(out); printf("Wrote SFX to %s\n", output); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } parse_file(argv[1]); // For write: write_file(argv[1], "output.sfx"); return 0; } // ===== end task-659 .SFX ===== // ===== task-660 .SH [C] ===== #include #include #include #include #include #include #include #include typedef struct { char *path; char *content; char *shebang; struct stat st; int lines; } SHFile; SHFile *shfile_new(const char *path) { SHFile *self = malloc(sizeof(SHFile)); self->path = strdup(path); self->content = NULL; self->shebang = strdup("None"); self->lines = 0; if (stat(path, &self->st) != 0) { perror("stat"); free(self); return NULL; } FILE *f = fopen(path, "r"); if (!f) { perror("fopen"); free(self->path); free(self->shebang); free(self); return NULL; } fseek(f, 0, SEEK_END); long size = ftell(f); rewind(f); self->content = malloc(size + 1); fread(self->content, 1, size, f); self->content[size] = '\0'; fclose(f); // Count lines and check shebang self->lines = 1; for (int i = 0; i < size; i++) { if (self->content[i] == '\n') self->lines++; } if (size > 2 && strncmp(self->content, "#!", 2) == 0) { free(self->shebang); char *nl = strchr(self->content, '\n'); int len = nl ? (nl - self->content) : size; self->shebang = malloc(len + 1); strncpy(self->shebang, self->content, len); self->shebang[len] = '\0'; } return self; } void shfile_print_properties(SHFile *self) { char timebuf[64]; struct tm *tm = localtime(&self->st.st_mtime); strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%S", tm); printf("File Name: %s\n", self->path ? strrchr(self->path, '/') + 1 : "N/A"); printf("File Size (bytes): %ld\n", (long)self->st.st_size); printf("Permissions (octal): %o\n", self->st.st_mode & 0777); printf("Owner UID: %d\n", self->st.st_uid); printf("Group GID: %d\n", self->st.st_gid); printf("Modification Time (mtime): %s\n", timebuf); tm = localtime(&self->st.st_atime); strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%S", tm); printf("Access Time (atime): %s\n", timebuf); tm = localtime(&self->st.st_ctime); strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%S", tm); printf("Change Time (ctime): %s\n", timebuf); printf("Inode Number: %ld\n", (long)self->st.st_ino); printf("Hard Link Count: %ld\n", (long)self->st.st_nlink); printf("Type: %s\n", S_ISREG(self->st.st_mode) ? "Regular file" : "Other"); printf("Shebang Line: %s\n", self->shebang); printf("Line Count: %d\n", self->lines); } void shfile_write(SHFile *self, const char *new_content) { FILE *f = fopen(self->path, "w"); if (!f) { perror("fwrite"); return; } fputs(new_content, f); fclose(f); // Refresh free(self->content); self->content = strdup(new_content); self->lines = 1; for (size_t i = 0; new_content[i]; i++) { if (new_content[i] == '\n') self->lines++; } free(self->shebang); self->shebang = strdup("None"); if (strlen(new_content) > 2 && strncmp(new_content, "#!", 2) == 0) { const char *nl = strchr(new_content, '\n'); size_t len = nl ? (nl - new_content) : strlen(new_content); self->shebang = malloc(len + 1); strncpy(self->shebang, new_content, len); self->shebang[len] = '\0'; } stat(self->path, &self->st); // Refresh stat } void shfile_free(SHFile *self) { free(self->path); free(self->content); free(self->shebang); free(self); } // Example usage: // int main() { // SHFile *shf = shfile_new("example.sh"); // if (shf) { // shfile_print_properties(shf); // shfile_write(shf, "#!/bin/sh\necho \"Updated\""); // shfile_print_properties(shf); // shfile_free(shf); // } // return 0; // } // ===== end task-660 .SH ===== // ===== task-661 .SHAR [C] ===== #include #include #include #include #include #include #include // Not used, but for completeness #define MAX_LINES 100000 #define MAX_LINE_LEN 1024 #define MAX_FILES 1000 typedef struct { char name[256]; char type[16]; char permissions[4]; char timestamp[16]; int length; char md5[33]; } FileProperties; typedef struct { char **lines; int line_count; FileProperties files[MAX_FILES]; int file_count; } SharArchive; SharArchive *shar_open(const char *filename) { SharArchive *arch = malloc(sizeof(SharArchive)); if (!arch) return NULL; arch->line_count = 0; arch->lines = malloc(MAX_LINES * sizeof(char *)); if (!arch->lines) { free(arch); return NULL; } FILE *f = fopen(filename, "r"); if (!f) { free(arch->lines); free(arch); return NULL; } char buf[MAX_LINE_LEN]; while (fgets(buf, sizeof(buf), f) && arch->line_count < MAX_LINES) { arch->lines[arch->line_count] = strdup(buf); arch->line_count++; } fclose(f); arch->file_count = 0; return arch; } void shar_parse(SharArchive *arch) { int i = 0; regex_t regex_chmod, regex_touch, regex_md5; regcomp(®ex_chmod, "chmod\\s+(\\d+)", REG_EXTENDED); regcomp(®ex_touch, "touch -am -t (\\S+)", REG_EXTENDED); regcomp(®ex_md5, "([a-f0-9]{32})", REG_EXTENDED); while (i < arch->line_count) { char *line = arch->lines[i]; if (strncmp(line, "echo x - ", 9) == 0) { char *filename_start = strstr(line, " - ") + 3; char filename[256] = "unknown"; sscanf(filename_start, "%255s", filename); char *quote = strchr(filename, '\''); if (quote) *quote = '\0'; strcpy(arch->files[arch->file_count].name, filename); strcpy(arch->files[arch->file_count].type, strstr(line, "text") ? "text" : "binary"); // Find chmod char perm[4] = "644"; int j = i + 1; while (j < arch->line_count && strstr(arch->lines[j], "sed") == NULL) { regmatch_t matches[2]; if (regexec(®ex_chmod, arch->lines[j], 2, matches, 0) == 0) { strncpy(perm, arch->lines[j] + matches[1].rm_so, 3); perm[3] = '\0'; } j++; } strcpy(arch->files[arch->file_count].permissions, perm); // Find touch char ts[16] = {0}; while (j < arch->line_count && strstr(arch->lines[j], "sed") == NULL) { regmatch_t matches[2]; if (regexec(®ex_touch, arch->lines[j], 2, matches, 0) == 0) { strncpy(ts, arch->lines[j] + matches[1].rm_so, 14); ts[15] = '\0'; } j++; } strcpy(arch->files[arch->file_count].timestamp, ts); // Content length (approx) const char *delim = "SHAR_EOF"; int content_len = 0; int k = j + 1; while (k < arch->line_count) { if (strstr(arch->lines[k], delim) != NULL) break; if (arch->lines[k][0] == 'X') content_len += strlen(arch->lines[k]) - 1; else content_len += strlen(arch->lines[k]); k++; } arch->files[arch->file_count].length = content_len; // Find MD5 char md5[33] = {0}; int m = k + 1; while (m < arch->line_count && strstr(arch->lines[m], "md5sum") == NULL) m++; if (m + 1 < arch->line_count) { regmatch_t matches[2]; if (regexec(®ex_md5, arch->lines[m + 1], 2, matches, 0) == 0) { strncpy(md5, arch->lines[m + 1] + matches[1].rm_so, 32); } } strcpy(arch->files[arch->file_count].md5, md5); arch->file_count++; i = k + 1; } else { i++; } } regfree(®ex_chmod); regfree(®ex_touch); regfree(®ex_md5); } void shar_print_properties(SharArchive *arch) { shar_parse(arch); printf("Archive Properties:\n"); printf("Number of files: %d\n", arch->file_count); for (int f = 0; f < arch->file_count; f++) { printf("File: %s\n", arch->files[f].name); printf(" Type: %s\n", arch->files[f].type); printf(" Permissions: %s\n", arch->files[f].permissions); printf(" Timestamp: %s\n", strlen(arch->files[f].timestamp) ? arch->files[f].timestamp : "N/A"); printf(" Length: %d\n", arch->files[f].length); printf(" MD5: %s\n", strlen(arch->files[f].md5) ? arch->files[f].md5 : "N/A"); printf("\n"); } } void shar_write(const char **filepaths, int num_files, const char *output_filename) { FILE *out = fopen(output_filename, "w"); if (!out) return; fprintf(out, "#!/bin/sh\n"); fprintf(out, "# Simple SHAR archive.\n\n"); for (int idx = 0; idx < num_files; idx++) { const char *file_path = filepaths[idx]; struct stat st; if (stat(file_path, &st) == 0) { char filename[256]; strncpy(filename, strrchr(file_path, '/') + 1, 255); char perm[4]; sprintf(perm, "%03o", st.st_mode & 0777); struct tm *tm_info = localtime(&st.st_mtime); char timestamp[16]; strftime(timestamp, sizeof(timestamp), "%Y%m%d%H%M.%S", tm_info); FILE *inf = fopen(file_path, "r"); char buf[1024]; fprintf(out, "echo 'x - %s (text)'\n", filename); fprintf(out, "chmod %s %s\n", perm, filename); fprintf(out, "touch -am -t %s %s\n", timestamp, filename); fprintf(out, "sed 's/^X//' <<'SHAR_EOF' >%s\n", filename); while (fgets(buf, sizeof(buf), inf)) { fprintf(out, "X%s", buf); } fclose(inf); fprintf(out, "SHAR_EOF\n"); fprintf(out, "test -r %s || echo 'restore of %s failed'\n", filename, filename); fprintf(out, "wc -c <'%s'\n", filename); fprintf(out, "echo 'done'\n\n"); } } fprintf(out, "exit 0\n"); fclose(out); } void shar_close(SharArchive *arch) { for (int l = 0; l < arch->line_count; l++) { free(arch->lines[l]); } free(arch->lines); free(arch); } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } SharArchive *arch = shar_open(argv[1]); if (arch) { shar_print_properties(arch); shar_close(arch); } // Example write: const char *files[] = {"file1.txt"}; shar_write(files, 1, "new.shar"); return 0; } // ===== end task-661 .SHAR ===== // ===== task-662 .SHTM [C] ===== #include #include #include #include #include #include typedef struct { char directive[32]; char params[256]; } Directive; typedef struct { char file_ext[8]; char mime_type[16]; long file_size; char last_mod[64]; char encoding[16]; int ssi_count; Directive* directives; int has_html; char server_dep[64]; } Properties; Properties* extract_properties(const char* file_path, char* content, size_t content_len) { Properties* props = malloc(sizeof(Properties)); strcpy(props->file_ext, ".shtm"); strcpy(props->mime_type, "text/html"); strcpy(props->encoding, "UTF-8"); strcpy(props->server_dep, "Requires SSI-enabled server"); struct stat st; stat(file_path, &st); props->file_size = st.st_size; struct tm* tm = localtime(&st.st_mtime); strftime(props->last_mod, sizeof(props->last_mod), "%Y-%m-%dT%H:%M:%S", tm); // Simple scan for SSI directives props->ssi_count = 0; props->directives = malloc(100 * sizeof(Directive)); // Assume max 100 char* pos = content; while ((pos = strstr(pos, "") == NULL) break; char* end = strstr(pos, "-->"); if (end) { char dir[32] = {0}; sscanf(pos + 5, "%31s", dir); // Skip ") char param_buf[256] = {0}; strncpy(param_buf, pos + 6 + strlen(dir), end - (pos + 6 + strlen(dir))); strcpy(props->directives[props->ssi_count].params, param_buf); props->ssi_count++; pos = end; } else { break; } } props->has_html = (strstr(content, "file_ext); printf("MIME Type: %s\n", props->mime_type); printf("File Size (bytes): %ld\n", props->file_size); printf("Last Modified: %s\n", props->last_mod); printf("Encoding: %s\n", props->encoding); printf("SSI Directives Found: %d\n", props->ssi_count); for (int i = 0; i < props->ssi_count; i++) { printf(" Directive %d: %s (params: %s)\n", i+1, props->directives[i].directive, props->directives[i].params); } printf("Contains HTML Structure: %s\n", props->has_html ? "Yes" : "No"); printf("Server Dependency: %s\n", props->server_dep); } void write_file(const char* file_path, const char* content, size_t len) { FILE* f = fopen(file_path, "w"); if (f) { fwrite(content, 1, len, f); fclose(f); } } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } FILE* f = fopen(argv[1], "r"); if (!f) { perror("Error opening file"); return 1; } fseek(f, 0, SEEK_END); size_t len = ftell(f); fseek(f, 0, SEEK_SET); char* content = malloc(len + 1); fread(content, 1, len, f); content[len] = '\0'; fclose(f); Properties* props = extract_properties(argv[1], content, len); print_properties(props); // Free resources free(props->directives); free(props); free(content); // Example write: write_file("output.shtm", content, len); return 0; } // ===== end task-662 .SHTM ===== // ===== task-663 .SHTML [C] ===== #include #include #include #include #include typedef struct { char *filepath; char *content; long size; } SHTMLHandler; SHTMLHandler* shtml_create(const char *filepath) { SHTMLHandler *handler = malloc(sizeof(SHTMLHandler)); if (!handler) return NULL; handler->filepath = strdup(filepath); handler->content = NULL; handler->size = 0; struct stat st; if (stat(filepath, &st) != 0 || !strstr(filepath, ".shtml")) { free(handler->filepath); free(handler); return NULL; } handler->size = st.st_size; return handler; } void shtml_destroy(SHTMLHandler *handler) { if (handler) { free(handler->content); free(handler->filepath); free(handler); } } char* shtml_read(SHTMLHandler *handler) { FILE *f = fopen(handler->filepath, "r"); if (!f) return NULL; fseek(f, 0, SEEK_END); long fsize = ftell(f); rewind(f); handler->content = malloc(fsize + 1); fread(handler->content, 1, fsize, f); handler->content[fsize] = '\0'; fclose(f); return handler->content; } void shtml_write(SHTMLHandler *handler, char *new_content) { if (!new_content) new_content = handler->content; FILE *f = fopen(handler->filepath, "w"); if (f) { fputs(new_content, f); fclose(f); } } void shtml_print_properties(SHTMLHandler *handler) { if (!handler->content) shtml_read(handler); printf("File: %s\n", handler->filepath); printf("Size: %ld characters\n", handler->size); printf("Encoding: UTF-8\n"); printf("\nFormat Properties:\n"); printf("- Extension: .shtml\n"); printf("- MIME Type: text/html\n"); printf("- Directive Syntax: \n"); printf("- Supported Elements: comment, config, echo, exec, fsize, flastmod, include, printenv, set, if/elif/else/endif\n"); printf("- Built-in Variables: DATE_GMT, DATE_LOCAL, DOCUMENT_NAME, etc.\n"); printf("- Default Time Format: %%A, %%d-%%b-%%Y %%H:%%M:%%S %%Z\n"); printf("- Default Size Format: bytes\n"); printf("- Default Undefined Echo: (none)\n"); printf("- Default Error Msg: [an error occurred while processing this directive]\n"); // Simple regex for directives (POSIX) regex_t regex; regcomp(®ex, "", REG_EXTENDED); regmatch_t matches[10]; int num_directives = 0; char *unique_elements[20]; // Limited int num_unique = 0; char *ptr = handler->content; while (regexec(®ex, ptr, 1, matches, 0) == 0) { num_directives++; // Extract element (basic parse) char *start = ptr + matches[0].rm_so + 6; // Skip (\\d{2}:\\d{2}:\\d{2},\\d{3})$"))) { currentSub.start = match[1]; currentSub.end = match[2]; state = "text"; } } else if (state == "text") { currentSub.text.push_back(l); } } if (inSub) { subtitles.push_back(currentSub); } } void printProperties() { std::cout << "SRT File Properties:" << std::endl; std::cout << "Encoding: " << properties["encoding"] << std::endl; std::cout << "Line Endings: " << (properties["line_endings"] == "\r\n" ? "\\r\\n" : "\\n") << std::endl; std::cout << "Has Header/Footer: " << properties["has_header_footer"] << std::endl; std::cout << "Number of Subtitles: " << subtitles.size() << std::endl; std::cout << "Subtitle Blocks:" << std::endl; for (const auto& sub : subtitles) { std::cout << "Number: " << sub.number << std::endl; std::cout << "Start: " << sub.start << std::endl; std::cout << "End: " << sub.end << std::endl; std::cout << "Text:" << std::endl; for (const auto& textLine : sub.text) { std::cout << textLine << std::endl; } std::cout << "---" << std::endl; } } void write(const std::string& filepath) { std::ofstream file(filepath); if (!file.is_open()) { throw std::runtime_error("Could not open file for writing."); } std::string lineEnd = properties["line_endings"]; for (const auto& sub : subtitles) { file << sub.number << lineEnd; file << sub.start << " --> " << sub.end << lineEnd; for (const auto& textLine : sub.text) { file << textLine << lineEnd; } file << lineEnd; } file.close(); } }; // Example usage: // int main() { // try { // SRTHandler handler; // handler.read("example.srt"); // handler.printProperties(); // handler.write("output.srt"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-684 .SRT ===== // ===== task-685 .SRX [C++] ===== #include #include #include "tinyxml2.h" // Assume TinyXML-2 is available: https://github.com/leethomason/tinyxml2 using namespace tinyxml2; class SRXHandler { private: std::string filename; XMLDocument doc; public: SRXHandler(const std::string& fn) : filename(fn) {} bool readAndDecode() { if (doc.LoadFile(filename.c_str()) != XML_SUCCESS) { std::cout << "Error loading file." << std::endl; return false; } return true; } void printProperties() { XMLElement* sparql = doc.FirstChildElement("sparql"); if (!sparql) { std::cout << "Invalid .SRX format." << std::endl; return; } const char* schemaLoc = sparql->Attribute("xsi:schemaLocation"); std::cout << "Root: sparql (schemaLocation: " << (schemaLoc ? schemaLoc : "none") << ")" << std::endl; XMLElement* head = sparql->FirstChildElement("head"); if (head) { std::cout << "Head:" << std::endl; for (XMLElement* var = head->FirstChildElement("variable"); var; var = var->NextSiblingElement("variable")) { std::cout << " Variable name: " << var->Attribute("name") << std::endl; } for (XMLElement* link = head->FirstChildElement("link"); link; link = link->NextSiblingElement("link")) { std::cout << " Link href: " << link->Attribute("href") << std::endl; } } XMLElement* results = sparql->FirstChildElement("results"); if (results) { std::cout << "Results:" << std::endl; int i = 1; for (XMLElement* result = results->FirstChildElement("result"); result; result = result->NextSiblingElement("result"), ++i) { std::cout << " Result " << i << ":" << std::endl; for (XMLElement* binding = result->FirstChildElement("binding"); binding; binding = binding->NextSiblingElement("binding")) { const char* name = binding->Attribute("name"); XMLElement* child = binding->FirstChildElement(); std::string tag = child->Name(); std::string value = child->GetText() ? child->GetText() : ""; if (tag == "literal") { const char* lang = child->Attribute("xml:lang"); const char* datatype = child->Attribute("datatype"); value += " (lang: " + std::string(lang ? lang : "") + ", datatype: " + std::string(datatype ? datatype : "") + ")"; } std::cout << " Binding " << name << ": " << tag << " = " << value << std::endl; } } } XMLElement* booleanElem = sparql->FirstChildElement("boolean"); if (booleanElem) { std::cout << "Boolean: " << (booleanElem->GetText() ? booleanElem->GetText() : "") << std::endl; } } void writeSample(const std::string& outputFilename) { XMLDocument newDoc; XMLDeclaration* decl = newDoc.NewDeclaration(); newDoc.InsertFirstChild(decl); XMLElement* root = newDoc.NewElement("sparql"); root->SetAttribute("xmlns", "http://www.w3.org/2005/sparql-results#"); newDoc.InsertEndChild(root); XMLElement* head = newDoc.NewElement("head"); root->InsertEndChild(head); XMLElement* var = newDoc.NewElement("variable"); var->SetAttribute("name", "x"); head->InsertEndChild(var); XMLElement* results = newDoc.NewElement("results"); root->InsertEndChild(results); XMLElement* result = newDoc.NewElement("result"); results->InsertEndChild(result); XMLElement* binding = newDoc.NewElement("binding"); binding->SetAttribute("name", "x"); result->InsertEndChild(binding); XMLElement* uri = newDoc.NewElement("uri"); uri->SetText("http://example.org"); binding->InsertEndChild(uri); newDoc.SaveFile(outputFilename.c_str()); } }; // Example usage: // int main() { // SRXHandler handler("example.srx"); // if (handler.readAndDecode()) { // handler.printProperties(); // } // handler.writeSample("output.srx"); // return 0; // } // ===== end task-685 .SRX ===== // ===== task-686 .SSC [C++] ===== #include #include #include #include #include #include #include class SSCFile { private: std::vector> objects; // Requires C++17 for std::any public: SSCFile(const std::string& filename = "") { if (!filename.empty()) { read(filename); } } void read(const std::string& filename) { std::ifstream file(filename); std::string line; std::vector*> stack; std::map* currentObject = nullptr; std::map* currentBlock = nullptr; while (std::getline(file, line)) { line = std::regex_replace(line, std::regex("^\\s+|\\s+$"), ""); if (line.empty() || line[0] == '#') continue; if (line.find('{') != std::string::npos) { std::string header = line.substr(0, line.find('{')); header = std::regex_replace(header, std::regex("^\\s+|\\s+$"), ""); std::vector parts; std::stringstream ss(header); std::string part; while (ss >> part) { part = std::regex_replace(part, std::regex("\""), ""); parts.push_back(part); } if (parts.size() >= 2) { std::map newObj; std::string type = ""; std::string name = parts[0]; std::vector types = {"AltSurface", "Location", "ReferencePoint", "Modify", "Replace"}; if (std::find(types.begin(), types.end(), parts[0]) != types.end()) { type = parts[0]; name = parts[1]; } newObj["type"] = type; newObj["name"] = name; newObj["path"] = parts.back(); newObj["properties"] = std::map{}; objects.push_back(newObj); currentObject = &objects.back(); currentBlock = &std::any_cast&>((*currentObject)["properties"]); stack.clear(); stack.push_back(currentBlock); } else { std::string key = parts[0]; (*currentBlock)[key] = std::map{}; stack.push_back(&std::any_cast&>((*currentBlock)[key])); currentBlock = stack.back(); } } else if (line == "}") { stack.pop_back(); currentBlock = stack.empty() ? nullptr : stack.back(); } else if (currentBlock) { std::smatch match; if (std::regex_match(line, match, std::regex("(\\w+)\\s+(.*)"))) { std::string key = match[1]; std::string value = match[2]; value = std::regex_replace(value, std::regex("^\\s+|\\s+$"), ""); if (value[0] == '[') { std::vector list; std::smatch numMatch; std::string nums = value.substr(1, value.size() - 2); std::regex numRegex("[\\d.]+"); auto iter = std::sregex_iterator(nums.begin(), nums.end(), numRegex); for (auto i = iter; i != std::sregex_iterator(); ++i) { list.push_back(std::stof((*i).str())); } (*currentBlock)[key] = list; } else { try { (*currentBlock)[key] = std::stof(value); } catch (...) { if (value == "true" || value == "false") { (*currentBlock)[key] = (value == "true"); } else { value = std::regex_replace(value, std::regex("\""), ""); (*currentBlock)[key] = value; } } } } } } } void write(const std::string& filename) { std::ofstream file(filename); for (auto& obj : objects) { std::string typePrefix = std::any_cast(obj["type"]).empty() ? "" : std::any_cast(obj["type"]) + " "; file << typePrefix << "\"" << std::any_cast(obj["name"]) << "\" \"" << std::any_cast(obj["path"]) << "\" {\n"; writeProperties(file, std::any_cast>(obj["properties"]), 1); file << "}\n\n"; } } private: void writeProperties(std::ofstream& file, const std::map& props, int indent) { std::string ind(indent * 2, ' '); for (const auto& [key, value] : props) { if (value.type() == typeid(std::map)) { file << ind << key << " {\n"; writeProperties(file, std::any_cast>(value), indent + 1); file << ind << "}\n"; } else if (value.type() == typeid(std::vector)) { file << ind << key << " ["; for (auto v : std::any_cast>(value)) file << " " << v; file << " ]\n"; } else if (value.type() == typeid(bool)) { file << ind << key << " " << (std::any_cast(value) ? "true" : "false") << "\n"; } else { std::string valStr = std::any_cast(value); // Assume string for non-numeric if (valStr.find(' ') != std::string::npos && valStr[0] != '"') valStr = "\"" + valStr + "\""; file << ind << key << " " << valStr << "\n"; } } } public: void printProperties() { // Simple console output; implement JSON-like if needed for (const auto& obj : objects) { std::cout << "{ \"type\": \"" << std::any_cast(obj.at("type")) << "\", \"name\": \"" << std::any_cast(obj.at("name")) << "\", \"path\": \"" << std::any_cast(obj.at("path")) << "\", \"properties\": { ... } }" << std::endl; } } }; // Example usage: // int main() { // SSCFile ssc("example.ssc"); // ssc.printProperties(); // ssc.write("output.ssc"); // return 0; // } // ===== end task-686 .SSC ===== // ===== task-687 .ST [C++] ===== #include #include #include #include #include #include #include class STFile { private: std::string filepath; std::vector data; std::map properties; public: STFile(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) throw std::runtime_error("Cannot open file"); auto size = file.tellg(); file.seekg(0); data.resize(size); file.read(reinterpret_cast(data.data()), size); if (data.size() % 512 != 0) throw std::runtime_error("Invalid .ST file size"); parseProperties(); } void parseProperties() { auto le16 = [](const uint8_t* p) { return p[0] | (p[1] << 8); }; auto be16 = [](const uint8_t* p) { return (p[0] << 8) | p[1]; }; properties["File Size (bytes)"] = std::to_string(data.size()); properties["Total Sectors"] = std::to_string(data.size() / 512); properties["Bytes Per Sector"] = std::to_string(le16(&data[0x0B])); properties["Sectors Per Cluster"] = std::to_string(data[0x0D]); properties["Reserved Sectors"] = std::to_string(le16(&data[0x0E])); properties["Number of FATs"] = std::to_string(data[0x10]); properties["Root Directory Entries"] = std::to_string(le16(&data[0x11])); properties["Total Sectors (from boot)"] = std::to_string(le16(&data[0x13])); properties["Media Descriptor"] = std::to_string(data[0x15]); properties["Sectors Per FAT"] = std::to_string(le16(&data[0x16])); properties["Sectors Per Track"] = std::to_string(le16(&data[0x18])); properties["Number of Heads (Sides)"] = std::to_string(le16(&data[0x1A])); properties["Hidden Sectors"] = std::to_string(le16(&data[0x1C])); uint32_t serial = le16(&data[0x08]) | (data[0x0A] << 16); properties["Volume Serial Number"] = std::to_string(serial); uint32_t checksum = 0; for (size_t i = 0; i < 512; i += 2) checksum = (checksum + be16(&data[i])) & 0xFFFF; properties["Boot Checksum"] = std::to_string(checksum); properties["Bootable Flag"] = (checksum == 0x1234) ? "True" : "False"; properties["Filesystem Type"] = "FAT12"; uint32_t spt = std::stoul(properties["Sectors Per Track"]); uint32_t heads = std::stoul(properties["Number of Heads (Sides)"]); properties["Number of Tracks"] = std::to_string(std::stoul(properties["Total Sectors"]) / (spt * heads)); uint32_t reserved = std::stoul(properties["Reserved Sectors"]); uint32_t fats = std::stoul(properties["Number of FATs"]); uint32_t spf = std::stoul(properties["Sectors Per FAT"]); uint32_t rootEntries = std::stoul(properties["Root Directory Entries"]); size_t rootStart = (reserved + fats * spf) * 512; std::string volumeLabel; uint32_t fileCount = 0; for (uint32_t i = 0; i < rootEntries; ++i) { size_t offset = rootStart + i * 32; if (data[offset] == 0) break; if (data[offset] != 0xE5) ++fileCount; if (data[offset + 11] == 0x08) { volumeLabel.assign(reinterpret_cast(&data[offset]), 11); volumeLabel.erase(std::remove(volumeLabel.begin(), volumeLabel.end(), ' '), volumeLabel.end()); } } properties["Volume Label"] = volumeLabel; properties["Number of Files/Directories"] = std::to_string(fileCount); size_t fatStart = reserved * 512; uint32_t freeClusters = 0; uint32_t spc = std::stoul(properties["Sectors Per Cluster"]); uint32_t bps = std::stoul(properties["Bytes Per Sector"]); uint32_t numClusters = (std::stoul(properties["Total Sectors"]) - reserved - (fats * spf) - (rootEntries * 32 / 512)) / spc; for (uint32_t cl = 2; cl < numClusters + 2; ++cl) { size_t byteOffset = fatStart + (cl * 3 / 2); uint16_t entry = le16(&data[byteOffset - (cl % 2)]); if (cl % 2 == 1) entry >>= 4; entry &= 0xFFF; if (entry == 0) ++freeClusters; } properties["Free Space (bytes)"] = std::to_string(freeClusters * spc * bps); } void printProperties() { for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } void write(const std::string& newFilepath = "") { if (data.empty()) throw std::runtime_error("No data to write"); std::ofstream file(newFilepath.empty() ? filepath : newFilepath, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); // Modify data vector for changes } }; // Example usage: // int main() { // STFile st("example.st"); // st.read(); // st.printProperties(); // st.write("modified.st"); // return 0; // } // ===== end task-687 .ST ===== // ===== task-688 .STC [C++] ===== #include #include #include #include #include struct Sample { uint8_t num; std::vector> data; // 32 entries uint8_t rep_pos; uint8_t rep_len; }; struct Position { int8_t trans; uint8_t pat_num; }; struct Ornament { uint8_t num; std::vector data; // 32 entries }; struct Pattern { uint8_t num; uint16_t ch_a, ch_b, ch_c; std::vector data_a, data_b, data_c; }; class STCFile { private: uint8_t delay; uint16_t pos_ptr; uint16_t orn_ptr; uint16_t pat_ptr; char identifier[19]; uint16_t size; std::vector samples; std::vector positions; std::vector ornaments; std::vector patterns; public: STCFile(const std::string& filename) { read(filename); } void read(const std::string& filename) { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) throw std::runtime_error("Cannot open file"); size_t len = file.tellg(); file.seekg(0); std::vector data(len); file.read(reinterpret_cast(data.data()), len); delay = data[0]; pos_ptr = *reinterpret_cast(&data[1]); orn_ptr = *reinterpret_cast(&data[3]); pat_ptr = *reinterpret_cast(&data[5]); memcpy(identifier, &data[7], 18); identifier[18] = '\0'; size = *reinterpret_cast(&data[25]); uint16_t min_ptr = std::min(pos_ptr, std::min(orn_ptr, pat_ptr)); size_t offset = 27; while (offset + 99 <= min_ptr && offset < len) { uint8_t num = data[offset]; if (num < 1 || num > 16) break; Sample s; s.num = num; for (int i = 0; i < 32; ++i) { size_t base = offset + 1 + i * 3; std::array d = {data[base], data[base+1], data[base+2]}; s.data.push_back(d); } s.rep_pos = data[offset + 97]; s.rep_len = data[offset + 98]; samples.push_back(s); offset += 99; } if (pos_ptr >= len) throw std::runtime_error("Invalid pos_ptr"); uint8_t pos_count = data[pos_ptr]; for (uint8_t i = 0; i < pos_count; ++i) { size_t base = pos_ptr + 1 + i * 2; Position p; p.trans = *reinterpret_cast(&data[base]); p.pat_num = data[base + 1]; positions.push_back(p); } offset = orn_ptr; for (int i = 0; i < 16; ++i) { if (offset >= len) break; uint8_t num = data[offset]; if (num > 15) break; Ornament o; o.num = num; for (int j = 1; j < 33; ++j) { o.data.push_back(*reinterpret_cast(&data[offset + j])); } ornaments.push_back(o); offset += 33; } offset = pat_ptr; while (offset < len) { uint8_t num = data[offset]; if (num == 0 || num > 32) break; uint16_t ch_a = *reinterpret_cast(&data[offset + 1]); uint16_t ch_b = *reinterpret_cast(&data[offset + 3]); uint16_t ch_c = *reinterpret_cast(&data[offset + 5]); auto read_pat = [&data, len](uint16_t start) -> std::vector { if (start >= len) return {}; std::vector d; size_t end = start; while (end < len) { uint8_t b = data[end]; d.push_back(b); if (b == 0xff) break; ++end; } return d; }; Pattern p; p.num = num; p.ch_a = ch_a; p.ch_b = ch_b; p.ch_c = ch_c; p.data_a = read_pat(ch_a); p.data_b = read_pat(ch_b); p.data_c = read_pat(ch_c); patterns.push_back(p); offset += 7; } } void printProperties() const { std::cout << "Global Delay: " << static_cast(delay) << std::endl; std::cout << "Positions Pointer: " << pos_ptr << std::endl; std::cout << "Ornaments Pointer: " << orn_ptr << std::endl; std::cout << "Patterns Pointer: " << pat_ptr << std::endl; std::cout << "Identifier: " << identifier << std::endl; std::cout << "Size: " << size << std::endl; std::cout << "Samples (" << samples.size() << "):" << std::endl; for (size_t i = 0; i < samples.size(); ++i) { const auto& s = samples[i]; std::cout << " Sample " << (i + 1) << " (Num: " << static_cast(s.num) << ", Rep Pos: " << static_cast(s.rep_pos) << ", Rep Len: " << static_cast(s.rep_len) << ")" << std::endl; std::cout << " Data: "; for (const auto& d : s.data) std::cout << "[" << static_cast(d[0]) << "," << static_cast(d[1]) << "," << static_cast(d[2]) << "] "; std::cout << std::endl; } std::cout << "Positions (" << positions.size() << "):" << std::endl; for (size_t i = 0; i < positions.size(); ++i) { const auto& p = positions[i]; std::cout << " Pos " << i << ": Transposition " << static_cast(p.trans) << ", Pattern Num " << static_cast(p.pat_num) << std::endl; } std::cout << "Ornaments (" << ornaments.size() << "):" << std::endl; for (size_t i = 0; i < ornaments.size(); ++i) { const auto& o = ornaments[i]; std::cout << " Ornament " << i << " (Num: " << static_cast(o.num) << ")" << std::endl; std::cout << " Data: "; for (auto d : o.data) std::cout << static_cast(d) << " "; std::cout << std::endl; } std::cout << "Patterns (" << patterns.size() << "):" << std::endl; for (const auto& p : patterns) { std::cout << " Pattern " << static_cast(p.num) << ": ChA " << p.ch_a << ", ChB " << p.ch_b << ", ChC " << p.ch_c << std::endl; std::cout << " ChA Data: "; for (auto b : p.data_a) std::cout << static_cast(b) << " "; std::cout << std::endl; std::cout << " ChB Data: "; for (auto b : p.data_b) std::cout << static_cast(b) << " "; std::cout << std::endl; std::cout << " ChC Data: "; for (auto b : p.data_c) std::cout << static_cast(b) << " "; std::cout << std::endl; } } void write(const std::string& filename) const { // Placeholder for write/encode. std::ofstream file(filename, std::ios::binary); if (!file) return; // Write header, etc. } }; // Example: STCFile stc("example.stc"); stc.printProperties(); stc.write("output.stc"); // ===== end task-688 .STC ===== // ===== task-689 .STD [C] ===== #include #include #include #include typedef struct { char* filename; // List of records, each with type, sub, map of fields (use struct or array) // For simplicity, use linked list or array } StdfParser; uint8_t read_u1(FILE *f) { uint8_t v; fread(&v, 1, 1, f); return v; } uint16_t read_u2(FILE *f) { uint16_t v; fread(&v, 2, 1, f); return v; } // Similar for other types // For cn char* read_cn(FILE *f) { uint8_t len = read_u1(f); char* str = malloc(len + 1); fread(str, 1, len, f); str[len] = '\0'; return str; } // Parse function similar to Python, using switch for typ/sub, read fields void print_properties(StdfParser *parser) { // Loop over records, printf each field } // Write similar, fopen wb, fwrite headers and fields StdfParser* stdf_parser_new(const char* filename) { StdfParser* p = malloc(sizeof(StdfParser)); p->filename = strdup(filename); // Read return p; } void stdf_parser_free(StdfParser *p) { free(p->filename); free(p); } int main(int argc, char** argv) { if (argc > 1) { StdfParser* parser = stdf_parser_new(argv[1]); print_properties(parser); // Write to "output.std" stdf_parser_free(parser); } return 0; } // ===== end task-689 .STD ===== // ===== task-690 .STEP [C++] ===== #include #include #include #include #include #include #include #include using PropertyValue = std::variant>; class StepFile { private: std::string filepath; std::map properties; std::string header_raw; std::string rest_of_file; PropertyValue parse_params(const std::string& params_str) { std::vector tokens; std::string current; bool in_string = false; int in_list = 0; for (char ch : params_str) { if (ch == '\'' && !in_string) { in_string = true; current += ch; } else if (ch == '\'' && in_string && !current.empty() && current.back() == '\\') { current += ch; } else if (ch == '\'' && in_string) { in_string = false; current += ch; tokens.emplace_back(current); current.clear(); } else if (ch == '(' && !in_string) { ++in_list; current += ch; } else if (ch == ')' && !in_string) { --in_list; current += ch; } else if (ch == ',' && !in_string && in_list == 0) { tokens.emplace_back(current); current.clear(); } else { current += ch; } } if (!current.empty()) { tokens.emplace_back(current); } std::vector result; for (auto& token_var : tokens) { if (auto token = std::get_if(&token_var)) { token->erase(std::remove_if(token->begin(), token->end(), isspace), token->end()); // Trim if (token->front() == '(' && token->back() == ')') { result.push_back(parse_params(token->substr(1, token->size() - 2))); } else if (token->front() == '\'' && token->back() == '\'') { std::string str = token->substr(1, token->size() - 2); size_t pos; while ((pos = str.find("''")) != std::string::npos) { str.replace(pos, 2, "'"); } result.emplace_back(str); } else if (*token == "$") { result.emplace_back(nullptr); } else if (*token == "*") { result.emplace_back("derived"); } else { try { if (token->find('.') != std::string::npos || token->find('e') != std::string::npos || token->find('E') != std::string::npos) { result.emplace_back(std::stod(*token)); } else { result.emplace_back(std::stoi(*token)); } } catch (...) { result.emplace_back(*token); } } } } return result.size() == 1 ? result[0] : PropertyValue(result); } std::string serialize_params(const PropertyValue& params) { if (std::holds_alternative(params)) { return "$"; } else if (auto str = std::get_if(¶ms)) { if (*str == "derived") return "*"; std::string escaped = *str; size_t pos = 0; while ((pos = escaped.find("'", pos)) != std::string::npos) { escaped.replace(pos, 1, "''"); pos += 2; } return "'" + escaped + "'"; } else if (auto num_d = std::get_if(¶ms)) { return std::to_string(*num_d); } else if (auto num_i = std::get_if(¶ms)) { return std::to_string(*num_i); } else if (auto list = std::get_if>(¶ms)) { std::stringstream ss; for (size_t i = 0; i < list->size(); ++i) { ss << serialize_params((*list)[i]); if (i < list->size() - 1) ss << ","; } return ss.str(); } return ""; } void print_value(const PropertyValue& val, int indent = 0) { if (std::holds_alternative(val)) { std::cout << "null"; } else if (auto str = std::get_if(&val)) { std::cout << "\"" << *str << "\""; } else if (auto num_d = std::get_if(&val)) { std::cout << *num_d; } else if (auto num_i = std::get_if(&val)) { std::cout << *num_i; } else if (auto list = std::get_if>(&val)) { std::cout << "[\n"; for (const auto& item : *list) { std::cout << std::string(indent + 2, ' '); print_value(item, indent + 2); std::cout << ",\n"; } std::cout << std::string(indent, ' ') << "]"; } } public: StepFile(const std::string& fp) : filepath(fp) { read_and_decode(); } void read_and_decode() { std::ifstream file(filepath, std::ios::binary); std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); if (content.substr(0, 13) != "ISO-10303-21;") { throw std::runtime_error("Not a valid .STEP file"); } std::regex header_regex(R"(HEADER;(.*?)ENDSEC;)", std::regex::dotall); std::smatch header_match; if (!std::regex_search(content, header_match, header_regex)) { throw std::runtime_error("No HEADER section found"); } header_raw = header_match[1].str(); size_t end_pos = header_match.position() + header_match.length(); rest_of_file = content.substr(end_pos); // Remove comments std::regex comment_regex(R"(/\*.*?\*/)", std::regex::dotall); std::string header = std::regex_replace(header_raw, comment_regex, ""); // Find entities std::regex entity_regex(R"(([A-Z_!]+)\((.*?)\);)", std::regex::dotall); std::sregex_iterator iter(header.begin(), header.end(), entity_regex); std::sregex_iterator end; for (; iter != end; ++iter) { std::string key = iter->str(1); std::transform(key.begin(), key.end(), key.begin(), ::tolower); std::replace(key.begin(), key.end(), '!', 'user_'); std::string params_str = iter->str(2); PropertyValue params = parse_params(params_str); properties[key] = params; } } void print_properties() { std::cout << "{\n"; for (const auto& [key, val] : properties) { std::cout << " \"" << key << "\": "; print_value(val, 2); std::cout << ",\n"; } std::cout << "}\n"; } void write(const std::string& new_filepath, const std::map& updated_properties = {}) { for (const auto& [k, v] : updated_properties) { properties[k] = v; } std::stringstream header_ss; header_ss << "ISO-10303-21;\nHEADER;\n"; for (const auto& [key, params] : properties) { std::string orig_key = key; std::transform(orig_key.begin(), orig_key.end(), orig_key.begin(), ::toupper); std::replace(orig_key.begin(), orig_key.end(), 'USER_', "!"); std::string params_str = serialize_params(params); header_ss << orig_key << "(" << params_str << ");\n"; } header_ss << "ENDSEC;"; std::ofstream out(new_filepath, std::ios::binary); out << header_ss.str() << rest_of_file; } }; // Example usage: // int main() { // StepFile sf("example.step"); // sf.print_properties(); // std::map updates; // updates["file_name"] = std::vector{"new_name", "2025-11-22T00:00:00", std::vector{"author"}, std::vector{"org"}, "v1", "sys", "auth"}; // sf.write("modified.step", updates); // return 0; // } // ===== end task-690 .STEP ===== // ===== task-691 .STI [C] ===== #include #include #include #include typedef struct { uint32_t data_offset; uint32_t data_size; uint16_t x_offset; uint16_t y_offset; uint16_t height; uint16_t width; } SubImage; typedef struct { char *filename; char format_id[5]; uint32_t original_size; uint32_t compressed_size; uint32_t transparent_index; uint32_t flags; uint16_t height; uint16_t width; union { struct { uint32_t red_mask; uint32_t green_mask; uint32_t blue_mask; uint32_t alpha_mask; uint8_t red_depth; uint8_t green_depth; uint8_t blue_depth; uint8_t alpha_depth; } bit16; struct { uint32_t num_colors; uint16_t num_subimages; uint8_t red_depth; uint8_t green_depth; uint8_t blue_depth; } bit8; } color_details; uint8_t color_depth; uint32_t app_data_size; uint8_t *palette; SubImage *subimages; uint8_t *image_data; uint8_t *app_data; } STIFile; STIFile *sti_create(const char *filename) { STIFile *sti = malloc(sizeof(STIFile)); memset(sti, 0, sizeof(STIFile)); sti->filename = strdup(filename); return sti; } void sti_read(STIFile *sti, const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) return; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); memcpy(sti->format_id, data, 4); sti->format_id[4] = '\0'; memcpy(&sti->original_size, data + 4, 4); memcpy(&sti->compressed_size, data + 8, 4); memcpy(&sti->transparent_index, data + 12, 4); memcpy(&sti->flags, data + 16, 4); memcpy(&sti->height, data + 20, 2); memcpy(&sti->width, data + 22, 2); uint32_t is16bit = sti->flags & 0x08; uint32_t is8bit = sti->flags & 0x10; if (is16bit) { memcpy(&sti->color_details.bit16.red_mask, data + 24, 4); memcpy(&sti->color_details.bit16.green_mask, data + 28, 4); memcpy(&sti->color_details.bit16.blue_mask, data + 32, 4); memcpy(&sti->color_details.bit16.alpha_mask, data + 36, 4); memcpy(&sti->color_details.bit16.red_depth, data + 40, 1); memcpy(&sti->color_details.bit16.green_depth, data + 41, 1); memcpy(&sti->color_details.bit16.blue_depth, data + 42, 1); memcpy(&sti->color_details.bit16.alpha_depth, data + 43, 1); } else if (is8bit) { memcpy(&sti->color_details.bit8.num_colors, data + 24, 4); memcpy(&sti->color_details.bit8.num_subimages, data + 28, 2); memcpy(&sti->color_details.bit8.red_depth, data + 30, 1); memcpy(&sti->color_details.bit8.green_depth, data + 31, 1); memcpy(&sti->color_details.bit8.blue_depth, data + 32, 1); sti->palette = malloc(768); memcpy(sti->palette, data + 64, 768); int num_sub = sti->color_details.bit8.num_subimages; sti->subimages = malloc(num_sub * sizeof(SubImage)); int sub_start = 64 + 768; for (int i = 0; i < num_sub; i++) { int off = sub_start + i * 16; memcpy(&sti->subimages[i].data_offset, data + off, 4); memcpy(&sti->subimages[i].data_size, data + off + 4, 4); memcpy(&sti->subimages[i].x_offset, data + off + 8, 2); memcpy(&sti->subimages[i].y_offset, data + off + 10, 2); memcpy(&sti->subimages[i].height, data + off + 12, 2); memcpy(&sti->subimages[i].width, data + off + 14, 2); } int image_start = sub_start + num_sub * 16; sti->image_data = malloc(sti->compressed_size); memcpy(sti->image_data, data + image_start, sti->compressed_size); } sti->color_depth = data[44]; memcpy(&sti->app_data_size, data + 45, 4); if (sti->app_data_size > 0) { int app_start = 64 + (is8bit ? 768 + sti->color_details.bit8.num_subimages * 16 + sti->compressed_size : sti->compressed_size); sti->app_data = malloc(sti->app_data_size); memcpy(sti->app_data, data + app_start, sti->app_data_size); } free(data); } void sti_print_properties(const STIFile *sti) { printf("Format Identifier: %s\n", sti->format_id); printf("Original Size: %u\n", sti->original_size); printf("Compressed Size: %u\n", sti->compressed_size); printf("Transparent Index: %u\n", sti->transparent_index); printf("Flags: %u (0x%x)\n", sti->flags, sti->flags); printf("Height: %hu\n", sti->height); printf("Width: %hu\n", sti->width); uint32_t is16bit = sti->flags & 0x08; uint32_t is8bit = sti->flags & 0x10; if (is16bit) { printf("Red Mask: %u\n", sti->color_details.bit16.red_mask); printf("Green Mask: %u\n", sti->color_details.bit16.green_mask); printf("Blue Mask: %u\n", sti->color_details.bit16.blue_mask); printf("Alpha Mask: %u\n", sti->color_details.bit16.alpha_mask); printf("Red Depth: %u\n", sti->color_details.bit16.red_depth); printf("Green Depth: %u\n", sti->color_details.bit16.green_depth); printf("Blue Depth: %u\n", sti->color_details.bit16.blue_depth); printf("Alpha Depth: %u\n", sti->color_details.bit16.alpha_depth); } else if (is8bit) { printf("Number of Colors: %u\n", sti->color_details.bit8.num_colors); printf("Number of Subimages: %hu\n", sti->color_details.bit8.num_subimages); printf("Red Depth: %u\n", sti->color_details.bit8.red_depth); printf("Green Depth: %u\n", sti->color_details.bit8.green_depth); printf("Blue Depth: %u\n", sti->color_details.bit8.blue_depth); } printf("Color Depth: %u\n", sti->color_depth); printf("App Data Size: %u\n", sti->app_data_size); if (sti->palette) { printf("Palette (first 5 colors):\n"); for (int i = 0; i < 5; i++) { int offset = i * 3; printf("Color %d: R=%u G=%u B=%u\n", i, sti->palette[offset], sti->palette[offset+1], sti->palette[offset+2]); } } if (sti->subimages) { printf("Subimages:\n"); for (int i = 0; i < sti->color_details.bit8.num_subimages; i++) { SubImage sub = sti->subimages[i]; printf("Subimage %d: Data Offset %u, Data Size %u, X Offset %hu, Y Offset %hu, Height %hu, Width %hu\n", i, sub.data_offset, sub.data_size, sub.x_offset, sub.y_offset, sub.height, sub.width); } } if (sti->app_data_size > 0) { printf("Application Data present (size %u bytes)\n", sti->app_data_size); } } void sti_write(const STIFile *sti, const char *filename) { FILE *f = fopen(filename ? filename : sti->filename, "wb"); if (!f) return; fwrite(sti->format_id, 1, 4, f); fwrite(&sti->original_size, 4, 1, f); fwrite(&sti->compressed_size, 4, 1, f); fwrite(&sti->transparent_index, 4, 1, f); fwrite(&sti->flags, 4, 1, f); fwrite(&sti->height, 2, 1, f); fwrite(&sti->width, 2, 1, f); uint32_t is16bit = sti->flags & 0x08; uint32_t is8bit = sti->flags & 0x10; if (is16bit) { fwrite(&sti->color_details.bit16, sizeof(sti->color_details.bit16), 1, f); } else if (is8bit) { fwrite(&sti->color_details.bit8, sizeof(sti->color_details.bit8), 1, f); char pad[11] = {0}; fwrite(pad, 1, 11, f); } fwrite(&sti->color_depth, 1, 1, f); fwrite(&sti->app_data_size, 4, 1, f); char reserved[16] = {0}; fwrite(reserved, 1, 16, f); if (sti->palette) { fwrite(sti->palette, 1, 768, f); for (int i = 0; i < sti->color_details.bit8.num_subimages; i++) { fwrite(&sti->subimages[i], sizeof(SubImage), 1, f); } } if (sti->image_data) { fwrite(sti->image_data, 1, sti->compressed_size, f); } if (sti->app_data) { fwrite(sti->app_data, 1, sti->app_data_size, f); } fclose(f); } void sti_free(STIFile *sti) { free(sti->filename); free(sti->palette); free(sti->subimages); free(sti->image_data); free(sti->app_data); free(sti); } // Example usage: // int main() { // STIFile *sti = sti_create(NULL); // sti_read(sti, "example.sti"); // sti_print_properties(sti); // sti_write(sti, "output.sti"); // sti_free(sti); // return 0; // } // ===== end task-691 .STI ===== // ===== task-692 .STK [C] ===== #include #include #include typedef struct { char **comments; int num_comments; char *header; double insertion_x, insertion_y; double area; double perimeter; double rect_length, rect_width; double *vertices_x; double *vertices_y; int num_vertices; } STKFile; STKFile *stk_open(const char *filename) { STKFile *stk = malloc(sizeof(STKFile)); stk->comments = NULL; stk->num_comments = 0; stk->header = NULL; stk->vertices_x = NULL; stk->vertices_y = NULL; stk->num_vertices = 0; FILE *f = fopen(filename, "r"); if (f == NULL) return NULL; char line[1024]; double numbers[1024]; int num_numbers = 0; while (fgets(line, sizeof(line), f)) { char *trim = line; while (*trim == ' ') trim++; if (*trim == 0) continue; if (*trim == '#') { stk->num_comments++; stk->comments = realloc(stk->comments, stk->num_comments * sizeof(char*)); stk->comments[stk->num_comments - 1] = strdup(trim); } else if (*trim == '@') { stk->header = strdup(trim); } else { char *token = strtok(trim, " "); while (token) { numbers[num_numbers++] = atof(token); token = strtok(NULL, " "); } } } fclose(f); if (num_numbers >= 6) { stk->insertion_x = numbers[0]; stk->insertion_y = numbers[1]; stk->area = numbers[2]; stk->perimeter = numbers[3]; stk->rect_length = numbers[4]; stk->rect_width = numbers[5]; stk->num_vertices = (num_numbers - 6) / 2; stk->vertices_x = malloc(stk->num_vertices * sizeof(double)); stk->vertices_y = malloc(stk->num_vertices * sizeof(double)); for (int i = 0; i < stk->num_vertices; i++) { stk->vertices_x[i] = numbers[6 + i*2]; stk->vertices_y[i] = numbers[6 + i*2 + 1]; } } return stk; } void stk_print(STKFile *stk) { printf("Comments:\n"); for (int i = 0; i < stk->num_comments; i++) { printf("%s\n", stk->comments[i]); } printf("Header: %s\n", stk->header); printf("Insertion Point: (%f, %f)\n", stk->insertion_x, stk->insertion_y); printf("Area: %f\n", stk->area); printf("Perimeter: %f\n", stk->perimeter); printf("Rectangle Length: %f\n", stk->rect_length); printf("Rectangle Width: %f\n", stk->rect_width); printf("Vertices:\n"); for (int i = 0; i < stk->num_vertices; i++) { printf("(%f, %f)\n", stk->vertices_x[i], stk->vertices_y[i]); } } void stk_write(STKFile *stk, const char *filename) { FILE *f = fopen(filename, "w"); if (f == NULL) return; for (int i = 0; i < stk->num_comments; i++) { fprintf(f, "%s\n", stk->comments[i]); } if (stk->header) fprintf(f, "%s\n", stk->header); fprintf(f, "%f %f %f %f %f %f\n", stk->insertion_x, stk->insertion_y, stk->area, stk->perimeter, stk->rect_length, stk->rect_width); for (int i = 0; i < stk->num_vertices; i++) { fprintf(f, "%f %f\n", stk->vertices_x[i], stk->vertices_y[i]); } fclose(f); } void stk_close(STKFile *stk) { for (int i = 0; i < stk->num_comments; i++) { free(stk->comments[i]); } free(stk->comments); free(stk->header); free(stk->vertices_x); free(stk->vertices_y); free(stk); } // Example usage // int main() { // STKFile *stk = stk_open("example.stk"); // stk_print(stk); // stk_write(stk, "output.stk"); // stk_close(stk); // return 0; // } // ===== end task-692 .STK ===== // ===== task-694 .STM [C] ===== #include #include #include #include typedef struct { char song_name[21]; char tracker_name[9]; uint8_t id_marker; uint8_t file_type; uint8_t major_version; uint8_t minor_version; uint8_t tempo; uint8_t num_patterns; uint8_t global_volume; uint8_t reserved_header[13]; struct Instrument { char name[13]; uint8_t id; uint8_t disk; uint16_t reserved1; uint16_t length; uint16_t loop_start; uint16_t loop_end; uint8_t volume; uint8_t reserved2; uint16_t c3_freq; uint32_t reserved3; uint16_t para_length; } instruments[31]; uint8_t pattern_orders[64]; uint8_t** pattern_data; // Array of pointers to 1024-byte arrays uint8_t* sample_data; size_t sample_data_len; } STMFile; void stm_read(STMFile* stm, const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) { perror("Failed to open file"); exit(1); } fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); // Song Name strncpy(stm->song_name, (char*)data + 0x0000, 20); stm->song_name[20] = '\0'; // Tracker Name strncpy(stm->tracker_name, (char*)data + 0x0014, 8); stm->tracker_name[8] = '\0'; // ID stm->id_marker = data[0x001C]; // File Type stm->file_type = data[0x001D]; // Versions stm->major_version = data[0x001E]; stm->minor_version = data[0x001F]; // Tempo stm->tempo = data[0x0020]; // Num Patterns stm->num_patterns = data[0x0021]; // Global Volume stm->global_volume = data[0x0022]; // Reserved memcpy(stm->reserved_header, data + 0x0023, 13); // Instruments for (int i = 0; i < 31; i++) { size_t offset = 0x0030 + i * 30; strncpy(stm->instruments[i].name, (char*)data + offset, 12); stm->instruments[i].name[12] = '\0'; stm->instruments[i].id = data[offset + 12]; stm->instruments[i].disk = data[offset + 13]; memcpy(&stm->instruments[i].reserved1, data + offset + 14, 2); memcpy(&stm->instruments[i].length, data + offset + 16, 2); memcpy(&stm->instruments[i].loop_start, data + offset + 18, 2); memcpy(&stm->instruments[i].loop_end, data + offset + 20, 2); stm->instruments[i].volume = data[offset + 22]; stm->instruments[i].reserved2 = data[offset + 23]; memcpy(&stm->instruments[i].c3_freq, data + offset + 24, 2); memcpy(&stm->instruments[i].reserved3, data + offset + 26, 4); memcpy(&stm->instruments[i].para_length, data + offset + 30, 2); } // Pattern Orders memcpy(stm->pattern_orders, data + 0x03D0, 64); // Pattern Data size_t pattern_start = 0x0410; stm->pattern_data = malloc(stm->num_patterns * sizeof(uint8_t*)); for (uint8_t p = 0; p < stm->num_patterns; p++) { size_t pat_offset = pattern_start + p * 1024; stm->pattern_data[p] = malloc(1024); memcpy(stm->pattern_data[p], data + pat_offset, 1024); } // Sample Data size_t samples_start = pattern_start + stm->num_patterns * 1024; stm->sample_data_len = size - samples_start; stm->sample_data = malloc(stm->sample_data_len); memcpy(stm->sample_data, data + samples_start, stm->sample_data_len); free(data); } void stm_write(STMFile* stm, const char* filename) { FILE* f = fopen(filename, "wb"); if (!f) { perror("Failed to write file"); exit(1); } // Song Name char song_padded[20] = {0}; strncpy(song_padded, stm->song_name, 20); fwrite(song_padded, 1, 20, f); // Tracker Name fwrite(stm->tracker_name, 1, 8, f); // ID fwrite(&stm->id_marker, 1, 1, f); // File Type fwrite(&stm->file_type, 1, 1, f); // Versions fwrite(&stm->major_version, 1, 1, f); fwrite(&stm->minor_version, 1, 1, f); // Tempo fwrite(&stm->tempo, 1, 1, f); // Num Patterns fwrite(&stm->num_patterns, 1, 1, f); // Global Volume fwrite(&stm->global_volume, 1, 1, f); // Reserved fwrite(stm->reserved_header, 1, 13, f); // Instruments for (int i = 0; i < 31; i++) { char name_padded[12] = {0}; strncpy(name_padded, stm->instruments[i].name, 12); fwrite(name_padded, 1, 12, f); fwrite(&stm->instruments[i].id, 1, 1, f); fwrite(&stm->instruments[i].disk, 1, 1, f); fwrite(&stm->instruments[i].reserved1, 2, 1, f); fwrite(&stm->instruments[i].length, 2, 1, f); fwrite(&stm->instruments[i].loop_start, 2, 1, f); fwrite(&stm->instruments[i].loop_end, 2, 1, f); fwrite(&stm->instruments[i].volume, 1, 1, f); fwrite(&stm->instruments[i].reserved2, 1, 1, f); fwrite(&stm->instruments[i].c3_freq, 2, 1, f); fwrite(&stm->instruments[i].reserved3, 4, 1, f); fwrite(&stm->instruments[i].para_length, 2, 1, f); } // Pattern Orders fwrite(stm->pattern_orders, 1, 64, f); // Pattern Data for (uint8_t p = 0; p < stm->num_patterns; p++) { fwrite(stm->pattern_data[p], 1, 1024, f); } // Sample Data (pad to 16) fwrite(stm->sample_data, 1, stm->sample_data_len, f); size_t pad = (16 - stm->sample_data_len % 16) % 16; for (size_t i = 0; i < pad; i++) { uint8_t zero = 0; fwrite(&zero, 1, 1, f); } fclose(f); } void stm_print_properties(STMFile* stm) { printf("Song Name: %s\n", stm->song_name); printf("Tracker Name: %s\n", stm->tracker_name); printf("ID: 0x%02X\n", stm->id_marker); printf("File Type: %u (%s)\n", stm->file_type, stm->file_type == 1 ? "Song" : "Module"); printf("Major Version: %u\n", stm->major_version); printf("Minor Version: %u\n", stm->minor_version); printf("Playback Tempo: %u\n", stm->tempo); printf("Number of Patterns: %u\n", stm->num_patterns); printf("Global Volume: %u\n", stm->global_volume); printf("Reserved Header: "); for (int i = 0; i < 13; i++) printf("%02X ", stm->reserved_header[i]); printf("\n\nInstruments:\n"); for (int i = 0; i < 31; i++) { printf("Instrument %d:\n", i + 1); printf(" Name: %s\n", stm->instruments[i].name); printf(" ID: %u\n", stm->instruments[i].id); printf(" Disk: %u\n", stm->instruments[i].disk); printf(" Reserved1: %u\n", stm->instruments[i].reserved1); printf(" Length: %u\n", stm->instruments[i].length); printf(" Loop Start: %u\n", stm->instruments[i].loop_start); printf(" Loop End: %u\n", stm->instruments[i].loop_end); printf(" Volume: %u\n", stm->instruments[i].volume); printf(" Reserved2: %u\n", stm->instruments[i].reserved2); printf(" C3 Frequency: %u\n", stm->instruments[i].c3_freq); printf(" Reserved3: %u\n", stm->instruments[i].reserved3); printf(" Paragraph Length: %u\n", stm->instruments[i].para_length); } printf("\nPattern Orders: "); for (int i = 0; i < 64; i++) printf("%u ", stm->pattern_orders[i]); printf("\n\nPattern Data Summary: %u patterns, each 1024 bytes\n", stm->num_patterns); printf("Sample Data Length: %zu\n", stm->sample_data_len); } void stm_free(STMFile* stm) { for (uint8_t p = 0; p < stm->num_patterns; p++) { free(stm->pattern_data[p]); } free(stm->pattern_data); free(stm->sample_data); } // Example usage: // int main() { // STMFile stm; // stm_read(&stm, "example.stm"); // stm_print_properties(&stm); // stm_write(&stm, "output.stm"); // stm_free(&stm); // return 0; // } // ===== end task-694 .STM ===== // ===== task-695 .STO [C++] ===== #include #include #include #include #include struct STOFile { std::string name; int version = -1; // -1 indicates unknown std::string inDegrees = "no"; int nRows = -1; int nColumns = -1; std::vector columnLabels; std::vector> data; STOFile(const std::string& filepath = "") { if (!filepath.empty()) { read(filepath); } } void read(const std::string& filepath) { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file: " << filepath << std::endl; return; } std::string line; if (std::getline(file, line)) { name = line; } else { name = "Unknown"; } bool headerEnded = false; while (std::getline(file, line)) { std::istringstream iss(line); std::string key; iss >> key; if (key.find("version=") == 0) { sscanf(key.c_str(), "version=%d", &version); } else if (key.find("inDegrees=") == 0) { inDegrees = key.substr(10); } else if (key.find("nRows=") == 0) { sscanf(key.c_str(), "nRows=%d", &nRows); } else if (key.find("nColumns=") == 0) { sscanf(key.c_str(), "nColumns=%d", &nColumns); } else if (key == "endheader") { headerEnded = true; // Next line: column labels if (std::getline(file, line)) { std::istringstream labelIss(line); std::string label; while (labelIss >> label) { columnLabels.push_back(label); } } // Read data while (std::getline(file, line)) { if (line.empty()) continue; std::istringstream dataIss(line); std::vector row; double val; while (dataIss >> val) { row.push_back(val); } if (!row.empty()) { data.push_back(row); } } break; } } file.close(); } void printProperties() const { std::cout << "Name: " << name << std::endl; std::cout << "Version: " << (version != -1 ? std::to_string(version) : "Unknown") << std::endl; std::cout << "inDegrees: " << inDegrees << std::endl; std::cout << "nRows: " << nRows << std::endl; std::cout << "nColumns: " << nColumns << std::endl; std::cout << "Column Labels: "; for (size_t i = 0; i < columnLabels.size(); ++i) { std::cout << columnLabels[i]; if (i < columnLabels.size() - 1) std::cout << ", "; } std::cout << std::endl; } void write(const std::string& filepath) const { std::ofstream file(filepath); if (!file.is_open()) { std::cerr << "Error writing file: " << filepath << std::endl; return; } file << name << "\n"; if (version != -1) { file << "version=" << version << "\n"; } file << "inDegrees=" << inDegrees << "\n"; file << "nRows=" << data.size() << "\n"; file << "nColumns=" << columnLabels.size() << "\n"; file << "endheader\n"; for (const auto& label : columnLabels) { file << label << "\t"; } file << "\n"; for (const auto& row : data) { for (size_t i = 0; i < row.size(); ++i) { file << row[i]; if (i < row.size() - 1) file << "\t"; } file << "\n"; } file.close(); } }; // Example usage: // int main() { // STOFile sto("example.sto"); // sto.printProperties(); // sto.write("new.sto"); // return 0; // } // ===== end task-695 .STO ===== // ===== task-696 .STO [C] ===== #include #include #include #include typedef struct { char resref[9]; uint16_t exp_time; uint16_t q1, q2, q3; uint32_t flags; uint32_t stock; uint32_t infinite; uint32_t trigger; uint8_t unknown[56]; } ItemForSale; typedef struct { char resref[9]; uint32_t name_strref; uint32_t price; uint32_t strength; } Drink; typedef struct { char resref[9]; uint32_t price; } Cure; typedef struct { char signature[5]; char version[5]; uint32_t type; uint32_t name; uint32_t flags; uint32_t sell_markup; uint32_t buy_markup; uint32_t depreciation; uint16_t steal_failure; uint16_t capacity; uint8_t unknown1[8]; uint32_t* purchased_categories; size_t purchased_count; ItemForSale* items_for_sale; size_t items_count; uint32_t lore; uint32_t id_price; char rumours_tavern[9]; Drink* drinks; size_t drinks_count; char rumours_temple[9]; uint32_t room_flags; uint32_t price_peasant; uint32_t price_merchant; uint32_t price_noble; uint32_t price_royal; Cure* cures; size_t cures_count; uint8_t unknown2[36]; } STOFile; STOFile* sto_create() { STOFile* sto = calloc(1, sizeof(STOFile)); strcpy(sto->signature, "STOR"); strcpy(sto->version, "V1.1"); sto->sell_markup = 100; sto->buy_markup = 100; return sto; } void sto_free(STOFile* sto) { free(sto->purchased_categories); free(sto->items_for_sale); free(sto->drinks); free(sto->cures); free(sto); } int sto_read(STOFile* sto, const char* filename) { FILE* f = fopen(filename, "rb"); if (!f) return -1; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); memcpy(sto->signature, data, 4); sto->signature[4] = 0; memcpy(sto->version, data + 4, 4); sto->version[4] = 0; memcpy(&sto->type, data + 8, 4); memcpy(&sto->name, data + 12, 4); memcpy(&sto->flags, data + 16, 4); memcpy(&sto->sell_markup, data + 20, 4); memcpy(&sto->buy_markup, data + 24, 4); memcpy(&sto->depreciation, data + 28, 4); memcpy(&sto->steal_failure, data + 32, 2); memcpy(&sto->capacity, data + 34, 2); memcpy(sto->unknown1, data + 36, 8); uint32_t purchased_offset; memcpy(&purchased_offset, data + 44, 4); uint32_t purchased_count; memcpy(&purchased_count, data + 48, 4); uint32_t items_offset; memcpy(&items_offset, data + 52, 4); uint32_t items_count; memcpy(&items_count, data + 56, 4); memcpy(&sto->lore, data + 60, 4); memcpy(&sto->id_price, data + 64, 4); memcpy(sto->rumours_tavern, data + 68, 8); sto->rumours_tavern[8] = 0; uint32_t drinks_offset; memcpy(&drinks_offset, data + 76, 4); uint32_t drinks_count; memcpy(&drinks_count, data + 80, 4); memcpy(sto->rumours_temple, data + 84, 8); sto->rumours_temple[8] = 0; memcpy(&sto->room_flags, data + 92, 4); memcpy(&sto->price_peasant, data + 96, 4); memcpy(&sto->price_merchant, data + 100, 4); memcpy(&sto->price_noble, data + 104, 4); memcpy(&sto->price_royal, data + 108, 4); uint32_t cures_offset; memcpy(&cures_offset, data + 112, 4); uint32_t cures_count; memcpy(&cures_count, data + 116, 4); memcpy(sto->unknown2, data + 120, 36); sto->purchased_count = purchased_count; sto->purchased_categories = malloc(purchased_count * 4); memcpy(sto->purchased_categories, data + purchased_offset, purchased_count * 4); sto->items_count = items_count; sto->items_for_sale = malloc(items_count * sizeof(ItemForSale)); for (size_t i = 0; i < items_count; i++) { uint8_t* base = data + items_offset + i * 88; ItemForSale* item = &sto->items_for_sale[i]; memcpy(item->resref, base, 8); item->resref[8] = 0; memcpy(&item->exp_time, base + 8, 2); memcpy(&item->q1, base + 10, 2); memcpy(&item->q2, base + 12, 2); memcpy(&item->q3, base + 14, 2); memcpy(&item->flags, base + 16, 4); memcpy(&item->stock, base + 20, 4); memcpy(&item->infinite, base + 24, 4); memcpy(&item->trigger, base + 28, 4); memcpy(item->unknown, base + 32, 56); } sto->drinks_count = drinks_count; sto->drinks = malloc(drinks_count * sizeof(Drink)); for (size_t i = 0; i < drinks_count; i++) { uint8_t* base = data + drinks_offset + i * 20; Drink* drink = &sto->drinks[i]; memcpy(drink->resref, base, 8); drink->resref[8] = 0; memcpy(&drink->name_strref, base + 8, 4); memcpy(&drink->price, base + 12, 4); memcpy(&drink->strength, base + 16, 4); } sto->cures_count = cures_count; sto->cures = malloc(cures_count * sizeof(Cure)); for (size_t i = 0; i < cures_count; i++) { uint8_t* base = data + cures_offset + i * 12; Cure* cure = &sto->cures[i]; memcpy(cure->resref, base, 8); cure->resref[8] = 0; memcpy(&cure->price, base + 8, 4); } free(data); return 0; } int sto_write(STOFile* sto, const char* filename) { FILE* f = fopen(filename, "wb"); if (!f) return -1; fwrite(sto->signature, 1, 4, f); fwrite(sto->version, 1, 4, f); fwrite(&sto->type, 4, 1, f); fwrite(&sto->name, 4, 1, f); fwrite(&sto->flags, 4, 1, f); fwrite(&sto->sell_markup, 4, 1, f); fwrite(&sto->buy_markup, 4, 1, f); fwrite(&sto->depreciation, 4, 1, f); fwrite(&sto->steal_failure, 2, 1, f); fwrite(&sto->capacity, 2, 1, f); fwrite(sto->unknown1, 1, 8, f); long purchased_offset_pos = ftell(f); uint32_t placeholder = 0; fwrite(&placeholder, 4, 1, f); fwrite(&sto->purchased_count, 4, 1, f); long items_offset_pos = ftell(f); fwrite(&placeholder, 4, 1, f); fwrite(&sto->items_count, 4, 1, f); fwrite(&sto->lore, 4, 1, f); fwrite(&sto->id_price, 4, 1, f); char resref_pad[8] = {0}; strncpy(resref_pad, sto->rumours_tavern, 8); fwrite(resref_pad, 1, 8, f); long drinks_offset_pos = ftell(f); fwrite(&placeholder, 4, 1, f); fwrite(&sto->drinks_count, 4, 1, f); memset(resref_pad, 0, 8); strncpy(resref_pad, sto->rumours_temple, 8); fwrite(resref_pad, 1, 8, f); fwrite(&sto->room_flags, 4, 1, f); fwrite(&sto->price_peasant, 4, 1, f); fwrite(&sto->price_merchant, 4, 1, f); fwrite(&sto->price_noble, 4, 1, f); fwrite(&sto->price_royal, 4, 1, f); long cures_offset_pos = ftell(f); fwrite(&placeholder, 4, 1, f); fwrite(&sto->cures_count, 4, 1, f); fwrite(sto->unknown2, 1, 36, f); uint32_t purchased_offset = ftell(f); for (size_t i = 0; i < sto->purchased_count; i++) { fwrite(&sto->purchased_categories[i], 4, 1, f); } uint32_t items_offset = ftell(f); for (size_t i = 0; i < sto->items_count; i++) { ItemForSale* item = &sto->items_for_sale[i]; memset(resref_pad, 0, 8); strncpy(resref_pad, item->resref, 8); fwrite(resref_pad, 1, 8, f); fwrite(&item->exp_time, 2, 1, f); fwrite(&item->q1, 2, 1, f); fwrite(&item->q2, 2, 1, f); fwrite(&item->q3, 2, 1, f); fwrite(&item->flags, 4, 1, f); fwrite(&item->stock, 4, 1, f); fwrite(&item->infinite, 4, 1, f); fwrite(&item->trigger, 4, 1, f); fwrite(item->unknown, 1, 56, f); } uint32_t drinks_offset = ftell(f); for (size_t i = 0; i < sto->drinks_count; i++) { Drink* drink = &sto->drinks[i]; memset(resref_pad, 0, 8); strncpy(resref_pad, drink->resref, 8); fwrite(resref_pad, 1, 8, f); fwrite(&drink->name_strref, 4, 1, f); fwrite(&drink->price, 4, 1, f); fwrite(&drink->strength, 4, 1, f); } uint32_t cures_offset = ftell(f); for (size_t i = 0; i < sto->cures_count; i++) { Cure* cure = &sto->cures[i]; memset(resref_pad, 0, 8); strncpy(resref_pad, cure->resref, 8); fwrite(resref_pad, 1, 8, f); fwrite(&cure->price, 4, 1, f); } fseek(f, purchased_offset_pos, SEEK_SET); fwrite(&purchased_offset, 4, 1, f); fseek(f, items_offset_pos, SEEK_SET); fwrite(&items_offset, 4, 1, f); fseek(f, drinks_offset_pos, SEEK_SET); fwrite(&drinks_offset, 4, 1, f); fseek(f, cures_offset_pos, SEEK_SET); fwrite(&cures_offset, 4, 1, f); fclose(f); return 0; } void sto_print_properties(STOFile* sto) { printf("Header:\n"); printf("Signature: %s\n", sto->signature); printf("Version: %s\n", sto->version); printf("Type: %u\n", sto->type); printf("Name (strref): %u\n", sto->name); printf("Flags: %u (0x%x)\n", sto->flags, sto->flags); printf("Sell markup: %u\n", sto->sell_markup); printf("Buy markup: %u\n", sto->buy_markup); printf("Depreciation rate: %u\n", sto->depreciation); printf("Steal failure chance: %u\n", sto->steal_failure); printf("Capacity: %u\n", sto->capacity); printf("Unknown1: ["); for (int i = 0; i < 8; i++) printf("%u ", sto->unknown1[i]); printf("]\n"); printf("Lore: %u\n", sto->lore); printf("ID price: %u\n", sto->id_price); printf("Rumours tavern: %s\n", sto->rumours_tavern); printf("Rumours temple: %s\n", sto->rumours_temple); printf("Room flags: %u (0x%x)\n", sto->room_flags, sto->room_flags); printf("Price peasant: %u\n", sto->price_peasant); printf("Price merchant: %u\n", sto->price_merchant); printf("Price noble: %u\n", sto->price_noble); printf("Price royal: %u\n", sto->price_royal); printf("Unknown2: ["); for (int i = 0; i < 36; i++) printf("%u ", sto->unknown2[i]); printf("]\n\n"); printf("Purchased Categories:\n"); for (size_t i = 0; i < sto->purchased_count; i++) { printf("Category %zu: %u\n", i, sto->purchased_categories[i]); } printf("\nItems for Sale:\n"); for (size_t i = 0; i < sto->items_count; i++) { ItemForSale* item = &sto->items_for_sale[i]; printf("Item %zu:\n", i); printf(" resref: %s\n", item->resref); printf(" exp_time: %u\n", item->exp_time); printf(" q1: %u\n", item->q1); printf(" q2: %u\n", item->q2); printf(" q3: %u\n", item->q3); printf(" flags: %u (0x%x)\n", item->flags, item->flags); printf(" stock: %u\n", item->stock); printf(" infinite: %u\n", item->infinite); printf(" trigger: %u\n", item->trigger); printf(" unknown: ["); for (int j = 0; j < 56; j++) printf("%u ", item->unknown[j]); printf("]\n"); } printf("\nDrinks:\n"); for (size_t i = 0; i < sto->drinks_count; i++) { Drink* drink = &sto->drinks[i]; printf("Drink %zu:\n", i); printf(" resref: %s\n", drink->resref); printf(" name_strref: %u\n", drink->name_strref); printf(" price: %u\n", drink->price); printf(" strength: %u\n", drink->strength); } printf("\nCures:\n"); for (size_t i = 0; i < sto->cures_count; i++) { Cure* cure = &sto->cures[i]; printf("Cure %zu:\n", i); printf(" resref: %s\n", cure->resref); printf(" price: %u\n", cure->price); } } // Example usage: // int main() { // STOFile* sto = sto_create(); // sto_read(sto, "example.sto"); // sto_print_properties(sto); // sto_write(sto, "output.sto"); // sto_free(sto); // return 0; // } // ===== end task-696 .STO ===== // ===== task-697 .STP [C++] ===== #include #include #include #include #include #include #include class StpHandler { private: std::string filePath; std::map simpleProperties; std::map> listProperties; std::map filePopulation; std::string content; std::vector parseList(const std::string& s) { std::string cleaned = s; cleaned.erase(std::remove(cleaned.begin(), cleaned.end(), '('), cleaned.end()); cleaned.erase(std::remove(cleaned.begin(), cleaned.end(), ')'), cleaned.end()); if (cleaned.empty()) return {}; std::vector list; std::regex itemRegex(R"(([^,]+(?!(?:[^()]*\([^()]*\))*[^()]*$)))"); std::sregex_iterator iter(cleaned.begin(), cleaned.end(), itemRegex); std::sregex_iterator end; for (; iter != end; ++iter) { std::string item = iter->str(); item.erase(std::remove(item.begin(), item.end(), '\''), item.end()); list.push_back(item); } return list; } std::string formatList(const std::vector& lst) { if (lst.empty()) return "()"; std::string res = "("; for (const auto& item : lst) { res += "'" + item + "',"; } res.back() = ')'; return res; } public: StpHandler(const std::string& path) : filePath(path) { std::ifstream file(filePath); std::stringstream buffer; buffer << file.rdbuf(); content = buffer.str(); std::regex headerRegex(R"(HEADER;(.*?)ENDSEC;)", std::regex::dotall); std::smatch match; std::string headerContent; if (std::regex_search(content, match, headerRegex)) { headerContent = match[1].str(); } listProperties["description"] = {}; simpleProperties["implementation_level"] = ""; simpleProperties["name"] = ""; simpleProperties["time_stamp"] = ""; listProperties["author"] = {}; listProperties["organization"] = {}; simpleProperties["preprocessor_version"] = ""; simpleProperties["originating_system"] = ""; simpleProperties["authorization"] = ""; listProperties["schema_identifiers"] = {}; listProperties["schema_population"] = {}; filePopulation["governing_schema"] = ""; filePopulation["determination_method"] = ""; listProperties["governed_sections"] = {}; simpleProperties["default_language"] = ""; listProperties["context_identifiers"] = {}; std::regex entityRegex(R"(([^;]+);)"); std::sregex_iterator entityIter(headerContent.begin(), headerContent.end(), entityRegex); std::sregex_iterator entityEnd; for (; entityIter != entityEnd; ++entityIter) { std::string entity = entityIter->str(1); if (entity.find("FILE_DESCRIPTION") != std::string::npos) { std::regex paramsRegex(R"\((.*)\)"); std::smatch paramsMatch; if (std::regex_search(entity, paramsMatch, paramsRegex)) { std::string params = paramsMatch[1].str(); size_t splitPos = params.find_last_of(','); listProperties["description"] = parseList(params.substr(0, splitPos)); simpleProperties["implementation_level"] = params.substr(splitPos + 1); simpleProperties["implementation_level"].erase(std::remove(simpleProperties["implementation_level"].begin(), simpleProperties["implementation_level"].end(), '\''), simpleProperties["implementation_level"].end()); } } else if (entity.find("FILE_NAME") != std::string::npos) { std::regex paramsRegex(R"\((.*)\)"); std::smatch paramsMatch; if (std::regex_search(entity, paramsMatch, paramsRegex)) { std::string params = paramsMatch[1].str(); std::vector split; // Manual split for simplicity std::stringstream ss(params); std::string token; while (std::getline(ss, token, ',')) { if (token.find('(') != std::string::npos && token.find(')') == std::string::npos) { std::string nested; nested += token + ","; while (std::getline(ss, token, ',')) { nested += token + ","; if (token.find(')') != std::string::npos) break; } split.push_back(nested.substr(0, nested.size() - 1)); } else { split.push_back(token); } } simpleProperties["name"] = split[0]; simpleProperties["name"].erase(std::remove(simpleProperties["name"].begin(), simpleProperties["name"].end(), '\''), simpleProperties["name"].end()); simpleProperties["time_stamp"] = split[1]; simpleProperties["time_stamp"].erase(std::remove(simpleProperties["time_stamp"].begin(), simpleProperties["time_stamp"].end(), '\''), simpleProperties["time_stamp"].end()); listProperties["author"] = parseList(split[2]); listProperties["organization"] = parseList(split[3]); simpleProperties["preprocessor_version"] = split[4]; simpleProperties["preprocessor_version"].erase(std::remove(simpleProperties["preprocessor_version"].begin(), simpleProperties["preprocessor_version"].end(), '\''), simpleProperties["preprocessor_version"].end()); simpleProperties["originating_system"] = split[5]; simpleProperties["originating_system"].erase(std::remove(simpleProperties["originating_system"].begin(), simpleProperties["originating_system"].end(), '\''), simpleProperties["originating_system"].end()); simpleProperties["authorization"] = split.size() > 6 ? split[6] : ""; simpleProperties["authorization"].erase(std::remove(simpleProperties["authorization"].begin(), simpleProperties["authorization"].end(), '\''), simpleProperties["authorization"].end()); } } else if (entity.find("FILE_SCHEMA") != std::string::npos) { std::regex paramsRegex(R"\((.*)\)"); std::smatch paramsMatch; if (std::regex_search(entity, paramsMatch, paramsRegex)) { listProperties["schema_identifiers"] = parseList(paramsMatch[1].str()); } } else if (entity.find("SCHEMA_POPULATION") != std::string::npos) { std::regex paramsRegex(R"\((.*)\)"); std::smatch paramsMatch; if (std::regex_search(entity, paramsMatch, paramsRegex)) { listProperties["schema_population"] = parseList(paramsMatch[1].str()); } } else if (entity.find("FILE_POPULATION") != std::string::npos) { std::regex paramsRegex(R"\((.*)\)"); std::smatch paramsMatch; if (std::regex_search(entity, paramsMatch, paramsRegex)) { std::string params = paramsMatch[1].str(); size_t pos1 = params.find(','); size_t pos2 = params.find(',', pos1 + 1); filePopulation["governing_schema"] = params.substr(0, pos1); filePopulation["governing_schema"].erase(std::remove(filePopulation["governing_schema"].begin(), filePopulation["governing_schema"].end(), '\''), filePopulation["governing_schema"].end()); filePopulation["determination_method"] = params.substr(pos1 + 1, pos2 - pos1 - 1); filePopulation["determination_method"].erase(std::remove(filePopulation["determination_method"].begin(), filePopulation["determination_method"].end(), '\''), filePopulation["determination_method"].end()); if (pos2 != std::string::npos) { listProperties["governed_sections"] = parseList(params.substr(pos2 + 1)); } } } else if (entity.find("SECTION_LANGUAGE") != std::string::npos) { std::regex paramsRegex(R"\((.*)\)"); std::smatch paramsMatch; if (std::regex_search(entity, paramsMatch, paramsRegex)) { std::string params = paramsMatch[1].str(); size_t pos = params.find(','); simpleProperties["default_language"] = (pos != std::string::npos) ? params.substr(pos + 1) : ""; simpleProperties["default_language"].erase(std::remove(simpleProperties["default_language"].begin(), simpleProperties["default_language"].end(), '\''), simpleProperties["default_language"].end()); } } else if (entity.find("SECTION_CONTEXT") != std::string::npos) { std::regex paramsRegex(R"\((.*)\)"); std::smatch paramsMatch; if (std::regex_search(entity, paramsMatch, paramsRegex)) { std::string params = paramsMatch[1].str(); size_t pos = params.find(','); if (pos != std::string::npos) { listProperties["context_identifiers"] = parseList(params.substr(pos + 1)); } } } } } void printProperties() { std::cout << "{\n"; std::cout << " \"description\": [" << std::endl; for (const auto& item : listProperties["description"]) std::cout << " \"" << item << "\"," << std::endl; std::cout << " ],\n"; std::cout << " \"implementation_level\": \"" << simpleProperties["implementation_level"] << "\",\n"; std::cout << " \"name\": \"" << simpleProperties["name"] << "\",\n"; std::cout << " \"time_stamp\": \"" << simpleProperties["time_stamp"] << "\",\n"; std::cout << " \"author\": [" << std::endl; for (const auto& item : listProperties["author"]) std::cout << " \"" << item << "\"," << std::endl; std::cout << " ],\n"; std::cout << " \"organization\": [" << std::endl; for (const auto& item : listProperties["organization"]) std::cout << " \"" << item << "\"," << std::endl; std::cout << " ],\n"; std::cout << " \"preprocessor_version\": \"" << simpleProperties["preprocessor_version"] << "\",\n"; std::cout << " \"originating_system\": \"" << simpleProperties["originating_system"] << "\",\n"; std::cout << " \"authorization\": \"" << simpleProperties["authorization"] << "\",\n"; std::cout << " \"schema_identifiers\": [" << std::endl; for (const auto& item : listProperties["schema_identifiers"]) std::cout << " \"" << item << "\"," << std::endl; std::cout << " ],\n"; std::cout << " \"schema_population\": [" << std::endl; for (const auto& item : listProperties["schema_population"]) std::cout << " \"" << item << "\"," << std::endl; std::cout << " ],\n"; std::cout << " \"file_population\": {\n"; std::cout << " \"governing_schema\": \"" << filePopulation["governing_schema"] << "\",\n"; std::cout << " \"determination_method\": \"" << filePopulation["determination_method"] << "\",\n"; std::cout << " \"governed_sections\": [" << std::endl; for (const auto& item : listProperties["governed_sections"]) std::cout << " \"" << item << "\"," << std::endl; std::cout << " ]\n"; std::cout << " },\n"; std::cout << " \"default_language\": \"" << simpleProperties["default_language"] << "\",\n"; std::cout << " \"context_identifiers\": [" << std::endl; for (const auto& item : listProperties["context_identifiers"]) std::cout << " \"" << item << "\"," << std::endl; std::cout << " ]\n"; std::cout << "}" << std::endl; } void write(const std::string& newFilePath) { std::string newHeader = "HEADER;\n"; newHeader += "FILE_DESCRIPTION(" + formatList(listProperties["description"]) + ",'" + simpleProperties["implementation_level"] + "');\n"; newHeader += "FILE_NAME('" + simpleProperties["name"] + "','" + simpleProperties["time_stamp"] + "'," + formatList(listProperties["author"]) + "," + formatList(listProperties["organization"]) + ",'" + simpleProperties["preprocessor_version"] + "','" + simpleProperties["originating_system"] + "','" + simpleProperties["authorization"] + "');\n"; newHeader += "FILE_SCHEMA(" + formatList(listProperties["schema_identifiers"]) + ");\n"; if (!listProperties["schema_population"].empty()) { newHeader += "SCHEMA_POPULATION(" + formatList(listProperties["schema_population"]) + ");\n"; } if (!filePopulation["governing_schema"].empty()) { newHeader += "FILE_POPULATION('" + filePopulation["governing_schema"] + "','" + filePopulation["determination_method"] + "'," + formatList(listProperties["governed_sections"]) + ");\n"; } if (!simpleProperties["default_language"].empty()) { newHeader += "SECTION_LANGUAGE($,'" + simpleProperties["default_language"] + "');\n"; } if (!listProperties["context_identifiers"].empty()) { newHeader += "SECTION_CONTEXT($," + formatList(listProperties["context_identifiers"]) + ");\n"; } newHeader += "ENDSEC;\n"; std::regex headerRegex(R"(HEADER;(.*?)ENDSEC;)", std::regex::dotall); std::string newContent = std::regex_replace(content, headerRegex, newHeader); std::ofstream outFile(newFilePath); outFile << newContent; } }; // Example usage: // int main() { // StpHandler handler("example.stp"); // handler.printProperties(); // handler.write("modified.stp"); // return 0; // } // ===== end task-697 .STP ===== // ===== task-698 .STW [C] ===== #include #include #include #include typedef struct { char filename[256]; uint8_t *data; size_t size; struct { uint8_t signature[8]; uint8_t clsid[16]; uint16_t minorVersion; uint16_t majorVersion; uint16_t byteOrder; uint16_t sectorShift; uint16_t miniSectorShift; uint8_t reserved[6]; uint32_t numDirSectors; uint32_t numFatSectors; uint32_t firstDirSector; uint32_t transactionSig; uint32_t miniStreamCutoff; uint32_t firstMiniFatSector; uint32_t numMiniFatSectors; uint32_t firstDifatSector; uint32_t numDifatSectors; uint32_t difat[109]; } header; struct DirectoryEntry { char name[32]; // Simplified, assuming ASCII for print uint16_t nameLength; uint8_t objectType; uint8_t colorFlag; uint32_t leftSibling; uint32_t rightSibling; uint32_t child; uint8_t clsid[16]; uint32_t stateBits; uint64_t creationTime; uint64_t modifiedTime; uint32_t startingSector; uint64_t streamSize; struct DirectoryEntry *next; } *directoryEntries; uint32_t sectorSize; } STWParser; void readSTW(STWParser *parser) { FILE *f = fopen(parser->filename, "rb"); if (!f) return; fseek(f, 0, SEEK_END); parser->size = ftell(f); fseek(f, 0, SEEK_SET); parser->data = malloc(parser->size); fread(parser->data, 1, parser->size, f); fclose(f); // Parse header memcpy(parser->header.signature, parser->data, 8); memcpy(parser->header.clsid, parser->data + 8, 16); memcpy(&parser->header.minorVersion, parser->data + 24, 2); memcpy(&parser->header.majorVersion, parser->data + 26, 2); memcpy(&parser->header.byteOrder, parser->data + 28, 2); memcpy(&parser->header.sectorShift, parser->data + 30, 2); parser->sectorSize = 1 << parser->header.sectorShift; memcpy(&parser->header.miniSectorShift, parser->data + 32, 2); memcpy(parser->header.reserved, parser->data + 34, 6); memcpy(&parser->header.numDirSectors, parser->data + 40, 4); memcpy(&parser->header.numFatSectors, parser->data + 44, 4); memcpy(&parser->header.firstDirSector, parser->data + 48, 4); memcpy(&parser->header.transactionSig, parser->data + 52, 4); memcpy(&parser->header.miniStreamCutoff, parser->data + 56, 4); memcpy(&parser->header.firstMiniFatSector, parser->data + 60, 4); memcpy(&parser->header.numMiniFatSectors, parser->data + 64, 4); memcpy(&parser->header.firstDifatSector, parser->data + 68, 4); memcpy(&parser->header.numDifatSectors, parser->data + 72, 4); for (int i = 0; i < 109; i++) { memcpy(&parser->header.difat[i], parser->data + 76 + i * 4, 4); } // Parse directory entries uint32_t offset = (parser->header.firstDirSector + 1) * parser->sectorSize; struct DirectoryEntry *current = NULL; while (offset + 128 < parser->size) { struct DirectoryEntry *entry = malloc(sizeof(struct DirectoryEntry)); uint8_t nameBytes[64]; memcpy(nameBytes, parser->data + offset, 64); memcpy(&entry->nameLength, parser->data + offset + 64, 2); if (entry->nameLength == 0) { free(entry); break; } // Convert UTF-16 to ASCII for simplicity for (int j = 0; j < (entry->nameLength - 2)/2; j++) { entry->name[j] = nameBytes[j*2]; } entry->name[(entry->nameLength - 2)/2] = '\0'; memcpy(&entry->objectType, parser->data + offset + 66, 1); memcpy(&entry->colorFlag, parser->data + offset + 67, 1); memcpy(&entry->leftSibling, parser->data + offset + 68, 4); memcpy(&entry->rightSibling, parser->data + offset + 72, 4); memcpy(&entry->child, parser->data + offset + 76, 4); memcpy(entry->clsid, parser->data + offset + 80, 16); memcpy(&entry->stateBits, parser->data + offset + 96, 4); memcpy(&entry->creationTime, parser->data + offset + 100, 8); memcpy(&entry->modifiedTime, parser->data + offset + 108, 8); memcpy(&entry->startingSector, parser->data + offset + 116, 4); memcpy(&entry->streamSize, parser->data + offset + 120, 8); entry->next = NULL; if (current) { current->next = entry; } else { parser->directoryEntries = entry; } current = entry; offset += 128; } } void printProperties(STWParser *parser) { printf("Header Properties:\n"); printf("Signature: "); for (int i = 0; i < 8; i++) printf("%02x ", parser->header.signature[i]); printf("\n"); // Similarly print other header fields // ... (omit for brevity, similar to Python print) printf("\nDirectory Entries:\n"); struct DirectoryEntry *entry = parser->directoryEntries; while (entry) { printf("Name: %s\n", entry->name); // Print other fields... // ... (omit for brevity) entry = entry->next; } } void writeSTW(STWParser *parser, const char *newFilename) { FILE *f = fopen(newFilename, "wb"); if (!f) return; fwrite(parser->data, 1, parser->size, f); fclose(f); printf("File written to %s\n", newFilename); } void freeSTW(STWParser *parser) { free(parser->data); struct DirectoryEntry *entry = parser->directoryEntries; while (entry) { struct DirectoryEntry *next = entry->next; free(entry); entry = next; } } // Example usage // int main() { // STWParser parser; // strcpy(parser.filename, "example.stw"); // readSTW(&parser); // printProperties(&parser); // writeSTW(&parser, "example.new.stw"); // freeSTW(&parser); // return 0; // } // ===== end task-698 .STW ===== // ===== task-699 .STX [C] ===== #include #include #include #include typedef struct { char id[4]; uint16_t version; uint16_t tool; uint16_t reserved1; uint8_t trackCount; uint8_t revision; uint32_t reserved2; } FileHeader; typedef struct { uint32_t recordSize; uint32_t fuzzyCount; uint16_t sectorCount; uint16_t flags; uint16_t length; uint8_t number; uint8_t type; } TrackHeader; typedef struct { uint32_t dataOffset; uint16_t bitPosition; uint16_t readTime; uint8_t track; uint8_t head; uint8_t number; uint8_t size; uint16_t crc; uint8_t fdcFlags; uint8_t reserved; } SectorHeader; typedef struct { FileHeader fileHeader; TrackHeader* tracks; SectorHeader** sectors; // Array of pointers to sector arrays } STXFile; STXFile* stx_open(const char* filepath) { FILE* f = fopen(filepath, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); STXFile* stx = malloc(sizeof(STXFile)); uint8_t* ptr = data; memcpy(stx->fileHeader.id, ptr, 4); ptr += 4; stx->fileHeader.version = *(uint16_t*)ptr; ptr += 2; stx->fileHeader.tool = *(uint16_t*)ptr; ptr += 2; stx->fileHeader.reserved1 = *(uint16_t*)ptr; ptr += 2; stx->fileHeader.trackCount = *ptr++; stx->fileHeader.revision = *ptr++; stx->fileHeader.reserved2 = *(uint32_t*)ptr; ptr += 4; stx->tracks = malloc(stx->fileHeader.trackCount * sizeof(TrackHeader)); stx->sectors = malloc(stx->fileHeader.trackCount * sizeof(SectorHeader*)); for (uint8_t t = 0; t < stx->fileHeader.trackCount; t++) { stx->tracks[t].recordSize = *(uint32_t*)ptr; ptr += 4; stx->tracks[t].fuzzyCount = *(uint32_t*)ptr; ptr += 4; stx->tracks[t].sectorCount = *(uint16_t*)ptr; ptr += 2; stx->tracks[t].flags = *(uint16_t*)ptr; ptr += 2; stx->tracks[t].length = *(uint16_t*)ptr; ptr += 2; stx->tracks[t].number = *ptr++; stx->tracks[t].type = *ptr++; if (stx->tracks[t].flags & 0x01) { stx->sectors[t] = malloc(stx->tracks[t].sectorCount * sizeof(SectorHeader)); for (uint16_t s = 0; s < stx->tracks[t].sectorCount; s++) { stx->sectors[t][s].dataOffset = *(uint32_t*)ptr; ptr += 4; stx->sectors[t][s].bitPosition = *(uint16_t*)ptr; ptr += 2; stx->sectors[t][s].readTime = *(uint16_t*)ptr; ptr += 2; stx->sectors[t][s].track = *ptr++; stx->sectors[t][s].head = *ptr++; stx->sectors[t][s].number = *ptr++; stx->sectors[t][s].size = *ptr++; stx->sectors[t][s].crc = *(uint16_t*)ptr; ptr += 2; stx->sectors[t][s].fdcFlags = *ptr++; stx->sectors[t][s].reserved = *ptr++; } } else { stx->sectors[t] = NULL; } // Skip data uint32_t parsed = 16 + ((stx->tracks[t].flags & 0x01) ? 16 * stx->tracks[t].sectorCount : 0); ptr += stx->tracks[t].recordSize - parsed; } free(data); return stx; } void stx_print(STXFile* stx) { printf("File Header:\n"); printf(" ID: %.4s\n", stx->fileHeader.id); printf(" Version: 0x%04X\n", stx->fileHeader.version); printf(" Tool: 0x%04X\n", stx->fileHeader.tool); printf(" Reserved1: 0x%04X\n", stx->fileHeader.reserved1); printf(" Track Count: %u\n", stx->fileHeader.trackCount); printf(" Revision: 0x%02X\n", stx->fileHeader.revision); printf(" Reserved2: 0x%08X\n", stx->fileHeader.reserved2); for (uint8_t t = 0; t < stx->fileHeader.trackCount; t++) { printf("\nTrack %u:\n", t); printf(" Record Size: %u\n", stx->tracks[t].recordSize); printf(" Fuzzy Count: %u\n", stx->tracks[t].fuzzyCount); printf(" Sector Count: %u\n", stx->tracks[t].sectorCount); printf(" Flags: 0x%04X\n", stx->tracks[t].flags); printf(" Length: %u\n", stx->tracks[t].length); printf(" Number: %u\n", stx->tracks[t].number); printf(" Type: 0x%02X\n", stx->tracks[t].type); if (stx->sectors[t]) { for (uint16_t s = 0; s < stx->tracks[t].sectorCount; s++) { printf(" Sector %u:\n", s); printf(" Data Offset: %u\n", stx->sectors[t][s].dataOffset); printf(" Bit Position: %u\n", stx->sectors[t][s].bitPosition); printf(" Read Time: %u\n", stx->sectors[t][s].readTime); printf(" Track: %u\n", stx->sectors[t][s].track); printf(" Head: %u\n", stx->sectors[t][s].head); printf(" Number: %u\n", stx->sectors[t][s].number); printf(" Size: %u\n", stx->sectors[t][s].size); printf(" CRC: 0x%04X\n", stx->sectors[t][s].crc); printf(" FDC Flags: 0x%02X\n", stx->sectors[t][s].fdcFlags); printf(" Reserved: 0x%02X\n", stx->sectors[t][s].reserved); } } } } void stx_write(STXFile* stx, const char* newFilepath) { // Simplified: write headers; extend for data FILE* f = fopen(newFilepath, "wb"); if (!f) return; fwrite(stx->fileHeader.id, 1, 4, f); fwrite(&stx->fileHeader.version, 2, 1, f); fwrite(&stx->fileHeader.tool, 2, 1, f); fwrite(&stx->fileHeader.reserved1, 2, 1, f); fwrite(&stx->fileHeader.trackCount, 1, 1, f); fwrite(&stx->fileHeader.revision, 1, 1, f); fwrite(&stx->fileHeader.reserved2, 4, 1, f); for (uint8_t t = 0; t < stx->fileHeader.trackCount; t++) { fwrite(&stx->tracks[t].recordSize, 4, 1, f); fwrite(&stx->tracks[t].fuzzyCount, 4, 1, f); fwrite(&stx->tracks[t].sectorCount, 2, 1, f); fwrite(&stx->tracks[t].flags, 2, 1, f); fwrite(&stx->tracks[t].length, 2, 1, f); fwrite(&stx->tracks[t].number, 1, 1, f); fwrite(&stx->tracks[t].type, 1, 1, f); if (stx->sectors[t]) { for (uint16_t s = 0; s < stx->tracks[t].sectorCount; s++) { fwrite(&stx->sectors[t][s].dataOffset, 4, 1, f); fwrite(&stx->sectors[t][s].bitPosition, 2, 1, f); fwrite(&stx->sectors[t][s].readTime, 2, 1, f); fwrite(&stx->sectors[t][s].track, 1, 1, f); fwrite(&stx->sectors[t][s].head, 1, 1, f); fwrite(&stx->sectors[t][s].number, 1, 1, f); fwrite(&stx->sectors[t][s].size, 1, 1, f); fwrite(&stx->sectors[t][s].crc, 2, 1, f); fwrite(&stx->sectors[t][s].fdcFlags, 1, 1, f); fwrite(&stx->sectors[t][s].reserved, 1, 1, f); } } // Add data write if needed } fclose(f); } void stx_close(STXFile* stx) { for (uint8_t t = 0; t < stx->fileHeader.trackCount; t++) { if (stx->sectors[t]) free(stx->sectors[t]); } free(stx->sectors); free(stx->tracks); free(stx); } // Example usage: // int main() { // STXFile* stx = stx_open("example.stx"); // stx_print(stx); // stx_write(stx, "example.new.stx"); // stx_close(stx); // return 0; // } // ===== end task-699 .STX ===== // ===== task-700 .SUR [C] ===== #include #include #include typedef struct { char* file_identifier; int version_number; int u_resolution; int v_resolution; int number_of_tiles; double camera_position[3]; double view_direction[3]; double image_plane_center[3]; double image_plane_horizontal_vector[3]; double image_plane_vertical_vector[3]; double focal_length; double scale; double eye_separation; double clipping_plane_distance; double*** vertex_grid; double**** tile_transformation_matrices; int* normal_correctors; } SURProperties; typedef struct { char* filename; SURProperties properties; } SURFile; SURFile* sur_create(const char* filename) { SURFile* sur = (SURFile*)malloc(sizeof(SURFile)); sur->filename = strdup(filename); memset(&sur->properties, 0, sizeof(SURProperties)); return sur; } void sur_read(SURFile* sur) { FILE* f = fopen(sur->filename, "r"); if (!f) return; char line[256]; int index = 0; fgets(line, sizeof(line), f); sur->properties.file_identifier = strdup(line); fgets(line, sizeof(line), f); sur->properties.version_number = atoi(line); fgets(line, sizeof(line), f); sur->properties.u_resolution = atoi(line); fgets(line, sizeof(line), f); sur->properties.v_resolution = atoi(line); fgets(line, sizeof(line), f); sur->properties.number_of_tiles = atoi(line); if (sur->properties.version_number >= 2) { for (int i = 0; i < 3; i++) { fgets(line, sizeof(line), f); sur->properties.camera_position[i] = atof(line); } for (int i = 0; i < 3; i++) { fgets(line, sizeof(line), f); sur->properties.view_direction[i] = atof(line); } for (int i = 0; i < 3; i++) { fgets(line, sizeof(line), f); sur->properties.image_plane_center[i] = atof(line); } for (int i = 0; i < 3; i++) { fgets(line, sizeof(line), f); sur->properties.image_plane_horizontal_vector[i] = atof(line); } for (int i = 0; i < 3; i++) { fgets(line, sizeof(line), f); sur->properties.image_plane_vertical_vector[i] = atof(line); } fgets(line, sizeof(line), f); sur->properties.focal_length = atof(line); fgets(line, sizeof(line), f); sur->properties.scale = atof(line); fgets(line, sizeof(line), f); sur->properties.eye_separation = atof(line); fgets(line, sizeof(line), f); sur->properties.clipping_plane_distance = atof(line); } sur->properties.vertex_grid = (double***)malloc(sur->properties.u_resolution * sizeof(double**)); for (int i = 0; i < sur->properties.u_resolution; i++) { sur->properties.vertex_grid[i] = (double**)malloc(sur->properties.v_resolution * sizeof(double*)); for (int j = 0; j < sur->properties.v_resolution; j++) { sur->properties.vertex_grid[i][j] = (double*)malloc(3 * sizeof(double)); for (int k = 0; k < 3; k++) { fgets(line, sizeof(line), f); sur->properties.vertex_grid[i][j][k] = atof(line); } } } if (sur->properties.number_of_tiles > 1) { sur->properties.tile_transformation_matrices = (double****)malloc(sur->properties.number_of_tiles * sizeof(double***)); for (int k = 0; k < sur->properties.number_of_tiles; k++) { sur->properties.tile_transformation_matrices[k] = (double***)malloc(4 * sizeof(double**)); for (int row = 0; row < 4; row++) { sur->properties.tile_transformation_matrices[k][row] = (double**)malloc(3 * sizeof(double*)); for (int col = 0; col < 3; col++) { sur->properties.tile_transformation_matrices[k][row][col] = (double*)malloc(sizeof(double)); fgets(line, sizeof(line), f); *sur->properties.tile_transformation_matrices[k][row][col] = atof(line); } } } } sur->properties.normal_correctors = (int*)malloc(sur->properties.number_of_tiles * sizeof(int)); for (int k = 0; k < sur->properties.number_of_tiles; k++) { fgets(line, sizeof(line), f); sur->properties.normal_correctors[k] = atoi(line); } fclose(f); } void sur_print_properties(SURFile* sur) { printf("File Identifier: %s\n", sur->properties.file_identifier); printf("Version Number: %d\n", sur->properties.version_number); printf("U Resolution: %d\n", sur->properties.u_resolution); printf("V Resolution: %d\n", sur->properties.v_resolution); printf("Number of Tiles: %d\n", sur->properties.number_of_tiles); // Similarly print other properties, vectors, grids, etc. (omitted for brevity, use loops for arrays) } void sur_write(SURFile* sur, const char* filename) { FILE* f = fopen(filename, "w"); if (!f) return; fprintf(f, "SurfaceDataFile\n"); fprintf(f, "%d\n", sur->properties.version_number); fprintf(f, "%d\n", sur->properties.u_resolution); fprintf(f, "%d\n", sur->properties.v_resolution); fprintf(f, "%d\n", sur->properties.number_of_tiles); if (sur->properties.version_number >= 2) { for (int i = 0; i < 3; i++) fprintf(f, "%f\n", sur->properties.camera_position[i]); for (int i = 0; i < 3; i++) fprintf(f, "%f\n", sur->properties.view_direction[i]); for (int i = 0; i < 3; i++) fprintf(f, "%f\n", sur->properties.image_plane_center[i]); for (int i = 0; i < 3; i++) fprintf(f, "%f\n", sur->properties.image_plane_horizontal_vector[i]); for (int i = 0; i < 3; i++) fprintf(f, "%f\n", sur->properties.image_plane_vertical_vector[i]); fprintf(f, "%f\n", sur->properties.focal_length); fprintf(f, "%f\n", sur->properties.scale); fprintf(f, "%f\n", sur->properties.eye_separation); fprintf(f, "%f\n", sur->properties.clipping_plane_distance); } for (int i = 0; i < sur->properties.u_resolution; i++) { for (int j = 0; j < sur->properties.v_resolution; j++) { for (int k = 0; k < 3; k++) { fprintf(f, "%f\n", sur->properties.vertex_grid[i][j][k]); } } } if (sur->properties.number_of_tiles > 1) { for (int k = 0; k < sur->properties.number_of_tiles; k++) { for (int row = 0; row < 4; row++) { for (int col = 0; col < 3; col++) { fprintf(f, "%f\n", *sur->properties.tile_transformation_matrices[k][row][col]); } } } } for (int k = 0; k < sur->properties.number_of_tiles; k++) { fprintf(f, "%d\n", sur->properties.normal_correctors[k]); } fclose(f); } void sur_free(SURFile* sur) { free(sur->file_identifier); // Free allocated arrays (vertex_grid, matrices, normal_correctors) - omitted for brevity, use nested free loops free(sur->filename); free(sur); } // Example usage // int main() { // SURFile* sur = sur_create("example.sur"); // sur_read(sur); // sur_print_properties(sur); // sur_write(sur, "output.sur"); // sur_free(sur); // return 0; // } // ===== end task-700 .SUR ===== // ===== task-701 .SVC [C++] ===== #include #include #include #include #include class SVCParser { private: std::string filename; std::vector data; size_t offset; std::map properties; // Simplified to uint32_t for example public: SVCParser(const std::string& fn) : filename(fn), offset(0) {} void openAndRead() { std::ifstream file(filename, std::ios::binary); if (file) { file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(data.data(), size); } parse(); printProperties(); } void parse() { offset = 0; while (offset < data.size()) { uint32_t size = readUint32(); char type[5]; memcpy(type, &data[offset], 4); type[4] = '\0'; offset += 4; if (strcmp(type, "svcC") == 0) { parseSVCConfiguration(); } else if (strcmp(type, "svcd") == 0) { parseSVCDependencyEntry(); } offset += size - 8; } } uint32_t readUint32() { uint32_t val = (static_cast(data[offset]) << 24) | (static_cast(data[offset+1]) << 16) | (static_cast(data[offset+2]) << 8) | static_cast(data[offset+3]); offset += 4; return val; } uint8_t readUint8() { uint8_t val = static_cast(data[offset]); offset += 1; return val; } void parseSVCConfiguration() { properties["configurationVersion"] = readUint8(); properties["SVCProfileIndication"] = readUint8(); // Simplified } void parseSVCDependencyEntry() { properties["ProfileIndication"] = readUint8(); // Simplified } void printProperties() { for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } void write(const std::string& newFilename) { std::ofstream file(newFilename, std::ios::binary); file.write(data.data(), data.size()); } }; // Example usage // int main() { // SVCParser parser("example.svc"); // parser.openAndRead(); // parser.write("modified.svc"); // return 0; // } // ===== end task-701 .SVC ===== // ===== task-702 .SVELTE [C++] ===== #include #include #include #include class SvelteFileHandler { private: std::string filepath; std::string module_script; std::string instance_script; std::string markup; std::string style; public: SvelteFileHandler(const std::string& fp) : filepath(fp) {} void read_and_decode() { std::ifstream file(filepath); if (!file) { std::cerr << "Failed to open file." << std::endl; return; } std::string text((std::istreambuf_iterator(file)), std::istreambuf_iterator()); // Simple regex-based extraction (not perfect, but functional for basic cases) std::regex module_regex(R"([\s\S]*?)"); std::smatch match; if (std::regex_search(text, match, module_regex)) { module_script = match[0].str().substr(15, match[0].str().length() - 24); // Strip tags } else { std::regex legacy_regex(R"([\s\S]*?)"); if (std::regex_search(text, match, legacy_regex)) { module_script = match[0].str().substr(26, match[0].str().length() - 35); } } std::regex instance_regex(R"([\s\S]*?)"); if (std::regex_search(text, match, instance_regex)) { instance_script = match[0].str().substr(8, match[0].str().length() - 17); } std::regex style_regex(R"()"); if (std::regex_search(text, match, style_regex)) { style = match[0].str().substr(7, match[0].str().length() - 15); } // Markup: rough approximation by removing matched sections std::string temp = text; temp = std::regex_replace(temp, module_regex, ""); temp = std::regex_replace(temp, legacy_regex, ""); temp = std::regex_replace(temp, instance_regex, ""); temp = std::regex_replace(temp, style_regex, ""); markup = temp; // Trim whitespaces module_script = trim(module_script); instance_script = trim(instance_script); style = trim(style); markup = trim(markup); } void print_properties() { std::cout << "Module Script: " << (module_script.empty() ? "None" : module_script) << std::endl; std::cout << "Instance Script: " << (instance_script.empty() ? "None" : instance_script) << std::endl; std::cout << "Markup: " << (markup.empty() ? "None" : markup) << std::endl; std::cout << "Style: " << (style.empty() ? "None" : style) << std::endl; } void write(const std::string& new_filepath = "", const std::string& new_module = "", const std::string& new_instance = "", const std::string& new_markup = "", const std::string& new_style = "") { std::string fp = new_filepath.empty() ? filepath : new_filepath; std::ofstream out(fp); if (!out) { std::cerr << "Failed to write file." << std::endl; return; } std::string m = new_module.empty() ? module_script : new_module; if (!m.empty()) { out << "\n"; } std::string i = new_instance.empty() ? instance_script : new_instance; if (!i.empty()) { out << "\n"; } std::string mk = new_markup.empty() ? markup : new_markup; if (!mk.empty()) { out << mk << "\n"; } std::string s = new_style.empty() ? style : new_style; if (!s.empty()) { out << "\n"; } } private: std::string trim(const std::string& str) { size_t first = str.find_first_not_of(" \n\r\t"); if (first == std::string::npos) return ""; size_t last = str.find_last_not_of(" \n\r\t"); return str.substr(first, (last - first + 1)); } }; // Example usage: // int main() { // SvelteFileHandler handler("example.svelte"); // handler.read_and_decode(); // handler.print_properties(); // handler.write("new.svelte", "new module code"); // return 0; // } // ===== end task-702 .SVELTE ===== // ===== task-704 .SWF [C++] ===== #include #include #include #include #include class SWFHandler { private: std::string filename; std::string signature; uint8_t version; uint32_t fileLength; std::vector frameSize; // {xmin, xmax, ymin, ymax} double frameRate; uint16_t frameCount; public: SWFHandler(const std::string& fn) : filename(fn) { read(); } void read() { std::ifstream file(filename, std::ios::binary); if (!file) return; std::vector header(8); file.read(reinterpret_cast(header.data()), 8); signature = std::string(1, header[0]) + std::string(1, header[1]) + std::string(1, header[2]); version = header[3]; fileLength = *reinterpret_cast(&header[4]); // Assume LE std::vector compressed((std::istreambuf_iterator(file)), std::istreambuf_iterator()); std::vector uncompressed; if (signature[0] == 'C') { uLongf destLen = fileLength - 8; uncompressed.resize(destLen); uncompress(uncompressed.data(), &destLen, compressed.data(), compressed.size()); } else if (signature[0] == 'Z') { // Use lzma library std::cerr << "LZMA not supported" << std::endl; return; } else { uncompressed = compressed; } size_t offset = 0; // Parse RECT (simplified) uint8_t byte = uncompressed[offset]; uint8_t nbits = (byte >> 3) & 0x1F; offset += (5 + 4 * nbits + 7) / 8; frameRate = *reinterpret_cast(&uncompressed[offset]) / 256.0; offset += 2; frameCount = *reinterpret_cast(&uncompressed[offset]); // frameSize parsing omitted } void printProperties() { std::cout << "Signature: " << signature << std::endl; std::cout << "Version: " << static_cast(version) << std::endl; std::cout << "File Length: " << fileLength << std::endl; std::cout << "Frame Rate: " << frameRate << " fps" << std::endl; std::cout << "Frame Count: " << frameCount << std::endl; } void write(const std::string& newFilename, double newFrameRate = -1) { if (newFrameRate >= 0) frameRate = newFrameRate; // Implement write; omitted } }; // Example: // int main() { // SWFHandler swf("example.swf"); // swf.printProperties(); // return 0; // } // ===== end task-704 .SWF ===== // ===== task-705 .SWG [C] ===== #include #include #include #include #include typedef struct { uint8_t checksum; char method[6]; uint32_t compressed_size; uint32_t uncompressed_size; struct tm timestamp; uint8_t attr; uint8_t level; uint8_t* extra_header; char* filename; uint16_t crc16; uint8_t* body; } SWGMember; typedef struct { char* filename; SWGMember* members; size_t member_count; } SWGFile; SWGFile* swg_create(const char* filename) { SWGFile* swg = malloc(sizeof(SWGFile)); swg->filename = strdup(filename); swg->members = NULL; swg->member_count = 0; return swg; } void swg_read(SWGFile* swg) { FILE* f = fopen(swg->filename, "rb"); fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); size_t offset = 0; while (offset < size) { uint8_t header_len = data[offset]; if (header_len == 0) break; offset++; SWGMember member; member.checksum = data[offset]; strncpy(member.method, (char*)(data + offset + 1), 5); member.method[5] = '\0'; member.compressed_size = *(uint32_t*)(data + offset + 6); member.uncompressed_size = *(uint32_t*)(data + offset + 10); uint16_t time_val = *(uint16_t*)(data + offset + 14); uint16_t date_val = *(uint16_t*)(data + offset + 16); member.timestamp.tm_year = 80 + (date_val >> 9); member.timestamp.tm_mon = ((date_val >> 5) & 0xF) - 1; member.timestamp.tm_mday = date_val & 0x1F; member.timestamp.tm_hour = time_val >> 11; member.timestamp.tm_min = (time_val >> 5) & 0x3F; member.timestamp.tm_sec = (time_val & 0x1F) * 2; member.timestamp.tm_isdst = -1; member.attr = data[offset + 18]; member.level = data[offset + 19]; member.extra_header = malloc(165); memcpy(member.extra_header, data + offset + 20, 165); uint8_t filename_len = data[offset + 20 + 165]; member.filename = malloc(filename_len + 1); memcpy(member.filename, data + offset + 21 + 165, filename_len); member.filename[filename_len] = '\0'; member.crc16 = *(uint16_t*)(data + offset + 21 + 165 + filename_len); member.body = malloc(member.compressed_size); memcpy(member.body, data + offset + header_len, member.compressed_size); swg->members = realloc(swg->members, sizeof(SWGMember) * (swg->member_count + 1)); swg->members[swg->member_count++] = member; offset += header_len + member.compressed_size; } free(data); } void swg_print_properties(const SWGFile* swg) { for (size_t i = 0; i < swg->member_count; i++) { SWGMember m = swg->members[i]; printf("Member File: %s\n", m.filename); printf("Header Checksum: %u\n", m.checksum); printf("Compression Method: %s\n", m.method); printf("Compressed Size: %u\n", m.compressed_size); printf("Uncompressed Size: %u\n", m.uncompressed_size); char time_str[20]; strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", &m.timestamp); printf("File Timestamp: %s\n", time_str); printf("Attribute: %u\n", m.attr); printf("LHA Level: %u\n", m.level); printf("Extra Header: "); for (int j = 0; j < 165; j++) printf("%02X ", m.extra_header[j]); printf("\n"); printf("Filename: %s\n", m.filename); printf("File Uncompressed CRC16: %u\n", m.crc16); printf("---\n"); } } void swg_write(const SWGFile* swg, const char* new_filename) { FILE* f = fopen(new_filename, "wb"); for (size_t i = 0; i < swg->member_count; i++) { SWGMember m = swg->members[i]; size_t fn_len = strlen(m.filename); uint8_t header_len = 20 + 165 + 1 + fn_len + 2; fwrite(&header_len, 1, 1, f); fwrite(&m.checksum, 1, 1, f); fwrite(m.method, 1, 5, f); fwrite(&m.compressed_size, 4, 1, f); fwrite(&m.uncompressed_size, 4, 1, f); uint16_t date_val = ((m.timestamp.tm_year - 80) << 9) | ((m.timestamp.tm_mon + 1) << 5) | m.timestamp.tm_mday; uint16_t time_val = (m.timestamp.tm_hour << 11) | (m.timestamp.tm_min << 5) | (m.timestamp.tm_sec / 2); fwrite(&time_val, 2, 1, f); fwrite(&date_val, 2, 1, f); fwrite(&m.attr, 1, 1, f); fwrite(&m.level, 1, 1, f); fwrite(m.extra_header, 1, 165, f); uint8_t fn_len_byte = (uint8_t)fn_len; fwrite(&fn_len_byte, 1, 1, f); fwrite(m.filename, 1, fn_len, f); fwrite(&m.crc16, 2, 1, f); fwrite(m.body, 1, m.compressed_size, f); } uint8_t end = 0; fwrite(&end, 1, 1, f); fclose(f); } void swg_destroy(SWGFile* swg) { for (size_t i = 0; i < swg->member_count; i++) { free(swg->members[i].extra_header); free(swg->members[i].filename); free(swg->members[i].body); } free(swg->members); free(swg->filename); free(swg); } // Example usage: // SWGFile* swg = swg_create("example.swg"); // swg_read(swg); // swg_print_properties(swg); // swg_write(swg, "new_example.swg"); // swg_destroy(swg); // ===== end task-705 .SWG ===== // ===== task-706 .SWIFT [C] ===== #include #include #include #include #include #include #include #include #include typedef struct { char* filepath; struct stat stats; } SwiftFileHandler; SwiftFileHandler* createSwiftFileHandler(const char* filepath) { SwiftFileHandler* handler = malloc(sizeof(SwiftFileHandler)); handler->filepath = strdup(filepath); const char* ext = strrchr(filepath, '.'); if (!ext || strcasecmp(ext, ".swift") != 0) { fprintf(stderr, "File must have .SWIFT extension\n"); free(handler); return NULL; } if (stat(filepath, &handler->stats) != 0) { perror("stat"); free(handler->filepath); free(handler); return NULL; } return handler; } void destroySwiftFileHandler(SwiftFileHandler* handler) { free(handler->filepath); free(handler); } void printProperties(SwiftFileHandler* handler) { struct tm* tm; char buf[256]; struct passwd* pw = getpwuid(handler->stats.st_uid); struct group* gr = getgrgid(handler->stats.st_gid); printf("File name: %s\n", strrchr(handler->filepath, '/') ? strrchr(handler->filepath, '/') + 1 : handler->filepath); printf("File path: %s\n", handler->filepath); printf("File size: %lld bytes\n", (long long)handler->stats.st_size); tm = localtime(&handler->stats.st_ctime); strftime(buf, sizeof(buf), "%c", tm); printf("Creation time: %s\n", buf); tm = localtime(&handler->stats.st_mtime); strftime(buf, sizeof(buf), "%c", tm); printf("Last modification time: %s\n", buf); tm = localtime(&handler->stats.st_atime); strftime(buf, sizeof(buf), "%c", tm); printf("Last access time: %s\n", buf); printf("Permissions: %o\n", handler->stats.st_mode & 0777); printf("Owner user ID/name: %d/%s\n", handler->stats.st_uid, pw ? pw->pw_name : "N/A"); printf("Group ID/name: %d/%s\n", handler->stats.st_gid, gr ? gr->gr_name : "N/A"); printf("File type: %s\n", S_ISDIR(handler->stats.st_mode) ? "directory" : "regular file"); printf("Inode number: %ld\n", (long)handler->stats.st_ino); printf("Device ID: %ld\n", (long)handler->stats.st_dev); printf("Number of hard links: %ld\n", (long)handler->stats.st_nlink); } void writeProperties(SwiftFileHandler* handler, time_t new_mtime, mode_t new_permissions) { if (new_mtime != -1) { struct utimbuf ut; ut.actime = handler->stats.st_atime; ut.modtime = new_mtime; utime(handler->filepath, &ut); } if (new_permissions != -1) { chmod(handler->filepath, new_permissions); } stat(handler->filepath, &handler->stats); // Refresh } // Example usage: // int main() { // SwiftFileHandler* handler = createSwiftFileHandler("example.swift"); // if (handler) { // printProperties(handler); // writeProperties(handler, time(NULL), 0644); // printProperties(handler); // destroySwiftFileHandler(handler); // } // return 0; // } // ===== end task-706 .SWIFT ===== // ===== task-707 .SWM [C] ===== #include #include #include #include #include typedef struct { char magic[8]; uint32_t header_size; uint32_t version; uint32_t flags; uint32_t compression_chunk_size; uint8_t guid[16]; uint16_t part_number; uint16_t total_parts; uint32_t image_count; struct { uint64_t offset, size, flags; } lookup_table; struct { uint64_t offset, size, flags; } xml_data; struct { uint64_t offset, size, flags; } boot_metadata; uint32_t boot_index; struct { uint64_t offset, size, flags; } integrity_table; } SWMHeader; void read_header(const char* filename, SWMHeader* h) { FILE* f = fopen(filename, "rb"); if (f == NULL) { perror("fopen"); exit(1); } uint8_t data[208]; if (fread(data, 1, 208, f) < 208) { fprintf(stderr, "File too small\n"); fclose(f); exit(1); } fclose(f); memcpy(h->magic, data, 8); memcpy(&h->header_size, data + 8, 4); memcpy(&h->version, data + 12, 4); memcpy(&h->flags, data + 16, 4); memcpy(&h->compression_chunk_size, data + 20, 4); memcpy(h->guid, data + 24, 16); memcpy(&h->part_number, data + 40, 2); memcpy(&h->total_parts, data + 42, 2); memcpy(&h->image_count, data + 44, 4); memcpy(&h->lookup_table, data + 48, 24); memcpy(&h->xml_data, data + 72, 24); memcpy(&h->boot_metadata, data + 96, 24); memcpy(&h->boot_index, data + 120, 4); memcpy(&h->integrity_table, data + 124, 24); } void print_properties(const SWMHeader* h) { printf("magic: %.8s\n", h->magic); printf("header_size: %u\n", h->header_size); printf("version: %u\n", h->version); printf("flags: %u\n", h->flags); printf("compression_chunk_size: %u\n", h->compression_chunk_size); printf("guid: "); for (int i = 0; i < 16; i++) printf("%02x", h->guid[i]); printf("\n"); printf("part_number: %u\n", h->part_number); printf("total_parts: %u\n", h->total_parts); printf("image_count: %u\n", h->image_count); printf("lookup_table: {offset: %llu, size: %llu, flags: %llu}\n", h->lookup_table.offset, h->lookup_table.size, h->lookup_table.flags); printf("xml_data: {offset: %llu, size: %llu, flags: %llu}\n", h->xml_data.offset, h->xml_data.size, h->xml_data.flags); printf("boot_metadata: {offset: %llu, size: %llu, flags: %llu}\n", h->boot_metadata.offset, h->boot_metadata.size, h->boot_metadata.flags); printf("boot_index: %u\n", h->boot_index); printf("integrity_table: {offset: %llu, size: %llu, flags: %llu}\n", h->integrity_table.offset, h->integrity_table.size, h->integrity_table.flags); } void write_header(const char* filename, const SWMHeader* h) { FILE* f = fopen(filename, "rb+"); if (f == NULL) { perror("fopen"); exit(1); } uint8_t data[208] = {0}; memcpy(data, h->magic, 8); memcpy(data + 8, &h->header_size, 4); memcpy(data + 12, &h->version, 4); memcpy(data + 16, &h->flags, 4); memcpy(data + 20, &h->compression_chunk_size, 4); memcpy(data + 24, h->guid, 16); memcpy(data + 40, &h->part_number, 2); memcpy(data + 42, &h->total_parts, 2); memcpy(data + 44, &h->image_count, 4); memcpy(data + 48, &h->lookup_table, 24); memcpy(data + 72, &h->xml_data, 24); memcpy(data + 96, &h->boot_metadata, 24); memcpy(data + 120, &h->boot_index, 4); memcpy(data + 124, &h->integrity_table, 24); fseek(f, 0, SEEK_SET); fwrite(data, 1, 208, f); fclose(f); } // Example usage: // int main() { // SWMHeader h; // read_header("example.swm", &h); // print_properties(&h); // h.part_number = 2; // write_header("example.swm", &h); // return 0; // } // ===== end task-707 .SWM ===== // ===== task-708 .SXC [C++] ===== #include #include #include #include #include // Include tinyxml2.h class SXCFile { private: std::string filepath; std::map props; // Simplified to string for demo zip_t* zip; tinyxml2::XMLDocument metaXml; public: SXCFile(const std::string& fp) : filepath(fp), zip(nullptr) {} ~SXCFile() { if (zip) zip_close(zip); } void open() { int err = 0; zip = zip_open(filepath.c_str(), 0, &err); if (!zip) return; decode(); } void decode() { zip_file_t* file = zip_fopen(zip, "mimetype", 0); if (file) { char buf[1024]; zip_int64_t len = zip_fread(file, buf, sizeof(buf) - 1); if (len > 0) { buf[len] = '\0'; props["MIME Type"] = std::string(buf).substr(0, len); } zip_fclose(file); } file = zip_fopen(zip, "meta.xml", 0); if (file) { std::string content; char buf[1024]; zip_int64_t len; while ((len = zip_fread(file, buf, sizeof(buf))) > 0) { content.append(buf, len); } zip_fclose(file); if (metaXml.Parse(content.c_str()) == tinyxml2::XML_SUCCESS) { tinyxml2::XMLElement* meta = metaXml.FirstChildElement("office:document-meta")->FirstChildElement("office:meta"); if (meta) { const char* tags[] = {"dc:title", "dc:description", "dc:subject", "dc:creator", "dc:publisher", "dc:contributor", "dc:date", "dc:type", "dc:format", "dc:identifier", "dc:source", "dc:language", "dc:coverage", "dc:rights", "dc:relation", "meta:initial-creator", "meta:creation-date", "meta:modification-date", "meta:print-date", "meta:printed-by", "meta:generator", "meta:editing-cycles", "meta:editing-duration"}; for (const char* tag : tags) { tinyxml2::XMLElement* elem = meta->FirstChildElement(tag); if (elem && elem->GetText()) { std::string key = std::string(tag).substr(std::string(tag).find(':') + 1); std::replace(key.begin(), key.end(), '-', ' '); props[key] = elem->GetText(); } } // Keywords (simplified) std::string keywords; tinyxml2::XMLElement* kw = meta->FirstChildElement("dc:keywords")->FirstChildElement("meta:keyword"); while (kw) { if (kw->GetText()) keywords += std::string(kw->GetText()) + ", "; kw = kw->NextSiblingElement("meta:keyword"); } if (!keywords.empty()) props["Keywords"] = keywords.substr(0, keywords.size() - 2); // User-defined (simplified to string) std::string userDefined; tinyxml2::XMLElement* ud = meta->FirstChildElement("meta:user-defined"); while (ud) { userDefined += ud->Attribute("meta:name") + ": " + (ud->GetText() ? ud->GetText() : "") + "; "; ud = ud->NextSiblingElement("meta:user-defined"); } if (!userDefined.empty()) props["User-Defined Fields"] = userDefined.substr(0, userDefined.size() - 2); // Statistics tinyxml2::XMLElement* stats = meta->FirstChildElement("meta:document-statistic"); if (stats) { std::string statStr; const tinyxml2::XMLAttribute* attr = stats->FirstAttribute(); while (attr) { std::string name = attr->Name(); if (name.find("meta:") == 0) { name = name.substr(5); std::replace(name.begin(), name.end(), '-', ' '); statStr += name + ": " + attr->Value() + "; "; } attr = attr->Next(); } if (!statStr.empty()) props["Document Statistics"] = statStr.substr(0, statStr.size() - 2); } } } } } void printProperties() { for (const auto& p : props) { std::cout << p.first << ": " << p.second << std::endl; } } void write(const std::string& newFilepath, const std::map& updates) { // Simplified: Re-open as write, update meta.xml zip_close(zip); zip = zip_open(filepath.c_str(), ZIP_CREATE, nullptr); // Re-open for write if (!zip) return; if (!updates.empty() && metaXml.RootElement()) { tinyxml2::XMLElement* meta = metaXml.FirstChildElement("office:document-meta")->FirstChildElement("office:meta"); for (const auto& update : updates) { std::string tag = update.first; std::replace(tag.begin(), tag.end(), ' ', '-'); tinyxml2::XMLElement* elem = meta->FirstChildElement(("dc:" + tag).c_str()); // Assume dc for simplicity if (!elem) elem = meta->FirstChildElement(("meta:" + tag).c_str()); if (elem) elem->SetText(update.second.c_str()); } tinyxml2::XMLPrinter printer; metaXml.Print(&printer); zip_file_add(zip, "meta.xml", zip_buffer_create((void*)printer.CStr(), printer.Size(), nullptr), ZIP_FL_OVERWRITE); } zip_close(zip); // To save as new, copy or rename if needed std::rename(filepath.c_str(), newFilepath.c_str()); // Simplified } }; // Example usage: // int main() { // SXCFile sxc("sample.sxc"); // sxc.open(); // sxc.printProperties(); // std::map updates = {{"title", "New Title"}}; // sxc.write("modified.sxc", updates); // return 0; // } // ===== end task-708 .SXC ===== // ===== task-709 .SXD [C] ===== #include #include #include #include #include #include typedef struct { char* filepath; zip_t* zip; // Simplified properties: use a map-like array for demo char* properties[10][2]; // key-value pairs, limited int prop_count; } SXDHandler; SXDHandler* sxd_create(const char* filepath) { SXDHandler* handler = malloc(sizeof(SXDHandler)); handler->filepath = strdup(filepath); handler->zip = NULL; handler->prop_count = 0; return handler; } int sxd_open(SXDHandler* handler) { int err = 0; handler->zip = zip_open(handler->filepath, ZIP_RDONLY, &err); return (handler->zip != NULL) ? 0 : -1; } void add_property(SXDHandler* handler, const char* key, const char* value) { if (handler->prop_count < 10) { handler->properties[handler->prop_count][0] = strdup(key); handler->properties[handler->prop_count][1] = strdup(value); handler->prop_count++; } } int sxd_decode_read(SXDHandler* handler) { if (!handler->zip) if (sxd_open(handler) != 0) return -1; // Package files (simplified, print count) zip_int64_t num_entries = zip_get_num_entries(handler->zip, 0); char buf[32]; snprintf(buf, sizeof(buf), "%lld", num_entries); add_property(handler, "package_files_count", buf); // Mimetype zip_file_t* f = zip_fopen(handler->zip, "mimetype", 0); if (f) { char mime[256]; zip_fread(f, mime, 255); mime[255] = '\0'; add_property(handler, "mimetype", strtok(mime, "\n")); zip_fclose(f); } // Parse XML files (simplified, check existence and root) const char* files[] = {"meta.xml", "content.xml", "styles.xml", "settings.xml"}; for (int i = 0; i < 4; i++) { zip_stat_t sb; if (zip_stat(handler->zip, files[i], 0, &sb) == 0) { char* content = malloc(sb.size + 1); f = zip_fopen(handler->zip, files[i], 0); zip_fread(f, content, sb.size); content[sb.size] = '\0'; zip_fclose(f); xmlDocPtr doc = xmlReadMemory(content, sb.size, NULL, NULL, 0); if (doc) { xmlNodePtr root = xmlDocGetRootElement(doc); if (root) { char key[64]; snprintf(key, sizeof(key), "%s_root", files[i]); add_property(handler, key, (char*)root->name); // Sample: for meta, get title if (strcmp(files[i], "meta.xml") == 0) { xmlNodePtr cur = root->children; while (cur) { if (xmlStrcmp(cur->name, (const xmlChar*)"title") == 0) { add_property(handler, "meta_title", (char*)xmlNodeGetContent(cur)); break; } cur = cur->next; } } } xmlFreeDoc(doc); } free(content); } } return 0; } void sxd_print_properties(SXDHandler* handler) { if (handler->prop_count == 0) sxd_decode_read(handler); for (int i = 0; i < handler->prop_count; i++) { printf("%s: %s\n", handler->properties[i][0], handler->properties[i][1]); } } int sxd_write(SXDHandler* handler, const char* new_filepath) { if (!handler->zip) return -1; zip_t* new_zip = zip_open(new_filepath, ZIP_CREATE | ZIP_TRUNCATE, NULL); if (!new_zip) return -1; zip_int64_t num = zip_get_num_entries(handler->zip, 0); for (zip_int64_t i = 0; i < num; i++) { const char* name = zip_get_name(handler->zip, i, 0); zip_stat_t sb; zip_stat_index(handler->zip, i, 0, &sb); char* data = malloc(sb.size); zip_file_t* f = zip_fopen_index(handler->zip, i, 0); zip_fread(f, data, sb.size); zip_fclose(f); if (strcmp(name, "meta.xml") == 0) { // Modify title xmlDocPtr doc = xmlReadMemory(data, sb.size, NULL, NULL, 0); xmlNodePtr title = xmlNewNode(NULL, (xmlChar*)"title"); xmlNodeSetContent(title, (xmlChar*)"Modified Title"); // Simplified: replace entire meta.xml with new minimal one for demo xmlFreeDoc(doc); free(data); data = strdup("Modified Title"); sb.size = strlen(data); } zip_source_t* src = zip_source_buffer(new_zip, data, sb.size, 1); zip_file_add(new_zip, name, src, ZIP_FL_OVERWRITE); } zip_close(new_zip); return 0; } void sxd_close(SXDHandler* handler) { if (handler->zip) zip_close(handler->zip); for (int i = 0; i < handler->prop_count; i++) { free(handler->properties[i][0]); free(handler->properties[i][1]); } free(handler->filepath); free(handler); } // Usage example: // int main() { // SXDHandler* handler = sxd_create("example.sxd"); // sxd_open(handler); // sxd_decode_read(handler); // sxd_print_properties(handler); // sxd_write(handler, "modified.sxd"); // sxd_close(handler); // return 0; // } // ===== end task-709 .SXD ===== // ===== task-710 .SXG [C++] ===== #include #include #include #include #include #include #include #include // For big endian conversions, assume available or use alternatives class SXGFile { private: std::vector signature; uint16_t fallback_url_length; std::string fallback_url; uint32_t sig_length; uint32_t header_length; std::string signature_header; std::map signed_headers; std::vector payload; public: SXGFile(const std::string& filepath) { read(filepath); } void read(const std::string& filepath) { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { throw std::runtime_error("Failed to open file"); } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); std::vector data(size); if (!file.read(reinterpret_cast(data.data()), size)) { throw std::runtime_error("Failed to read file"); } size_t offset = 0; // File Signature signature.assign(data.begin() + offset, data.begin() + offset + 8); offset += 8; // Fallback URL Length fallback_url_length = be16toh(*reinterpret_cast(&data[offset])); offset += 2; // Fallback URL fallback_url.assign(reinterpret_cast(&data[offset]), fallback_url_length); offset += fallback_url_length; // Signature Length sig_length = (data[offset] << 16) | (data[offset + 1] << 8) | data[offset + 2]; offset += 3; // Header Length header_length = (data[offset] << 16) | (data[offset + 1] << 8) | data[offset + 2]; offset += 3; // Signature Header signature_header.assign(reinterpret_cast(&data[offset]), sig_length); offset += sig_length; // Signed Headers CBOR std::vector cbor_data(data.begin() + offset, data.begin() + offset + header_length); signed_headers = parse_cbor_map(cbor_data); offset += header_length; // Payload payload.assign(data.begin() + offset, data.end()); } std::map parse_cbor_map(const std::vector& cbor_bytes) { size_t off = 0; uint8_t head = cbor_bytes[off++]; uint8_t major = head >> 5; uint8_t info = head & 0x1f; if (major != 5) throw std::runtime_error("Not a CBOR map"); uint16_t num_pairs; if (info < 24) num_pairs = info; else if (info == 24) num_pairs = cbor_bytes[off++]; else if (info == 25) { num_pairs = (cbor_bytes[off] << 8) | cbor_bytes[off + 1]; off += 2; } else throw std::runtime_error("Unsupported CBOR length"); std::map map; for (uint16_t i = 0; i < num_pairs; ++i) { uint8_t k_head = cbor_bytes[off++]; if ((k_head >> 5) != 2) throw std::runtime_error("Key not byte string"); uint16_t k_len = k_head & 0x1f; if (k_len == 24) k_len = cbor_bytes[off++]; else if (k_len == 25) { k_len = (cbor_bytes[off] << 8) | cbor_bytes[off + 1]; off += 2; } std::string key(reinterpret_cast(&cbor_bytes[off]), k_len); off += k_len; uint8_t v_head = cbor_bytes[off++]; if ((v_head >> 5) != 2) throw std::runtime_error("Value not byte string"); uint16_t v_len = v_head & 0x1f; if (v_len == 24) v_len = cbor_bytes[off++]; else if (v_len == 25) { v_len = (cbor_bytes[off] << 8) | cbor_bytes[off + 1]; off += 2; } std::string value(reinterpret_cast(&cbor_bytes[off]), v_len); off += v_len; map[key] = value; } return map; } void print_properties() { std::cout << "File Signature: "; for (char c : signature) std::cout << (c >= 32 && c <= 126 ? c : '.'); std::cout << " (hex: "; for (uint8_t b : signature) std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast(b) << " "; std::cout << ")\n"; std::cout << "Fallback URL Length: " << fallback_url_length << "\n"; std::cout << "Fallback URL: " << fallback_url << "\n"; std::cout << "Signature Length: " << sig_length << "\n"; std::cout << "Header Length: " << header_length << "\n"; std::cout << "Signature Header: " << signature_header << "\n"; std::cout << "Signed Headers:\n"; for (const auto& [key, value] : signed_headers) { std::cout << " " << key << ": " << value << "\n"; } std::cout << "Payload Length: " << payload.size() << "\n"; if (payload.size() < 100) { std::cout << "Payload: " << std::string(reinterpret_cast(payload.data()), payload.size()) << "\n"; } else { std::cout << "Payload (first 100 bytes): " << std::string(reinterpret_cast(payload.data()), 100) << "...\n"; } } void write(const std::string& filepath) { std::ofstream file(filepath, std::ios::binary); if (!file) { throw std::runtime_error("Failed to open file for writing"); } file.write(reinterpret_cast(signature.data()), 8); uint16_t be_ful = htobe16(fallback_url_length); file.write(reinterpret_cast(&be_ful), 2); file.write(fallback_url.c_str(), fallback_url_length); uint8_t sig_len_bytes[3] = {static_cast(sig_length >> 16), static_cast(sig_length >> 8), static_cast(sig_length)}; file.write(reinterpret_cast(sig_len_bytes), 3); uint8_t head_len_bytes[3] = {static_cast(header_length >> 16), static_cast(header_length >> 8), static_cast(header_length)}; file.write(reinterpret_cast(head_len_bytes), 3); file.write(signature_header.c_str(), sig_length); auto cbor = encode_cbor_map(signed_headers); file.write(reinterpret_cast(cbor.data()), cbor.size()); file.write(reinterpret_cast(payload.data()), payload.size()); } std::vector encode_cbor_map(const std::map& map) { std::vector cbor; uint16_t num = map.size(); if (num < 24) { cbor.push_back(0xa0 + num); } else if (num < 256) { cbor.push_back(0xb8); cbor.push_back(num); } else { cbor.push_back(0xb9); uint16_t be_num = htobe16(num); cbor.insert(cbor.end(), reinterpret_cast(&be_num), reinterpret_cast(&be_num) + 2); } for (const auto& [key, value] : map) { auto k_bytes = reinterpret_cast(key.c_str()); uint16_t kl = key.length(); if (kl < 24) { cbor.push_back(0x40 + kl); } else if (kl < 256) { cbor.push_back(0x58); cbor.push_back(kl); } else { cbor.push_back(0x59); uint16_t be_kl = htobe16(kl); cbor.insert(cbor.end(), reinterpret_cast(&be_kl), reinterpret_cast(&be_kl) + 2); } cbor.insert(cbor.end(), k_bytes, k_bytes + kl); auto v_bytes = reinterpret_cast(value.c_str()); uint16_t vl = value.length(); if (vl < 24) { cbor.push_back(0x40 + vl); } else if (vl < 256) { cbor.push_back(0x58); cbor.push_back(vl); } else { cbor.push_back(0x59); uint16_t be_vl = htobe16(vl); cbor.insert(cbor.end(), reinterpret_cast(&be_vl), reinterpret_cast(&be_vl) + 2); } cbor.insert(cbor.end(), v_bytes, v_bytes + vl); } return cbor; } }; // Example usage: // int main() { // try { // SXGFile sxg("example.sxg"); // sxg.print_properties(); // sxg.write("output.sxg"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-710 .SXG ===== // ===== task-711 .SXI [C++] ===== #include #include #include #include #include #include class SXIHandler { private: std::string filepath; std::map properties; zip_t* zip; public: SXIHandler(const std::string& fp) : filepath(fp) { int err = 0; zip = zip_open(filepath.c_str(), ZIP_RDONLY, &err); if (zip == nullptr) { std::cerr << "Error opening ZIP" << std::endl; return; } readProperties(); } ~SXIHandler() { if (zip) zip_close(zip); } void readProperties() { // MIME type zip_file_t* mimeFile = zip_fopen(zip, "mimetype", 0); if (mimeFile) { char buffer[100]; int len = zip_fread(mimeFile, buffer, sizeof(buffer)); properties["mimeType"] = std::string(buffer, len); zip_fclose(mimeFile); } // Manifest zip_file_t* manifestFile = zip_fopen(zip, "META-INF/manifest.xml", 0); if (manifestFile) { stat_t st; zip_stat(zip, "META-INF/manifest.xml", 0, &st); char* buf = new char[st.size + 1]; zip_fread(manifestFile, buf, st.size); buf[st.size] = '\0'; tinyxml2::XMLDocument doc; doc.Parse(buf); properties["manifestNamespace"] = "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"; tinyxml2::XMLElement* root = doc.FirstChildElement("manifest:manifest"); std::vector files; for (tinyxml2::XMLElement* entry = root->FirstChildElement("manifest:file-entry"); entry; entry = entry->NextSiblingElement("manifest:file-entry")) { files.push_back(entry->Attribute("manifest:full-path")); } // Store as string for simplicity std::string fileStr; for (const auto& f : files) fileStr += f + ", "; properties["requiredFiles"] = fileStr; delete[] buf; zip_fclose(manifestFile); } // Meta.xml zip_file_t* metaFile = zip_fopen(zip, "meta.xml", 0); if (metaFile) { stat_t st; zip_stat(zip, "meta.xml", 0, &st); char* buf = new char[st.size + 1]; zip_fread(metaFile, buf, st.size); buf[st.size] = '\0'; tinyxml2::XMLDocument doc; doc.Parse(buf); tinyxml2::XMLElement* meta = doc.FirstChildElement("office:document-meta")->FirstChildElement("office:meta"); properties["title"] = meta->FirstChildElement("dc:title") ? meta->FirstChildElement("dc:title")->GetText() : "Not found"; properties["creator"] = meta->FirstChildElement("dc:creator") ? meta->FirstChildElement("dc:creator")->GetText() : "Not found"; properties["creationDate"] = meta->FirstChildElement("meta:creation-date") ? meta->FirstChildElement("meta:creation-date")->GetText() : "Not found"; properties["modifiedDate"] = meta->FirstChildElement("dc:date") ? meta->FirstChildElement("dc:date")->GetText() : "Not found"; tinyxml2::XMLElement* stat = meta->FirstChildElement("meta:document-statistic"); properties["pageCount"] = stat ? stat->Attribute("meta:page-count") : "Not found"; delete[] buf; zip_fclose(metaFile); } // Content.xml zip_file_t* contentFile = zip_fopen(zip, "content.xml", 0); if (contentFile) { stat_t st; zip_stat(zip, "content.xml", 0, &st); char* buf = new char[st.size + 1]; zip_fread(contentFile, buf, st.size); buf[st.size] = '\0'; tinyxml2::XMLDocument doc; doc.Parse(buf); tinyxml2::XMLElement* root = doc.FirstChildElement("office:document-content"); properties["officeVersion"] = root->Attribute("office:version"); properties["officeNamespace"] = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; int slideCount = 0; for (tinyxml2::XMLElement* page = root->FirstChildElement("office:body")->FirstChildElement("draw:page"); page; page = page->NextSiblingElement("draw:page")) { slideCount++; } properties["numberOfSlides"] = std::to_string(slideCount); delete[] buf; zip_fclose(contentFile); } // Other properties["hasStyles"] = zip_name_locate(zip, "styles.xml", 0) >= 0 ? "true" : "false"; properties["hasSettings"] = zip_name_locate(zip, "settings.xml", 0) >= 0 ? "true" : "false"; properties["hasThumbnail"] = zip_name_locate(zip, "Thumbnails/thumbnail.png", 0) >= 0 ? "true" : "false"; int pictureCount = 0; int numFiles = zip_get_num_entries(zip, 0); for (int i = 0; i < numFiles; i++) { const char* name = zip_get_name(zip, i, 0); if (std::string(name).find("Pictures/") == 0) pictureCount++; } properties["embeddedPictures"] = std::to_string(pictureCount); } void printProperties() { for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } void updateTitle(const std::string& newTitle) { // Similar to read, parse meta, update, but for write see save properties["title"] = newTitle; } void save(const std::string& newFilepath) { zip_t* newZip = zip_open(newFilepath.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); int numFiles = zip_get_num_entries(zip, 0); for (int i = 0; i < numFiles; i++) { const char* name = zip_get_name(zip, i, 0); zip_file_t* f = zip_fopen_index(zip, i, 0); stat_t st; zip_stat_index(zip, i, 0, &st); char* buf = new char[st.size]; zip_fread(f, buf, st.size); zip_fclose(f); if (std::string(name) == "meta.xml" && !properties["title"].empty()) { tinyxml2::XMLDocument doc; doc.Parse(buf); tinyxml2::XMLElement* titleElem = doc.FirstChildElement("office:document-meta")->FirstChildElement("office:meta")->FirstChildElement("dc:title"); if (titleElem) titleElem->SetText(properties["title"].c_str()); tinyxml2::XMLPrinter printer; doc.Print(&printer); delete[] buf; buf = const_cast(printer.CStr()); st.size = printer.CStrSize() - 1; } zip_file_add(newZip, name, zip_source_buffer(newZip, buf, st.size, 0), ZIP_FL_OVERWRITE); } zip_close(newZip); } }; // Example usage // int main() { // SXIHandler handler("example.sxi"); // handler.printProperties(); // handler.updateTitle("New Title"); // handler.save("modified.sxi"); // return 0; // } // ===== end task-711 .SXI ===== // ===== task-712 .SXM [C++] ===== #include #include #include #include #include class SXMFile { private: std::string filename; std::map properties; std::vector binaryData; public: SXMFile(const std::string& fn) : filename(fn) { read(); } void read() { std::ifstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file"); } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); size_t headerEnd = content.find(":SCANIT_END:"); if (headerEnd == std::string::npos) { throw std::runtime_error("Invalid .SXM file: No SCANIT_END found."); } std::string header = content.substr(0, headerEnd + 12); binaryData.assign(content.begin() + headerEnd + 12 + 2, content.end()); // Skip \1A\04 std::string line; std::string currentKey; std::string value; size_t pos = 0; while ((pos = header.find('\n', pos)) != std::string::npos) { line = header.substr(0, pos); header.erase(0, pos + 1); line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); // Trim CR if (line[0] == ':') { if (!currentKey.empty()) { properties[currentKey] = value; } currentKey = line.substr(1, line.size() - 2); value = ""; } else if (!currentKey.empty()) { value += line + "\n"; } } if (!currentKey.empty()) { properties[currentKey] = value; } } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& newFilename) { std::ofstream file(newFilename, std::ios::binary); if (!file) { throw std::runtime_error("Cannot write file"); } for (const auto& pair : properties) { file << ":" << pair.first << ":\n" << pair.second << "\n"; } file << ":SCANIT_END:\n"; char marker[2] = {0x1A, 0x04}; file.write(marker, 2); file.write(binaryData.data(), binaryData.size()); } }; // Example usage: // int main() { // SXMFile sxm("example.sxm"); // sxm.printProperties(); // sxm.write("new_example.sxm"); // return 0; // } // ===== end task-712 .SXM ===== // ===== task-713 .SXP [C++] ===== #include #include #include #include #include class SXPParser { private: std::map properties; public: SXPParser(const std::string& filepath) { read(filepath); } void read(const std::string& filepath) { std::ifstream file(filepath); std::string text((std::istreambuf_iterator(file)), std::istreambuf_iterator()); std::regex pattern(R"(\(([^ )]+)\s+([^)]+)\))"); std::sregex_iterator iter(text.begin(), text.end(), pattern); std::sregex_iterator end; for (; iter != end; ++iter) { properties[(*iter)[1]] = (*iter)[2]; } printProperties(); } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& filepath) { std::ofstream file(filepath); for (const auto& pair : properties) { file << "(" << pair.first << " " << pair.second << ")\n"; } } }; // Example usage: // int main() { // SXPParser parser("example.sxp"); // parser.properties["new-key"] = "new-value"; // parser.write("output.sxp"); // return 0; // } // ===== end task-713 .SXP ===== // ===== task-715 .SYLK [C++] ===== #include #include #include #include #include class SylkHandler { private: std::string filename; struct Record { std::string recordType; std::vector fields; }; std::vector properties; public: SylkHandler(const std::string& fn) : filename(fn) {} void readAndDecode() { std::ifstream file(filename); if (!file.is_open()) { throw std::runtime_error("File " + filename + " not found."); } std::string line; while (std::getline(file, line)) { if (line.empty()) continue; std::stringstream ss(line); std::string part; std::vector parts; while (std::getline(ss, part, ';')) { size_t pos = 0; while ((pos = part.find(";;", pos)) != std::string::npos) { part.replace(pos, 2, ";"); pos += 1; } parts.push_back(part); } std::string recordType = parts[0]; std::vector fields; for (size_t i = 1; i < parts.size(); ++i) { // Trim whitespace size_t start = parts[i].find_first_not_of(" \t"); size_t end = parts[i].find_last_not_of(" \t"); if (start != std::string::npos) { fields.push_back(parts[i].substr(start, end - start + 1)); } else { fields.push_back(""); } } properties.push_back({recordType, fields}); } file.close(); } void printProperties() const { if (properties.empty()) { std::cout << "No properties loaded. Call readAndDecode() first." << std::endl; return; } std::cout << "SYLK Properties:" << std::endl; for (size_t idx = 0; idx < properties.size(); ++idx) { const auto& prop = properties[idx]; std::cout << "Record " << (idx + 1) << ": Type = " << prop.recordType << std::endl; for (size_t fIdx = 0; fIdx < prop.fields.size(); ++fIdx) { std::cout << " Field " << (fIdx + 1) << ": " << prop.fields[fIdx] << std::endl; } std::cout << std::endl; } } void write(const std::string& outputFilename) const { if (properties.empty()) { throw std::runtime_error("No properties to write. Call readAndDecode() first."); } std::ofstream file(outputFilename); if (!file.is_open()) { throw std::runtime_error("Unable to open output file " + outputFilename); } for (const auto& prop : properties) { file << prop.recordType; for (const auto& field : prop.fields) { std::string escaped = field; size_t pos = 0; while ((pos = escaped.find(';', pos)) != std::string::npos) { escaped.replace(pos, 1, ";;"); pos += 2; } file << ";" << escaped; } file << "\n"; } file.close(); } }; // Example usage: // int main() { // try { // SylkHandler handler("example.slk"); // handler.readAndDecode(); // handler.printProperties(); // handler.write("output.slk"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-715 .SYLK ===== // ===== task-716 .SYMBOLICLINK [C++] ===== #include #include #include #include #include #include class SymbolicLinkParser { private: uint32_t reparseTag; uint16_t reparseDataLength; uint16_t reserved; uint16_t substituteNameOffset; uint16_t substituteNameLength; uint16_t printNameOffset; uint16_t printNameLength; uint32_t flags; std::wstring substituteName; std::wstring printName; public: SymbolicLinkParser(const std::string& filename = "") { if (!filename.empty()) { read(filename); } } void read(const std::string& filename) { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) { throw std::runtime_error("Unable to open file"); } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); std::vector data(size); if (!file.read(data.data(), size)) { throw std::runtime_error("Error reading file"); } if (size < 20) { throw std::runtime_error("File too small for header"); } memcpy(&reparseTag, data.data() + 0, sizeof(uint32_t)); memcpy(&reparseDataLength, data.data() + 4, sizeof(uint16_t)); memcpy(&reserved, data.data() + 6, sizeof(uint16_t)); memcpy(&substituteNameOffset, data.data() + 8, sizeof(uint16_t)); memcpy(&substituteNameLength, data.data() + 10, sizeof(uint16_t)); memcpy(&printNameOffset, data.data() + 12, sizeof(uint16_t)); memcpy(&printNameLength, data.data() + 14, sizeof(uint16_t)); memcpy(&flags, data.data() + 16, sizeof(uint32_t)); if (reparseTag != 0xA000000C) { throw std::runtime_error("Invalid ReparseTag"); } char* pathBuffer = data.data() + 20; substituteName = std::wstring(reinterpret_cast(pathBuffer + substituteNameOffset), substituteNameLength / 2); printName = std::wstring(reinterpret_cast(pathBuffer + printNameOffset), printNameLength / 2); } void printProperties() const { std::cout << "ReparseTag: 0x" << std::hex << reparseTag << std::dec << std::endl; std::cout << "ReparseDataLength: " << reparseDataLength << std::endl; std::cout << "Reserved: " << reserved << std::endl; std::cout << "SubstituteNameOffset: " << substituteNameOffset << std::endl; std::cout << "SubstituteNameLength: " << substituteNameLength << std::endl; std::cout << "PrintNameOffset: " << printNameOffset << std::endl; std::cout << "PrintNameLength: " << printNameLength << std::endl; std::cout << "Flags: 0x" << std::hex << flags << std::dec << std::endl; std::wcout << L"SubstituteName: " << substituteName << std::endl; std::wcout << L"PrintName: " << printName << std::endl; } void write(const std::string& filename) { if (substituteName.empty() || printName.empty() || reparseTag == 0) { throw std::runtime_error("All properties must be set before writing"); } std::vector subBytes(reinterpret_cast(substituteName.data()), reinterpret_cast(substituteName.data()) + substituteName.size() * 2); std::vector printBytes(reinterpret_cast(printName.data()), reinterpret_cast(printName.data()) + printName.size() * 2); substituteNameLength = subBytes.size(); printNameLength = printBytes.size(); substituteNameOffset = 0; printNameOffset = substituteNameLength; std::vector pathBuffer; pathBuffer.insert(pathBuffer.end(), subBytes.begin(), subBytes.end()); pathBuffer.insert(pathBuffer.end(), printBytes.begin(), printBytes.end()); reparseDataLength = pathBuffer.size() + 12; std::vector header(20); memcpy(header.data() + 0, &reparseTag, sizeof(uint32_t)); memcpy(header.data() + 4, &reparseDataLength, sizeof(uint16_t)); memcpy(header.data() + 6, &reserved, sizeof(uint16_t)); memcpy(header.data() + 8, &substituteNameOffset, sizeof(uint16_t)); memcpy(header.data() + 10, &substituteNameLength, sizeof(uint16_t)); memcpy(header.data() + 12, &printNameOffset, sizeof(uint16_t)); memcpy(header.data() + 14, &printNameLength, sizeof(uint16_t)); memcpy(header.data() + 16, &flags, sizeof(uint32_t)); std::ofstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Unable to write file"); } file.write(header.data(), header.size()); file.write(pathBuffer.data(), pathBuffer.size()); } }; // Example usage: ./program input.symboliclink int main(int argc, char* argv[]) { try { if (argc > 1) { SymbolicLinkParser parser(argv[1]); parser.printProperties(); } else { SymbolicLinkParser parser; parser.reparseTag = 0xA000000C; parser.flags = 0; parser.substituteName = L"\\??\\C:\\Target"; parser.printName = L"Target"; parser.write("output.symboliclink"); } } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } // ===== end task-716 .SYMBOLICLINK ===== // ===== task-717 .TAK [C++] ===== #include #include #include #include #include #include class TakFile { private: std::string filepath; std::map properties; // Simplified std::vector audioData; std::vector apeTags; public: TakFile(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary); if (!file) throw std::runtime_error("Cannot open file"); std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); decode(data); } void decode(const std::vector& data) { size_t offset = 0; std::string sig(data.begin() + offset, data.begin() + offset + 4); offset += 4; if (sig != "tBaK") throw std::runtime_error("Invalid TAK file"); properties["signature"] = sig; // Metadata loop using bit manipulation on uint32_t // Parse and store in properties } void printProperties() { for (const auto& p : properties) { std::cout << p.first << ": " << p.second << std::endl; } } void write(const std::string& newFilepath) { std::ofstream file(newFilepath, std::ios::binary); if (!file) throw std::runtime_error("Cannot write file"); file.write("tBaK", 4); // Write metadata from properties // Write audioData } }; // Usage: // int main() { // TakFile tak("example.tak"); // tak.read(); // tak.printProperties(); // tak.write("new.tak"); // return 0; // } // ===== end task-717 .TAK ===== // ===== task-718 .TAR [C++] ===== #include #include #include #include #include #include #include class TarHandler { private: std::string filepath; static const int BLOCK_SIZE = 512; struct Properties { std::string name; int mode; int uid; int gid; std::string size; // Keep as string for printing long mtime; int checksum; char typeflag; std::string linkname; std::string magic; std::string version; std::string uname; std::string gname; int devmajor; int devminor; std::string prefix; void print() const { std::cout << " name: " << name << std::endl; std::cout << " mode: " << mode << std::endl; std::cout << " uid: " << uid << std::endl; std::cout << " gid: " << gid << std::endl; std::cout << " size: " << size << std::endl; std::cout << " mtime: " << mtime << std::endl; std::cout << " checksum: " << checksum << std::endl; std::cout << " typeflag: " << typeflag << std::endl; std::cout << " linkname: " << linkname << std::endl; std::cout << " magic: " << magic << std::endl; std::cout << " version: " << version << std::endl; std::cout << " uname: " << uname << std::endl; std::cout << " gname: " << gname << std::endl; std::cout << " devmajor: " << devmajor << std::endl; std::cout << " devminor: " << devminor << std::endl; std::cout << " prefix: " << prefix << std::endl; } }; public: TarHandler(const std::string& filepath) : filepath(filepath) {} void readAndPrintProperties() { std::ifstream file(filepath, std::ios::binary); if (!file) return; long offset = 0; while (true) { char header[BLOCK_SIZE]; file.read(header, BLOCK_SIZE); if (file.gcount() < BLOCK_SIZE || isAllZero(header)) break; Properties props = decodeHeader(header); if (!props.name.empty()) { std::cout << "Entry at offset " << offset << ":" << std::endl; props.print(); std::cout << std::endl; } long size = std::stol(props.size, nullptr, 8); long dataBlocks = (size + BLOCK_SIZE - 1) / BLOCK_SIZE; file.seekg(dataBlocks * BLOCK_SIZE, std::ios::cur); offset += BLOCK_SIZE + dataBlocks * BLOCK_SIZE; } } private: Properties decodeHeader(const char* data) { Properties props; props.name = trim(std::string(data + 0, 100)); if (props.name.empty()) return props; props.mode = std::stoi(trim(std::string(data + 100, 8)), nullptr, 8); props.uid = std::stoi(trim(std::string(data + 108, 8)), nullptr, 8); props.gid = std::stoi(trim(std::string(data + 116, 8)), nullptr, 8); props.size = trim(std::string(data + 124, 12)); props.mtime = std::stol(trim(std::string(data + 136, 12)), nullptr, 8); props.checksum = std::stoi(trim(std::string(data + 148, 8)), nullptr, 8); props.typeflag = data[156]; props.linkname = trim(std::string(data + 157, 100)); props.magic = std::string(data + 257, 6); props.version = std::string(data + 263, 2); props.uname = trim(std::string(data + 265, 32)); props.gname = trim(std::string(data + 297, 32)); props.devmajor = std::stoi(trim(std::string(data + 329, 8)), nullptr, 8); props.devminor = std::stoi(trim(std::string(data + 337, 8)), nullptr, 8); props.prefix = trim(std::string(data + 345, 155)); return props; } bool isAllZero(const char* data) { for (int i = 0; i < BLOCK_SIZE; ++i) { if (data[i] != 0) return false; } return true; } std::string trim(const std::string& str) { size_t end = str.find_last_not_of('\0'); return (end == std::string::npos) ? "" : str.substr(0, end + 1); } public: void writeTar(const std::string& outputPath, const std::vector& filesToAdd) { std::ofstream tarFile(outputPath, std::ios::binary); if (!tarFile) return; for (const auto& filePath : filesToAdd) { addFileToTar(tarFile, filePath); } // End of archive char end[BLOCK_SIZE * 2] = {0}; tarFile.write(end, BLOCK_SIZE * 2); } private: void addFileToTar(std::ofstream& tarFile, const std::string& filePath) { struct stat stats; if (stat(filePath.c_str(), &stats) != 0) return; std::string name = filePath.substr(filePath.find_last_of('/') + 1); char header[BLOCK_SIZE] = {0}; strncpy(header + 0, name.c_str(), 100); snprintf(header + 100, 8, "%07o", stats.st_mode & 0777); snprintf(header + 108, 8, "%07o", stats.st_uid); snprintf(header + 116, 8, "%07o", stats.st_gid); snprintf(header + 124, 12, "%011lo", (long)stats.st_size); snprintf(header + 136, 12, "%011lo", (long)stats.st_mtime); header[156] = '0'; // Regular file strncpy(header + 257, "ustar\0", 6); strncpy(header + 263, "00", 2); std::string user = getlogin() ? getlogin() : "user"; strncpy(header + 265, user.c_str(), 32); strncpy(header + 297, user.c_str(), 32); // Checksum unsigned int checksum = 0; for (int i = 0; i < BLOCK_SIZE; ++i) checksum += static_cast(header[i]); checksum += 8 * ' '; snprintf(header + 148, 8, "%06o\0 ", checksum); tarFile.write(header, BLOCK_SIZE); std::ifstream src(filePath, std::ios::binary); if (src) { char buffer[1024]; while (src.read(buffer, sizeof(buffer))) { tarFile.write(buffer, src.gcount()); } tarFile.write(buffer, src.gcount()); // Last read } int padding = (BLOCK_SIZE - (stats.st_size % BLOCK_SIZE)) % BLOCK_SIZE; char pad[BLOCK_SIZE] = {0}; tarFile.write(pad, padding); } }; // ===== end task-718 .TAR ===== // ===== task-719 .TAZ [C++] ===== #include #include #include #include #include struct TAZProperties { std::string name; int mode; int uid; int gid; long size; long mtime; char typeflag; std::string linkname; std::string uname; std::string gname; int devmajor; int devminor; std::string prefix; }; class TAZHandler { private: std::string filename; std::vector properties; public: TAZHandler(const std::string& fn) : filename(fn) {} void openAndRead() { std::ifstream f(filename, std::ios::binary); std::vector data((std::istreambuf_iterator(f)), std::istreambuf_iterator()); if (data[0] != 0x1F || data[1] != 0x9D) { throw std::runtime_error("Invalid .Z magic number"); } unsigned char settings = data[2]; bool blockMode = (settings & 0x80) != 0; int maxBits = settings & 0x1F; std::vector compressed(data.begin() + 3, data.end()); std::vector decompressed = decompressLZW(compressed, maxBits, blockMode); parseTAR(decompressed); printProperties(); } std::vector decompressLZW(const std::vector& data, int maxBits, bool blockMode) { // Implement LZW decompression similar to Python/JS versions // Return decompressed vector std::vector output; // ... (implementation omitted for brevity; similar logic as above) return output; } void parseTAR(const std::vector& data) { size_t pos = 0; while (pos < data.size()) { if (data[pos] == 0) break; // Parse header fields similar to Python // Add to properties pos += 512 + std::ceil(static_cast(size) / 512) * 512; } } void printProperties() { for (const auto& prop : properties) { std::cout << "Name: " << prop.name << std::endl; // Print other fields } } void write(const std::vector& files, const std::string& outputFilename) { // Placeholder for TAR and LZW } }; // ===== end task-719 .TAZ ===== // ===== task-721 .TBZ [C++] ===== #include #include #include #include #include #include class TBZHandler { private: std::string filename; char mode; struct TarHeader { char name[100]; char mode[8]; char uid[8]; char gid[8]; char size[12]; char mtime[12]; char chksum[8]; char typeflag; char linkname[100]; char magic[6]; char version[2]; char uname[32]; char gname[32]; char devmajor[8]; char devminor[8]; char prefix[155]; }; public: TBZHandler(const std::string& fn, char m = 'r') : filename(fn), mode(m) {} void printProperties() { if (mode != 'r') { std::cerr << "Printing properties is only supported in read mode." << std::endl; return; } BZFILE* bzfile = BZ2_bzopen(filename.c_str(), "rb"); if (!bzfile) { std::cerr << "Error opening file." << std::endl; return; } TarHeader header; while (true) { int bytesRead = BZ2_bzread(bzfile, &header, sizeof(TarHeader)); if (bytesRead != sizeof(TarHeader)) break; // Check for end (two zero blocks) if (std::memset(&header, 0, sizeof(TarHeader)) == &header) break; // Approximate zero check std::string fullName = std::string(header.prefix) + std::string(header.name); long size = strtol(header.size, nullptr, 8); long mtime = strtol(header.mtime, nullptr, 8); std::cout << "Name: " << fullName << std::endl; std::cout << "Mode: " << header.mode << std::endl; std::cout << "UID: " << strtol(header.uid, nullptr, 8) << std::endl; std::cout << "GID: " << strtol(header.gid, nullptr, 8) << std::endl; std::cout << "Size: " << size << std::endl; std::cout << "Mtime: " << mtime << std::endl; std::cout << "Type flag: " << header.typeflag << std::endl; std::cout << "Link name: " << header.linkname << std::endl; std::cout << "User name: " << header.uname << std::endl; std::cout << "Group name: " << header.gname << std::endl; std::cout << "Device major: " << strtol(header.devmajor, nullptr, 8) << std::endl; std::cout << "Device minor: " << strtol(header.devminor, nullptr, 8) << std::endl; std::cout << "---" << std::endl; // Skip data blocks int blocks = (size + 511) / 512; char skip[512]; for (int i = 0; i < blocks; ++i) { BZ2_bzread(bzfile, skip, 512); } } BZ2_bzclose(bzfile); } void createArchive(const std::string& sourceFile) { if (mode != 'w') { std::cerr << "Writing is only supported in write mode." << std::endl; return; } // Basic write: create tar in memory, then compress with bz2 std::vector tarData; // Placeholder for tar creation (implement tar writing as needed) // ... (Add code to build tarData from sourceFile) BZFILE* bzfile = BZ2_bzopen(filename.c_str(), "wb"); if (!bzfile) { std::cerr << "Error opening file for write." << std::endl; return; } BZ2_bzwrite(bzfile, tarData.data(), tarData.size()); BZ2_bzclose(bzfile); } }; // Example usage for read: // TBZHandler handler("example.tbz", 'r'); // handler.printProperties(); // Example usage for write: // TBZHandler handler("new.tbz", 'w'); // handler.createArchive("path/to/file.txt"); // ===== end task-721 .TBZ ===== // ===== task-722 .TBZ2 [C] ===== // Compile with: gcc tbz2_handler.c -o tbz2_handler -lbz2 -lz (may need additional libs for tar, but here using simple tar parse) // Note: For full tar support, consider libtar, but here a basic manual parser for ustar. #include #include #include #include #include #include #include #include #define BLOCK_SIZE 512 typedef struct { char name[100]; char mode[8]; char uid[8]; char gid[8]; char size[12]; char mtime[12]; char chksum[8]; char typeflag; char linkname[100]; char magic[6]; char version[2]; char uname[32]; char gname[32]; char devmajor[8]; char devminor[8]; char prefix[155]; char pad[12]; } TarHeader; typedef struct { char* bzip2_magic; int bzip2_block_level; // List of items would be dynamic array in full impl } TBZ2Properties; void print_properties(unsigned char* decompressed, size_t decomp_size) { size_t offset = 0; while (offset < decomp_size) { if (decompressed[offset] == 0) break; TarHeader* header = (TarHeader*)(decompressed + offset); if (strncmp(header->magic, "ustar", 5) != 0) break; char full_name[256]; snprintf(full_name, sizeof(full_name), "%s%s%s", header->prefix, header->prefix[0] ? "/" : "", header->name); long size = strtol(header->size, NULL, 8); long mtime = strtol(header->mtime, NULL, 8); struct tm* tm = localtime(&mtime); char time_str[20]; strftime(time_str, sizeof(time_str), "%Y-%m-%dT%H:%M:%S", tm); printf("Item: %s\n", full_name); printf(" Mode: %lo\n", strtol(header->mode, NULL, 8)); printf(" UID: %ld\n", strtol(header->uid, NULL, 8)); printf(" GID: %ld\n", strtol(header->gid, NULL, 8)); printf(" Size: %ld\n", size); printf(" Mtime: %ld (%s)\n", mtime, time_str); printf(" Typeflag: %c\n", header->typeflag); printf(" Linkname: %s\n", header->linkname); printf(" Uname: %s\n", header->uname); printf(" Gname: %s\n", header->gname); printf(" Devmajor: %ld\n", strtol(header->devmajor, NULL, 8)); printf(" Devminor: %ld\n", strtol(header->devminor, NULL, 8)); printf("\n"); offset += BLOCK_SIZE + ((size + BLOCK_SIZE - 1) / BLOCK_SIZE * BLOCK_SIZE); } } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } // Read file FILE* file = fopen(argv[1], "rb"); fseek(file, 0, SEEK_END); size_t file_size = ftell(file); fseek(file, 0, SEEK_SET); unsigned char* compressed = malloc(file_size); fread(compressed, 1, file_size, file); fclose(file); // bzip2 header printf("bzip2 Magic: %c%c%c\n", compressed[0], compressed[1], compressed[2]); int block_level = compressed[3] - '0'; printf("bzip2 Block Size Level: %d\n\n", block_level); // Decompress unsigned int decomp_size = file_size * 10; // Estimate unsigned char* decompressed = malloc(decomp_size); int ret = BZ2_bzBuffToBuffDecompress((char*)decompressed, &decomp_size, (char*)compressed, file_size, 0, 0); if (ret != BZ_OK) { printf("Decompression failed: %d\n", ret); free(compressed); free(decompressed); return 1; } // Print tar properties print_properties(decompressed, decomp_size); free(compressed); free(decompressed); // For write: Implement similar with BZ2_bzBuffToBuffCompress and tar header creation (omitted for brevity) return 0; } // ===== end task-722 .TBZ2 ===== // ===== task-723 .TC [C++] ===== #include #include #include #include #include class TCFile { private: std::string filename; std::vector data; public: TCFile(const std::string& fn) : filename(fn) {} void open() { std::ifstream f(filename, std::ios::binary); data.assign(std::istreambuf_iterator(f), {}); } std::map decode(const std::string& password) { std::vector salt(data.begin(), data.begin() + 64); // Placeholder for key derivation and decryption std::vector decrypted(data.begin() + 64, data.begin() + 512); std::map props; props["signature"] = std::string(decrypted.begin(), decrypted.begin() + 4); // Add other fields using reinterpret_cast for unpacking return props; } void printProperties(const std::map& props) { for (const auto& p : props) { std::cout << p.first << ": " << p.second << std::endl; } } void write(const std::map& props) { // Placeholder } }; int main() { TCFile tc("test.tc"); tc.open(); auto props = tc.decode("password"); tc.printProperties(props); return 0; } // ===== end task-723 .TC ===== // ===== task-724 .TER [C] ===== #include #include #include #include typedef struct { char* filepath; char header[17]; int16_t size; uint16_t xpts; uint16_t ypts; float scale[3]; float crad; uint32_t crvm; int16_t heightscale; int16_t baseheight; int16_t* elevations; int elevations_size; char eof[5]; } TerFile; TerFile* ter_create(const char* filepath) { TerFile* ter = (TerFile*)malloc(sizeof(TerFile)); ter->filepath = strdup(filepath); ter->size = 0; ter->xpts = 0; ter->ypts = 0; ter->scale[0] = 30.0f; ter->scale[1] = 30.0f; ter->scale[2] = 30.0f; ter->crad = 6370.0f; ter->crvm = 0; ter->heightscale = 0; ter->baseheight = 0; ter->elevations = NULL; ter->elevations_size = 0; memset(ter->eof, 0, 5); return ter; } void ter_destroy(TerFile* ter) { free(ter->filepath); if (ter->elevations) free(ter->elevations); free(ter); } int ter_read(TerFile* ter) { FILE* f = fopen(ter->filepath, "rb"); if (!f) return -1; fseek(f, 0, SEEK_END); long file_size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = (uint8_t*)malloc(file_size); fread(data, 1, file_size, f); fclose(f); int offset = 0; // Header memcpy(ter->header, data + offset, 16); ter->header[16] = '\0'; offset += 16; while (offset < file_size - 4) { char chunk_id[5] = {0}; memcpy(chunk_id, data + offset, 4); offset += 4; if (strcmp(chunk_id, "SIZE") == 0) { memcpy(&ter->size, data + offset, 2); ter->size += 1; offset += 4; } else if (strcmp(chunk_id, "XPTS") == 0) { memcpy(&ter->xpts, data + offset, 2); offset += 4; } else if (strcmp(chunk_id, "YPTS") == 0) { memcpy(&ter->ypts, data + offset, 2); offset += 4; } else if (strcmp(chunk_id, "SCAL") == 0) { memcpy(ter->scale, data + offset, 12); offset += 12; } else if (strcmp(chunk_id, "CRAD") == 0) { memcpy(&ter->crad, data + offset, 4); offset += 4; } else if (strcmp(chunk_id, "CRVM") == 0) { memcpy(&ter->crvm, data + offset, 4); offset += 4; } else if (strcmp(chunk_id, "ALTW") == 0) { memcpy(&ter->heightscale, data + offset, 2); memcpy(&ter->baseheight, data + offset + 2, 2); offset += 4; if (ter->xpts == 0) ter->xpts = ter->size; if (ter->ypts == 0) ter->ypts = ter->size; ter->elevations_size = ter->xpts * ter->ypts; ter->elevations = (int16_t*)malloc(ter->elevations_size * 2); memcpy(ter->elevations, data + offset, ter->elevations_size * 2); offset += ter->elevations_size * 2; } else if (strcmp(chunk_id, "EOF ") == 0) { strcpy(ter->eof, chunk_id); break; } else { break; } } free(data); return 0; } void ter_print_properties(TerFile* ter) { printf("Header: %s\n", ter->header); printf("Size: %d\n", ter->size); printf("Xpts: %u\n", ter->xpts); printf("Ypts: %u\n", ter->ypts); printf("Scale: %f %f %f\n", ter->scale[0], ter->scale[1], ter->scale[2]); printf("Planet Radius: %f\n", ter->crad); printf("Curve Mode: %u\n", ter->crvm); printf("Height Scale: %d\n", ter->heightscale); printf("Base Height: %d\n", ter->baseheight); printf("Elevations: ["); for (int i = 0; i < ter->elevations_size; i++) { printf("%d", ter->elevations[i]); if (i < ter->elevations_size - 1) printf(", "); } printf("]\n"); printf("EOF Marker: %s\n", ter->eof); } int ter_write(TerFile* ter, const char* new_filepath) { if (!new_filepath) new_filepath = ter->filepath; FILE* f = fopen(new_filepath, "wb"); if (!f) return -1; fwrite(ter->header, 1, 16, f); fwrite("SIZE", 1, 4, f); int16_t size_val = ter->size - 1; fwrite(&size_val, 2, 1, f); int16_t padding = 0; fwrite(&padding, 2, 1, f); if (ter->xpts != ter->size || ter->ypts != ter->size) { fwrite("XPTS", 1, 4, f); fwrite(&ter->xpts, 2, 1, f); fwrite(&padding, 2, 1, f); fwrite("YPTS", 1, 4, f); fwrite(&ter->ypts, 2, 1, f); fwrite(&padding, 2, 1, f); } if (ter->scale[0] != 30.0f || ter->scale[1] != 30.0f || ter->scale[2] != 30.0f) { fwrite("SCAL", 1, 4, f); fwrite(ter->scale, 4, 3, f); } if (ter->crad != 6370.0f) { fwrite("CRAD", 1, 4, f); fwrite(&ter->crad, 4, 1, f); } if (ter->crvm != 0) { fwrite("CRVM", 1, 4, f); fwrite(&ter->crvm, 4, 1, f); } fwrite("ALTW", 1, 4, f); fwrite(&ter->heightscale, 2, 1, f); fwrite(&ter->baseheight, 2, 1, f); fwrite(ter->elevations, 2, ter->elevations_size, f); fwrite("EOF ", 1, 4, f); fclose(f); return 0; } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } TerFile* ter = ter_create(argv[1]); if (ter_read(ter) != 0) { printf("Error reading file\n"); ter_destroy(ter); return 1; } ter_print_properties(ter); // To write: ter_write(ter, "output.ter"); ter_destroy(ter); return 0; } // ===== end task-724 .TER ===== // ===== task-725 .TGA [C++] ===== #include #include #include #include class TGAHandler { private: uint8_t idLength; uint8_t colorMapType; uint8_t imageType; uint16_t colorMapFirstEntryIndex; uint16_t colorMapLength; uint8_t colorMapEntrySize; uint16_t xOrigin; uint16_t yOrigin; uint16_t imageWidth; uint16_t imageHeight; uint8_t pixelDepth; uint8_t imageDescriptor; public: TGAHandler(const std::string& filepath) { read(filepath); } void read(const std::string& filepath) { std::ifstream file(filepath, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file."); } std::vector header(18); file.read(reinterpret_cast(header.data()), 18); if (file.gcount() < 18) { throw std::runtime_error("Invalid TGA file."); } idLength = header[0]; colorMapType = header[1]; imageType = header[2]; colorMapFirstEntryIndex = static_cast(header[3]) | (static_cast(header[4]) << 8); colorMapLength = static_cast(header[5]) | (static_cast(header[6]) << 8); colorMapEntrySize = header[7]; xOrigin = static_cast(header[8]) | (static_cast(header[9]) << 8); yOrigin = static_cast(header[10]) | (static_cast(header[11]) << 8); imageWidth = static_cast(header[12]) | (static_cast(header[13]) << 8); imageHeight = static_cast(header[14]) | (static_cast(header[15]) << 8); pixelDepth = header[16]; imageDescriptor = header[17]; // Image data reading omitted } void printProperties() const { std::cout << "ID Length: " << static_cast(idLength) << std::endl; std::cout << "Color Map Type: " << static_cast(colorMapType) << std::endl; std::cout << "Image Type: " << static_cast(imageType) << std::endl; std::cout << "Color Map First Entry Index: " << colorMapFirstEntryIndex << std::endl; std::cout << "Color Map Length: " << colorMapLength << std::endl; std::cout << "Color Map Entry Size: " << static_cast(colorMapEntrySize) << std::endl; std::cout << "X Origin: " << xOrigin << std::endl; std::cout << "Y Origin: " << yOrigin << std::endl; std::cout << "Image Width: " << imageWidth << std::endl; std::cout << "Image Height: " << imageHeight << std::endl; std::cout << "Pixel Depth: " << static_cast(pixelDepth) << std::endl; std::cout << "Image Descriptor: " << static_cast(imageDescriptor) << std::endl; } void write(const std::string& filepath, const std::vector& imageData = {}) const { std::ofstream file(filepath, std::ios::binary); if (!file) { throw std::runtime_error("Cannot write file."); } uint8_t header[18] = { idLength, colorMapType, imageType, static_cast(colorMapFirstEntryIndex & 0xFF), static_cast((colorMapFirstEntryIndex >> 8) & 0xFF), static_cast(colorMapLength & 0xFF), static_cast((colorMapLength >> 8) & 0xFF), colorMapEntrySize, static_cast(xOrigin & 0xFF), static_cast((xOrigin >> 8) & 0xFF), static_cast(yOrigin & 0xFF), static_cast((yOrigin >> 8) & 0xFF), static_cast(imageWidth & 0xFF), static_cast((imageWidth >> 8) & 0xFF), static_cast(imageHeight & 0xFF), static_cast((imageHeight >> 8) & 0xFF), pixelDepth, imageDescriptor }; file.write(reinterpret_cast(header), 18); file.write(reinterpret_cast(imageData.data()), imageData.size()); } }; // Example usage: // int main() { // try { // TGAHandler tga("sample.tga"); // tga.printProperties(); // tga.write("output.tga"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-725 .TGA ===== // ===== task-726 .TGT [C++] ===== #include #include #include #include #include #include class TGTFile { private: std::map> properties; public: TGTFile(const std::string& filename = "") { if (!filename.empty()) { read(filename); } } void read(const std::string& filename) { std::ifstream file(filename); if (!file) { std::cerr << "Failed to open file." << std::endl; return; } std::stringstream buffer; buffer << file.rdbuf(); parse(buffer.str()); } void parse(const std::string& content) { properties.clear(); std::istringstream iss(content); std::string line; std::string currentTarget; while (std::getline(iss, line)) { line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); if (line.back() == ')') { currentTarget = line.substr(0, line.size() - 1); currentTarget.erase(currentTarget.find_last_not_of(" \t") + 1); properties[currentTarget] = {}; } else if (!line.empty() && line.find('=') != std::string::npos && !currentTarget.empty()) { size_t pos = line.find('='); std::string key = line.substr(0, pos); key.erase(key.find_last_not_of(" \t") + 1); std::string value = line.substr(pos + 1); value.erase(0, value.find_first_not_of(" \t")); value = std::regex_replace(value, std::regex(";;"), ""); if (std::regex_match(key, std::regex("targ_.*|NATIVE_LIB_DIRS"))) { properties[currentTarget][key] = value; } } } } void printProperties() const { for (const auto& targetPair : properties) { std::cout << "Target: " << targetPair.first << std::endl; for (const auto& propPair : targetPair.second) { std::cout << " " << propPair.first << ": " << propPair.second << std::endl; } std::cout << std::endl; } } void write(const std::string& filename) const { std::ofstream file(filename); if (!file) { std::cerr << "Failed to write file." << std::endl; return; } file << "# Sample .TGT configuration script\n"; file << "targ_emul=\n"; file << "targ_extra_emuls=\n"; file << "targ_extra_libpath=\n"; file << "targ_extra_ofiles=\n"; file << "targ64_extra_emuls=\n"; file << "targ64_extra_libpath=\n"; file << "case \"${targ}\" in\n"; for (const auto& targetPair : properties) { file << " " << targetPair.first << ")\n"; for (const auto& propPair : targetPair.second) { file << " " << propPair.first << "=" << propPair.second << " ;;\n"; } } file << " *) echo \"${targ} emulation unknown.\" ;;\n"; file << "esac\n"; file << "case \"${targ_obj}\" in\n"; file << "# NATIVE_LIB_DIRS setting\n"; file << "esac\n"; } }; // Example usage int main() { TGTFile tgt("example.tgt"); tgt.printProperties(); tgt.write("output.tgt"); return 0; } // ===== end task-726 .TGT ===== // ===== task-727 .TGZ [C] ===== #include #include #include #include #include #include #include #include typedef struct { char *filename; struct { unsigned char id1, id2, cm, flg, xfl, os; unsigned int mtime, crc32, isize; unsigned short extra_len, header_crc; char *fname, *comment, *extra; } gzip_props; struct TarEntry { char *name; unsigned int mode, uid, gid, size, mtime, chksum, devmajor, devminor; char typeflag; char *linkname, *magic, *version, *uname, *gname, *prefix; struct TarEntry *next; } *tar_entries; } TGZHandler; void init_tgz_handler(TGZHandler *handler, const char *filename) { handler->filename = strdup(filename); memset(&handler->gzip_props, 0, sizeof(handler->gzip_props)); handler->tar_entries = NULL; } void free_tgz_handler(TGZHandler *handler) { free(handler->filename); free(handler->gzip_props.fname); free(handler->gzip_props.comment); free(handler->gzip_props.extra); struct TarEntry *entry = handler->tar_entries; while (entry) { struct TarEntry *next = entry->next; free(entry->name); free(entry->linkname); free(entry->magic); free(entry->version); free(entry->uname); free(entry->gname); free(entry->prefix); free(entry); entry = next; } } int read_file(const char *filename, unsigned char **data, size_t *size) { FILE *f = fopen(filename, "rb"); if (!f) return -1; fseek(f, 0, SEEK_END); *size = ftell(f); fseek(f, 0, SEEK_SET); *data = malloc(*size); fread(*data, 1, *size, f); fclose(f); return 0; } void tgz_read(TGZHandler *handler) { unsigned char *data; size_t size; if (read_file(handler->filename, &data, &size) < 0) return; size_t pos = 0; handler->gzip_props.id1 = data[pos++]; handler->gzip_props.id2 = data[pos++]; handler->gzip_props.cm = data[pos++]; handler->gzip_props.flg = data[pos++]; handler->gzip_props.mtime = data[pos] | (data[pos+1] << 8) | (data[pos+2] << 16) | (data[pos+3] << 24); pos += 4; handler->gzip_props.xfl = data[pos++]; handler->gzip_props.os = data[pos++]; if (handler->gzip_props.flg & 4) { handler->gzip_props.extra_len = data[pos] | (data[pos+1] << 8); pos += 2; handler->gzip_props.extra = malloc(handler->gzip_props.extra_len); memcpy(handler->gzip_props.extra, data + pos, handler->gzip_props.extra_len); pos += handler->gzip_props.extra_len; } if (handler->gzip_props.flg & 8) { size_t start = pos; while (data[pos]) pos++; handler->gzip_props.fname = malloc(pos - start + 1); memcpy(handler->gzip_props.fname, data + start, pos - start); handler->gzip_props.fname[pos - start] = '\0'; pos++; } if (handler->gzip_props.flg & 16) { size_t start = pos; while (data[pos]) pos++; handler->gzip_props.comment = malloc(pos - start + 1); memcpy(handler->gzip_props.comment, data + start, pos - start); handler->gzip_props.comment[pos - start] = '\0'; pos++; } if (handler->gzip_props.flg & 2) { handler->gzip_props.header_crc = data[pos] | (data[pos+1] << 8); pos += 2; } z_stream stream; stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; inflateInit2(&stream, -MAX_WBITS); // Raw deflate stream.avail_in = size - pos - 8; stream.next_in = data + pos; unsigned char *decompressed = malloc(1024 * 1024 * 10); // Assume max size stream.avail_out = 1024 * 1024 * 10; stream.next_out = decompressed; inflate(&stream, Z_FINISH); size_t dec_size = stream.total_out; inflateEnd(&stream); size_t tar_pos = 0; struct TarEntry *last = NULL; while (tar_pos < dec_size) { unsigned char *header = decompressed + tar_pos; int all_zero = 1; for (int i = 0; i < 512; i++) if (header[i]) { all_zero = 0; break; } if (all_zero) break; struct TarEntry *entry = malloc(sizeof(struct TarEntry)); memset(entry, 0, sizeof(*entry)); entry->name = strndup((char*)header, 100); entry->mode = strtol((char*)header + 100, NULL, 8); entry->uid = strtol((char*)header + 108, NULL, 8); entry->gid = strtol((char*)header + 116, NULL, 8); entry->size = strtol((char*)header + 124, NULL, 8); entry->mtime = strtol((char*)header + 136, NULL, 8); entry->chksum = strtol((char*)header + 148, NULL, 8); entry->typeflag = header[156]; entry->linkname = strndup((char*)header + 157, 100); entry->magic = strndup((char*)header + 257, 6); entry->version = strndup((char*)header + 263, 2); entry->uname = strndup((char*)header + 265, 32); entry->gname = strndup((char*)header + 297, 32); entry->devmajor = strtol((char*)header + 329, NULL, 8); entry->devminor = strtol((char*)header + 337, NULL, 8); entry->prefix = strndup((char*)header + 345, 155); if (!handler->tar_entries) handler->tar_entries = entry; if (last) last->next = entry; last = entry; tar_pos += 512 + ((entry->size + 511) / 512 * 512); } handler->gzip_props.crc32 = data[size - 8] | (data[size - 7] << 8) | (data[size - 6] << 16) | (data[size - 5] << 24); handler->gzip_props.isize = data[size - 4] | (data[size - 3] << 8) | (data[size - 2] << 16) | (data[size - 1] << 24); free(decompressed); free(data); } void tgz_print_properties(const TGZHandler *handler) { printf("GZIP Properties:\n"); printf("- ID1: %u\n", handler->gzip_props.id1); printf("- ID2: %u\n", handler->gzip_props.id2); printf("- CM: %u\n", handler->gzip_props.cm); printf("- FLG: %u\n", handler->gzip_props.flg); printf("- MTIME: %u\n", handler->gzip_props.mtime); printf("- XFL: %u\n", handler->gzip_props.xfl); printf("- OS: %u\n", handler->gzip_props.os); if (handler->gzip_props.extra_len) printf("- Extra Length: %u\n", handler->gzip_props.extra_len); if (handler->gzip_props.fname) printf("- Original Filename: %s\n", handler->gzip_props.fname); if (handler->gzip_props.comment) printf("- Comment: %s\n", handler->gzip_props.comment); if (handler->gzip_props.header_crc) printf("- Header CRC: %u\n", handler->gzip_props.header_crc); printf("- CRC32: %u\n", handler->gzip_props.crc32); printf("- ISIZE: %u\n", handler->gzip_props.isize); printf("\nTAR Entry Properties:\n"); struct TarEntry *entry = handler->tar_entries; while (entry) { printf("Entry: %s%s%s\n", entry->prefix ? entry->prefix : "", entry->prefix ? "/" : "", entry->name); printf(" - Mode: %o\n", entry->mode); printf(" - UID: %u\n", entry->uid); printf(" - GID: %u\n", entry->gid); printf(" - Size: %u\n", entry->size); printf(" - MTime: %u\n", entry->mtime); printf(" - Checksum: %u\n", entry->chksum); printf(" - Type: %c\n", entry->typeflag); printf(" - Linkname: %s\n", entry->linkname); printf(" - Magic: %s\n", entry->magic); printf(" - Version: %s\n", entry->version); printf(" - UName: %s\n", entry->uname); printf(" - GName: %s\n", entry->gname); printf(" - DevMajor: %u\n", entry->devmajor); printf(" - DevMinor: %u\n", entry->devminor); entry = entry->next; } } void tgz_write(const char *output_filename, const char **files_to_archive, int num_files) { FILE *tar_f = tmpfile(); for (int i = 0; i < num_files; i++) { const char *filepath = files_to_archive[i]; FILE *fin = fopen(filepath, "rb"); if (!fin) continue; fseek(fin, 0, SEEK_END); size_t content_size = ftell(fin); fseek(fin, 0, SEEK_SET); unsigned char *content = malloc(content_size); fread(content, 1, content_size, fin); fclose(fin); struct stat st; stat(filepath, &st); char name[101]; strncpy(name, strrchr(filepath, '/') ? strrchr(filepath, '/') + 1 : filepath, 100); name[100] = '\0'; char mode[8]; snprintf(mode, 8, "%07o", st.st_mode & 0777); char uid[8]; snprintf(uid, 8, "%07o", st.st_uid); char gid[8]; snprintf(gid, 8, "%07o", st.st_gid); char size[12]; snprintf(size, 12, "%011o", (unsigned)content_size); char mtime[12]; snprintf(mtime, 12, "%011o", (unsigned)st.st_mtime); char typeflag = '0'; char linkname[101] = {0}; char magic[7] = "ustar\0"; char version[3] = "00"; char uname[33]; getlogin_r(uname, 32); uname[32] = '\0'; char gname[33]; getlogin_r(gname, 32); gname[32] = '\0'; char devmajor[8] = "0000000\0"; char devminor[8] = "0000000\0"; char prefix[156] = {0}; char header[512] = {0}; memcpy(header, name, strlen(name)); memcpy(header + 100, mode, 7); header[107] = '\0'; memcpy(header + 108, uid, 7); header[115] = '\0'; memcpy(header + 116, gid, 7); header[123] = '\0'; memcpy(header + 124, size, 11); header[135] = '\0'; memcpy(header + 136, mtime, 11); header[147] = '\0'; memset(header + 148, ' ', 8); header[156] = typeflag; memcpy(header + 157, linkname, strlen(linkname)); memcpy(header + 257, magic, 6); memcpy(header + 263, version, 2); memcpy(header + 265, uname, strlen(uname)); memcpy(header + 297, gname, strlen(gname)); memcpy(header + 329, devmajor, 8); memcpy(header + 337, devminor, 8); memcpy(header + 345, prefix, strlen(prefix)); // Checksum unsigned chksum = 0; for (int j = 0; j < 512; j++) chksum += header[j]; char chksum_str[9]; snprintf(chksum_str, 9, "%06o\0 ", chksum); memcpy(header + 148, chksum_str, 8); fwrite(header, 1, 512, tar_f); fwrite(content, 1, content_size, tar_f); size_t pad = (512 - (content_size % 512)) % 512; char zero_pad[512] = {0}; fwrite(zero_pad, 1, pad, tar_f); free(content); } char zero_block[1024] = {0}; fwrite(zero_block, 1, 1024, tar_f); fseek(tar_f, 0, SEEK_END); size_t tar_size = ftell(tar_f); fseek(tar_f, 0, SEEK_SET); unsigned char *tar_data = malloc(tar_size); fread(tar_data, 1, tar_size, tar_f); fclose(tar_f); uLongf compressed_size = compressBound(tar_size); unsigned char *compressed = malloc(compressed_size); compress(compressed, &compressed_size, tar_data, tar_size); FILE *out = fopen(output_filename, "wb"); // Write GZIP header (simple, no optionals) unsigned char gzip_header[10] = {0x1F, 0x8B, 8, 0, 0, 0, 0, 0, 0, 3}; // OS Unix time_t now = time(NULL); memcpy(gzip_header + 4, &now, 4); fwrite(gzip_header, 1, 10, out); fwrite(compressed, 1, compressed_size, out); uLong crc = crc32(0L, tar_data, tar_size); fwrite(&crc, 4, 1, out); uLong isize = tar_size; fwrite(&isize, 4, 1, out); fclose(out); free(tar_data); free(compressed); } // Example usage: // int main() { // TGZHandler handler; // init_tgz_handler(&handler, "example.tgz"); // tgz_read(&handler); // tgz_print_properties(&handler); // const char *files[] = {"file1.txt", "file2.txt"}; // tgz_write("new.tgz", files, 2); // free_tgz_handler(&handler); // return 0; // } // ===== end task-727 .TGZ ===== // ===== task-728 .THM [C] ===== #include #include #include typedef struct { char *filepath; unsigned char *data; long size; char *properties; // JSON-like string for properties } ThmFile; ThmFile* thm_new(const char *filepath) { ThmFile* thm = malloc(sizeof(ThmFile)); thm->filepath = strdup(filepath); thm->data = NULL; thm->size = 0; thm->properties = NULL; return thm; } void thm_open(ThmFile *thm) { FILE *f = fopen(thm->filepath, "rb"); if (f) { fseek(f, 0, SEEK_END); thm->size = ftell(f); fseek(f, 0, SEEK_SET); thm->data = malloc(thm->size); fread(thm->data, 1, thm->size, f); fclose(f); } } void thm_decode(ThmFile *thm) { if (!thm->data) return; int ofs = 0; char name[101] = {0}; strncpy(name, (char*)thm->data + ofs, 100); ofs += 100; char numbersStr[157] = {0}; strncpy(numbersStr, (char*)thm->data + ofs, 156); // Parse numbers (simplified) char *token = strtok(numbersStr, " \0"); int numbers[10] = {0}; int idx = 0; while (token && idx < 10) { numbers[idx++] = strtol(token, NULL, 8); token = strtok(NULL, " \0"); } int bodyLen = numbers[3]; ofs += 156; char ustar[6] = {0}; strncpy(ustar, (char*)thm->data + ofs + 1, 5); char nogroup[8] = {0}; strncpy(nogroup, (char*)thm->data + ofs + 40, 7); ofs += 156; unsigned char *body = thm->data + ofs; // Extract XML from tar (simplified, assume first file is XML) char tarName[101] = {0}; strncpy(tarName, (char*)body, 100); char sizeStr[12] = {0}; strncpy(sizeStr, (char*)body + 124, 11); int xmlSize = strtol(sizeStr, NULL, 8); char *xml = malloc(xmlSize + 1); strncpy(xml, (char*)body + 512, xmlSize); xml[xmlSize] = '\0'; // Basic XML parse (find key values) char *version = strstr(xml, "version=\""); char *bgColor = strstr(xml, "properties = props; free(xml); } void thm_print_properties(ThmFile *thm) { if (thm->properties) printf("%s", thm->properties); } void thm_write(ThmFile *thm, const char *new_filepath) { if (!thm->data) return; FILE *f = fopen(new_filepath, "wb"); if (f) { fwrite(thm->data, 1, thm->size, f); fclose(f); } } void thm_free(ThmFile *thm) { free(thm->filepath); free(thm->data); free(thm->properties); free(thm); } // ===== end task-728 .THM ===== // ===== task-729 .TIF [C++] ===== #include #include #include #include #include #include struct Entry { uint16_t tagId; uint16_t type; uint32_t count; uint32_t valOffset; }; struct Ifd { uint16_t numEntries; std::vector entries; uint32_t nextOffset; }; class TiffHandler { private: std::string filepath; std::string byteOrder; uint16_t version; uint32_t firstIfdOffset; std::vector ifds; std::vector data; std::map baselineTags; bool isLittleEndian; void loadBaselineTags() { baselineTags[254] = "NewSubfileType"; // Add all... baselineTags[33432] = "Copyright"; } public: TiffHandler(const std::string& fp) : filepath(fp) { loadBaselineTags(); decode(); } void decode() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); auto size = file.tellg(); data.resize(size); file.seekg(0); file.read(reinterpret_cast(data.data()), size); file.close(); byteOrder = std::string(1, data[0]) + std::string(1, data[1]); isLittleEndian = byteOrder == "II"; version = readUint16(2); firstIfdOffset = readUint32(4); uint32_t offset = firstIfdOffset; while (offset != 0) { uint16_t numEntries = readUint16(offset); Ifd ifd; ifd.numEntries = numEntries; uint32_t entryOffset = offset + 2; for (uint16_t i = 0; i < numEntries; ++i) { Entry entry; entry.tagId = readUint16(entryOffset); entry.type = readUint16(entryOffset + 2); entry.count = readUint32(entryOffset + 4); entry.valOffset = readUint32(entryOffset + 8); ifd.entries.push_back(entry); entryOffset += 12; } ifd.nextOffset = readUint32(offset + 2 + 12 * numEntries); ifds.push_back(ifd); offset = ifd.nextOffset; } } uint16_t readUint16(uint32_t pos) { uint16_t val; std::memcpy(&val, &data[pos], 2); if (!isLittleEndian) val = __builtin_bswap16(val); return val; } uint32_t readUint32(uint32_t pos) { uint32_t val; std::memcpy(&val, &data[pos], 4); if (!isLittleEndian) val = __builtin_bswap32(val); return val; } // Similar for other types... std::string readProperty(uint16_t tagId) { // Implement search and read return "Value"; } void printProperties() { std::cout << "Byte Order: " << byteOrder << std::endl; std::cout << "Version: " << version << std::endl; std::cout << "First IFD Offset: " << firstIfdOffset << std::endl; for (size_t i = 0; i < ifds.size(); ++i) { const auto& ifd = ifds[i]; std::cout << "\nIFD " << i << ":" << std::endl; std::cout << " Number of Entries: " << ifd.numEntries << std::endl; for (const auto& entry : ifd.entries) { auto it = baselineTags.find(entry.tagId); std::string tagName = (it != baselineTags.end()) ? it->second : "Unknown"; std::string value = readEntryValue(entry); std::cout << " " << tagName << " (ID: " << entry.tagId << "): " << value << std::endl; } } } std::string readEntryValue(const Entry& entry) { // Implement based on type return "Value"; } void write(const std::string& newFilepath) { std::ofstream file(newFilepath, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); file.close(); } void updateProperty(uint16_t tagId, const std::string& newValue) { // Modify data vector } }; // Example: // int main() { // TiffHandler handler("example.tif"); // handler.printProperties(); // // handler.updateProperty(256, "1024"); // // handler.write("modified.tif"); // return 0; // } // ===== end task-729 .TIF ===== // ===== task-730 .TIFF [C++] ===== #include #include #include #include #include #include // For byte order class TiffHandler { private: std::string filepath; std::vector data; bool littleEndian; std::map tags; std::map> tagMap; // name, type public: TiffHandler(const std::string& fp) : filepath(fp) { // Populate tagMap tagMap[254] = {"NewSubfileType", "LONG"}; // Add all... } void decode() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(data.data(), size); char byteOrder[3] = {data[0], data[1], '\0'}; littleEndian = std::string(byteOrder) == "II"; // Parse version, IFD (similar logic as above) // Implement parsing and populate tags } void printProperties() { if (tags.empty()) decode(); std::cout << "TIFF Properties:" << std::endl; for (const auto& [name, value] : tags) { std::cout << name << ": " << value << std::endl; } } void write(const std::string& newFilepath, const std::string& modifyTag, const std::string& newValue) { if (data.empty()) decode(); std::ofstream out(newFilepath, std::ios::binary); out.write(data.data(), data.size()); // Modify logic here } }; // Usage: // TiffHandler handler("example.tiff"); // handler.printProperties(); // handler.write("modified.tiff", "ImageWidth", "1024"); // ===== end task-730 .TIFF ===== // ===== task-731 .TLB [C++] ===== #include #include #include #include #include #include class TLBParser { private: std::string filename; std::vector data; std::map> properties; // Simplified for header public: TLBParser(const std::string& fn) : filename(fn) {} void read() { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) { throw std::runtime_error("Cannot open file."); } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(reinterpret_cast(data.data()), size); } void decode() { if (data.empty()) { throw std::runtime_error("No data loaded."); } const uint8_t* ptr = data.data(); size_t offset = 0; // TypeLib Header properties["header"] = {}; uint32_t magic1; std::memcpy(&magic1, ptr + offset, 4); offset += 4; properties["header"]["magic1"] = magic1; uint32_t magic2; std::memcpy(&magic2, ptr + offset, 4); offset += 4; properties["header"]["magic2"] = magic2; int32_t guid; std::memcpy(&guid, ptr + offset, 4); offset += 4; properties["header"]["guid"] = guid; uint32_t locale_id; std::memcpy(&locale_id, ptr + offset, 4); offset += 4; properties["header"]["locale_id"] = locale_id; uint32_t locale_id2; std::memcpy(&locale_id2, ptr + offset, 4); offset += 4; properties["header"]["locale_id2"] = locale_id2; uint32_t varflags; std::memcpy(&varflags, ptr + offset, 4); offset += 4; properties["header"]["varflags"] = varflags; uint32_t version; std::memcpy(&version, ptr + offset, 4); offset += 4; properties["header"]["version"] = version; uint32_t flags; std::memcpy(&flags, ptr + offset, 4); offset += 4; properties["header"]["flags"] = flags; uint32_t typeinfo_count; std::memcpy(&typeinfo_count, ptr + offset, 4); offset += 4; properties["header"]["typeinfo_count"] = typeinfo_count; int32_t help_string; std::memcpy(&help_string, ptr + offset, 4); offset += 4; properties["header"]["help_string"] = help_string; uint32_t help_string_context; std::memcpy(&help_string_context, ptr + offset, 4); offset += 4; properties["header"]["help_string_context"] = help_string_context; uint32_t help_context; std::memcpy(&help_context, ptr + offset, 4); offset += 4; properties["header"]["help_context"] = help_context; uint32_t name_table_count; std::memcpy(&name_table_count, ptr + offset, 4); offset += 4; properties["header"]["name_table_count"] = name_table_count; uint32_t name_table_chars; std::memcpy(&name_table_chars, ptr + offset, 4); offset += 4; properties["header"]["name_table_chars"] = name_table_chars; int32_t typelib_name; std::memcpy(&typelib_name, ptr + offset, 4); offset += 4; properties["header"]["typelib_name"] = typelib_name; int32_t help_file_name; std::memcpy(&help_file_name, ptr + offset, 4); offset += 4; properties["header"]["help_file_name"] = help_file_name; int32_t custom_data; std::memcpy(&custom_data, ptr + offset, 4); offset += 4; properties["header"]["custom_data"] = custom_data; uint32_t reserved1; std::memcpy(&reserved1, ptr + offset, 4); offset += 4; properties["header"]["reserved1"] = reserved1; uint32_t reserved2; std::memcpy(&reserved2, ptr + offset, 4); offset += 4; properties["header"]["reserved2"] = reserved2; int32_t dispatch_position; std::memcpy(&dispatch_position, ptr + offset, 4); offset += 4; properties["header"]["dispatch_position"] = dispatch_position; uint32_t importinfo_count; std::memcpy(&importinfo_count, ptr + offset, 4); offset += 4; properties["header"]["importinfo_count"] = importinfo_count; if (varflags & 0x100) { int32_t typelib_file_name; std::memcpy(&typelib_file_name, ptr + offset, 4); offset += 4; properties["header"]["typelib_file_name"] = typelib_file_name; } // Additional decoding abbreviated for other sections. } void printProperties() { std::cout << "TLB Properties:" << std::endl; for (const auto& section : properties) { std::cout << section.first << ":" << std::endl; for (const auto& prop : section.second) { std::cout << " " << prop.first << ": " << prop.second << std::endl; } } } void write(const std::string& outputFilename) { if (data.empty()) { throw std::runtime_error("No data to write."); } std::ofstream file(outputFilename, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); } }; int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "Usage: " << argv[0] << " " << std::endl; return 1; } try { TLBParser parser(argv[1]); parser.read(); parser.decode(); parser.printProperties(); parser.write("output.tlb"); } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } // ===== end task-731 .TLB ===== // ===== task-732 .TLZ [C] ===== #include #include #include #include #include #include // For CRC32 #include #include #include #include #include typedef struct { char* filename; } TLZHandler; TLZHandler* tlz_new(const char* filename) { TLZHandler* self = malloc(sizeof(TLZHandler)); self->filename = strdup(filename); return self; } void tlz_free(TLZHandler* self) { free(self->filename); free(self); } uint32_t compute_dict_size(uint8_t ds) { uint32_t base = 1 << (ds & 0x1F); uint32_t subtract = (base / 16) * (ds >> 5); return base - subtract; } void read_and_print_properties(TLZHandler* self) { FILE* f = fopen(self->filename, "rb"); if (!f) { perror("File open error"); return; } fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); if (memcmp(data, "LZIP", 4) != 0) { printf("Not a valid LZIP file\n"); free(data); return; } uint8_t version = data[4]; if (version != 1) { printf("Unsupported LZIP version\n"); free(data); return; } uint8_t ds = data[5]; uint32_t dict_size = compute_dict_size(ds); size_t trailer_offset = size - 20; uint8_t* compressed = data + 6; size_t compressed_size = trailer_offset - 6; lzma_filter filters[2] = { { .id = LZMA_FILTER_LZMA1, .options = &(lzma_lzma1_options){.dict_size = dict_size, .lc = 3, .lp = 0, .pb = 2} }, { .id = LZMA_VLI_UNKNOWN } }; lzma_stream_flags stream_flags = {0}; lzma_block block = { .filters = filters, .check = LZMA_CHECK_CRC32 }; uint8_t* decompressed = NULL; size_t decompressed_size = 0; // Simplified decompression (use lzma_block_decode if needed) lzma_stream strm = LZMA_STREAM_INIT; if (lzma_raw_decoder(&strm, filters) != LZMA_OK) { printf("Decoder init error\n"); free(data); return; } strm.next_in = compressed; strm.avail_in = compressed_size; uint8_t outbuf[8192]; strm.next_out = outbuf; strm.avail_out = sizeof(outbuf); lzma_ret ret; ByteArrayOutputStream-like, but append to decompressed // For brevity, assume small file, adjust for large do { ret = lzma_code(&strm, LZMA_FINISH); if (ret == LZMA_STREAM_END) break; if (ret != LZMA_OK) { printf("Decompression error\n"); lzma_end(&strm); free(data); return; } // Append to decompressed (simplified, use dynamic buffer in practice) } while (1); lzma_end(&strm); // Assume decompressed is filled // Validate trailer... // Parse TAR (simplified ustar parser) size_t pos = 0; while (pos < decompressed_size) { uint8_t* header = decompressed + pos; char name[100]; strncpy(name, (char*)header, 100); name[99] = '\0'; if (strlen(name) == 0) break; char prefix[155]; strncpy(prefix, (char*)(header + 345), 155); prefix[154] = '\0'; char full_name[256]; snprintf(full_name, 256, "%s%s%s", prefix, prefix[0] ? "/" : "", name); unsigned mode = strtol((char*)(header + 100), NULL, 8); unsigned uid = strtol((char*)(header + 108), NULL, 8); unsigned gid = strtol((char*)(header + 116), NULL, 8); unsigned long size = strtol((char*)(header + 124), NULL, 8); unsigned long mtime = strtol((char*)(header + 136), NULL, 8); unsigned chksum = strtol((char*)(header + 148), NULL, 8); char typeflag = header[156]; char linkname[100]; strncpy(linkname, (char*)(header + 157), 100); linkname[99] = '\0'; char uname[32]; strncpy(uname, (char*)(header + 265), 32); uname[31] = '\0'; char gname[32]; strncpy(gname, (char*)(header + 297), 32); gname[31] = '\0'; unsigned devmajor = strtol((char*)(header + 329), NULL, 8); unsigned devminor = strtol((char*)(header + 337), NULL, 8); printf("File: %s\n", full_name); printf(" Permissions (mode): %o\n", mode); printf(" UID: %u\n", uid); printf(" GID: %u\n", gid); printf(" Size: %lu\n", size); printf(" Mtime: %lu\n", mtime); printf(" Checksum: %u\n", chksum); printf(" Type flag: %c\n", typeflag); printf(" Link name: %s\n", linkname); printf(" Owner name: %s\n", uname); printf(" Group name: %s\n", gname); printf(" Dev major: %u\n", devmajor); printf(" Dev minor: %u\n", devminor); printf(" Prefix: %s\n", prefix); printf("---\n"); pos += 512 + ((size + 511) / 512) * 512; } free(decompressed); // Assume allocated free(data); } void write(TLZHandler* self, const char* source_dir, const char* output_filename) { // Simplified: Use system("tar cf temp.tar source_dir"); then compress temp.tar // For production, implement TAR creation // Then lzma_encode... // Omitted detailed implementation for brevity, similar to Python/Java printf("Write functionality stubbed.\n"); } // ===== end task-732 .TLZ ===== // ===== task-733 .TMP [C++] ===== #include #include #include #include #include #include #include namespace fs = std::filesystem; class TmpFileHandler { private: std::string filepath; std::map properties; public: TmpFileHandler(const std::string& filepath) : filepath(filepath) {} void readProperties() { if (!fs::exists(filepath) || filepath.substr(filepath.find_last_of(".") + 1) != "tmp") { throw std::invalid_argument("Invalid .TMP file path."); } struct stat st; if (stat(filepath.c_str(), &st) == 0) { properties["File Extension"] = ".tmp"; properties["MIME Type"] = "application/octet-stream"; properties["Size"] = std::to_string(st.st_size); properties["Creation Timestamp"] = std::ctime(&st.st_ctime); properties["Modification Timestamp"] = std::ctime(&st.st_mtime); properties["Access Timestamp"] = std::ctime(&st.st_atime); properties["Owner UID"] = std::to_string(st.st_uid); properties["Group GID"] = std::to_string(st.st_gid); properties["Permissions"] = std::to_string(st.st_mode & 0777); } } void printProperties() { for (const auto& [key, value] : properties) { std::cout << key << ": " << value << std::endl; } } void writeNewTmp(const std::string& content = "") { std::string newPath = fs::temp_directory_path() / ("example" + std::to_string(time(nullptr)) + ".tmp"); std::ofstream out(newPath); out << content; out.close(); filepath = newPath; std::cout << "New .TMP file created at: " << newPath << std::endl; } }; // Example usage: // int main() { // try { // TmpFileHandler handler("path/to/example.tmp"); // handler.readProperties(); // handler.printProperties(); // handler.writeNewTmp("Sample content"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-733 .TMP ===== // ===== task-734 .TORRENT [C++] ===== #include #include #include #include #include #include #include #include using Variant = std::variant, std::map>; class TorrentFile { private: std::map data; Variant bdecode(const std::string& bytes, size_t& pos) { char c = bytes[pos]; if (c == 'd') { pos++; std::map dict; while (bytes[pos] != 'e') { std::string key = std::get(bdecode(bytes, pos)); Variant val = bdecode(bytes, pos); dict[key] = val; } pos++; return dict; } else if (c == 'l') { pos++; std::vector list; while (bytes[pos] != 'e') { list.push_back(bdecode(bytes, pos)); } pos++; return list; } else if (c == 'i') { pos++; long long num = 0; int sign = 1; if (bytes[pos] == '-') { sign = -1; pos++; } while (bytes[pos] != 'e') { num = num * 10 + (bytes[pos] - '0'); pos++; } pos++; return num * sign; } else { size_t len = 0; while (bytes[pos] != ':') { len = len * 10 + (bytes[pos] - '0'); pos++; } pos++; std::string str = bytes.substr(pos, len); pos += len; return str; } } std::string bencode(const Variant& obj) { struct Visitor { std::string operator()(long long i) { return "i" + std::to_string(i) + "e"; } std::string operator()(const std::string& s) { return std::to_string(s.size()) + ":" + s; } std::string operator()(const std::vector& l) { std::string enc = "l"; for (const auto& item : l) enc += bencode(item); return enc + "e"; } std::string operator()(const std::map& d) { std::string enc = "d"; std::vector keys; for (const auto& p : d) keys.push_back(p.first); std::sort(keys.begin(), keys.end()); for (const auto& key : keys) enc += bencode(key) + bencode(d.at(key)); return enc + "e"; } }; return std::visit(Visitor{}, obj); } public: TorrentFile(const std::string& filepath = "") { if (!filepath.empty()) load(filepath); } void load(const std::string& filepath) { std::ifstream file(filepath, std::ios::binary); std::string bytes((std::istreambuf_iterator(file)), std::istreambuf_iterator()); size_t pos = 0; data = std::get>(bdecode(bytes, pos)); } void save(const std::string& filepath) { std::ofstream file(filepath, std::ios::binary); file << bencode(data); } void printProperties() { struct PrintVisitor { std::string indent; void operator()(long long i) { std::cout << i << std::endl; } void operator()(const std::string& s) { std::cout << s << std::endl; } void operator()(const std::vector& l) { std::cout << "list" << std::endl; for (size_t i = 0; i < l.size(); ++i) { std::cout << indent << " [" << i << "]: "; std::visit(PrintVisitor{indent + " "}, l[i]); } } void operator()(const std::map& d) { std::cout << "dictionary" << std::endl; for (const auto& p : d) { std::cout << indent << p.first << ": "; std::visit(PrintVisitor{indent + " "}, p.second); } } }; std::visit(PrintVisitor{""}, data); } }; // Example usage: // int main() { // TorrentFile t("example.torrent"); // t.printProperties(); // t.save("output.torrent"); // return 0; // } // ===== end task-734 .TORRENT ===== // ===== task-735 .TQL [C++] ===== #include #include #include #include #include #include class TQLFileHandler { private: std::string filepath; std::string content; public: TQLFileHandler(const std::string& fp) : filepath(fp) {} std::string openAndRead() { std::ifstream file(filepath); if (file) { content.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); } return content; } void printProperties() { struct stat st; if (stat(filepath.c_str(), &st) == 0) { std::cout << "File name: " << filepath.substr(filepath.find_last_of("/\\") + 1) << std::endl; std::cout << "File path: " << filepath << std::endl; std::cout << "File size (in bytes): " << st.st_size << std::endl; std::cout << "Creation time: " << std::ctime(&st.st_ctime); std::cout << "Last modification time: " << std::ctime(&st.st_mtime); std::cout << "Last access time: " << std::ctime(&st.st_atime); std::cout << "Owner user ID (UID): " << st.st_uid << std::endl; std::cout << "Owner group ID (GID): " << st.st_gid << std::endl; std::cout << "File permissions (mode): " << std::oct << st.st_mode << std::endl; } else { std::cerr << "Error retrieving properties." << std::endl; } } void writeExample(const std::string& newFilepath) { std::ofstream file(newFilepath); if (file) { file << R"( CREATE SOURCE ExampleSource USING FileReader ( directory: 'data', wildcard: '*.csv' ) OUTPUT TO ExampleStream; )"; file.close(); std::cout << "Example .TQL file written to " << newFilepath << std::endl; } } }; // Example usage: // int main() { // TQLFileHandler handler("example.tql"); // handler.openAndRead(); // handler.printProperties(); // handler.writeExample("new_example.tql"); // return 0; // } // ===== end task-735 .TQL ===== // ===== task-736 .TS [C++] ===== #include #include #include #include class TSFileHandler { private: static constexpr int PACKET_SIZE = 188; std::string filepath; public: TSFileHandler(const std::string& filepath) : filepath(filepath) {} void readAndDecode() { std::ifstream file(filepath, std::ios::binary); if (!file) { std::cout << "File " << filepath << " does not exist." << std::endl; return; } std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); size_t offset = 0; int packetCount = 0; while (offset + PACKET_SIZE <= data.size() && packetCount < 10) { if (data[offset] != 0x47) { std::cout << "Invalid sync byte at offset " << offset << ". Stopping." << std::endl; break; } uint8_t byte1 = data[offset + 1]; uint8_t byte2 = data[offset + 2]; uint8_t byte3 = data[offset + 3]; int transportError = (byte1 >> 7) & 1; int payloadStart = (byte1 >> 6) & 1; int transportPriority = (byte1 >> 5) & 1; int pid = ((byte1 & 0x1F) << 8) | byte2; int scrambling = (byte3 >> 6) & 3; int adaptationControl = (byte3 >> 4) & 3; int continuity = byte3 & 0xF; int adaptationLength = 0; if (adaptationControl == 2 || adaptationControl == 3) { adaptationLength = data[offset + 4]; } std::cout << "Packet " << (packetCount + 1) << ":" << std::endl; std::cout << "- Packet Size: " << PACKET_SIZE << " bytes" << std::endl; std::cout << "- Sync Byte: 0x47" << std::endl; std::cout << "- Transport Error Indicator: " << transportError << std::endl; std::cout << "- Payload Unit Start Indicator: " << payloadStart << std::endl; std::cout << "- Transport Priority: " << transportPriority << std::endl; std::cout << "- PID: " << pid << std::endl; std::cout << "- Transport Scrambling Control: " << scrambling << std::endl; std::cout << "- Adaptation Field Control: " << adaptationControl << std::endl; std::cout << "- Continuity Counter: " << continuity << std::endl; std::cout << "- Adaptation Field Length: " << adaptationLength << std::endl; std::cout << std::endl; offset += PACKET_SIZE; packetCount++; } } void writeSample(const std::string& outputPath, int numPackets = 5) { std::ofstream file(outputPath, std::ios::binary); if (!file) { std::cout << "Cannot open output file " << outputPath << "." << std::endl; return; } for (int i = 0; i < numPackets; ++i) { file.put(0x47); file.put(0x1F); file.put(0xFF); file.put(0x10); for (int j = 4; j < PACKET_SIZE; ++j) { file.put(0xFF); } } std::cout << "Sample .TS file written to " << outputPath << " with " << numPackets << " null packets." << std::endl; } }; // Example usage: // int main() { // TSFileHandler handler("sample.ts"); // handler.readAndDecode(); // handler.writeSample("output.ts"); // return 0; // } // ===== end task-736 .TS ===== // ===== task-737 .TSCN [C++] ===== #include #include #include #include #include #include #include class TSCNHandler { private: std::vector> sections; public: void openAndDecode(const std::string& filepath) { std::ifstream file(filepath); std::stringstream content; content << file.rdbuf(); sections = parse(content.str()); } std::vector> parse(const std::string& content) { std::vector> sectionsList; std::istringstream iss(content); std::string line; std::map currentSection; std::regex sectionRegex(R"(\[(\w+)(.*)\])"); std::regex kvRegex(R"((\w+)=([^ ]+))"); while (std::getline(iss, line)) { line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); if (line.empty() || line[0] == ';') continue; std::smatch sectionMatch; if (std::regex_match(line, sectionMatch, sectionRegex)) { if (!currentSection.empty()) sectionsList.push_back(currentSection); currentSection.clear(); currentSection["type"] = sectionMatch[1].str(); std::string propsStr = sectionMatch[2].str(); std::sregex_iterator iter(propsStr.begin(), propsStr.end(), kvRegex); for (; iter != std::sregex_iterator(); ++iter) { currentSection[(*iter)[1].str()] = (*iter)[2].str(); } } else if (!currentSection.empty()) { size_t eqPos = line.find('='); if (eqPos != std::string::npos) { std::string key = line.substr(0, eqPos); key.erase(key.find_last_not_of(" \t") + 1); std::string value = line.substr(eqPos + 1); value.erase(0, value.find_first_not_of(" \t")); currentSection[key] = value; } } } if (!currentSection.empty()) sectionsList.push_back(currentSection); return sectionsList; } void printProperties() { for (const auto& section : sections) { std::cout << "Section type: " << section.at("type") << std::endl; for (const auto& kv : section) { if (kv.first != "type") { std::cout << " " << kv.first << ": " << kv.second << std::endl; } } std::cout << std::endl; } } void write(const std::string& filepath) { std::ofstream file(filepath); for (const auto& section : sections) { file << "[" << section.at("type"); for (const auto& kv : section) { if (kv.first != "type") { file << " " << kv.first << "=\"" << kv.second << "\""; } } file << "]\n"; } } }; // Example usage: // int main() { // TSCNHandler handler; // handler.openAndDecode("example.tscn"); // handler.printProperties(); // handler.write("output.tscn"); // return 0; // } // ===== end task-737 .TSCN ===== // ===== task-738 .TSV [C++] ===== #include #include #include #include #include #include #include class TsvHandler { private: std::string filename; std::vector> data; public: TsvHandler(const std::string& fn) : filename(fn) {} void read() { std::ifstream file(filename); if (!file) return; data.clear(); std::string line; while (std::getline(file, line)) { if (line.empty()) continue; std::vector row; std::stringstream ss(line); std::string field; while (std::getline(ss, field, '\t')) { row.push_back(field); } data.push_back(row); } } void write() { std::ofstream file(filename); if (!file) return; for (const auto& row : data) { for (size_t i = 0; i < row.size(); ++i) { file << row[i]; if (i < row.size() - 1) file << '\t'; } file << '\n'; } } void printProperties() { struct stat st; if (stat(filename.c_str(), &st) == 0) { std::cout << "Device ID: " << st.st_dev << std::endl; std::cout << "Inode number: " << st.st_ino << std::endl; std::cout << "File mode: " << std::oct << st.st_mode << std::endl; std::cout << "Number of hard links: " << st.st_nlink << std::endl; std::cout << "User ID: " << st.st_uid << std::endl; std::cout << "Group ID: " << st.st_gid << std::endl; std::cout << "Special device ID: " << st.st_rdev << std::endl; std::cout << "File size: " << st.st_size << std::endl; std::cout << "Block size: " << st.st_blksize << std::endl; std::cout << "Number of blocks: " << st.st_blocks << std::endl; std::cout << "Access time: " << st.st_atime << std::endl; std::cout << "Modification time: " << st.st_mtime << std::endl; std::cout << "Change time: " << st.st_ctime << std::endl; } else { std::cerr << "Error retrieving file properties." << std::endl; } } }; // ===== end task-738 .TSV ===== // ===== task-739 .TTC [C++] ===== #include #include #include #include #include #include // For byte order conversion if needed; assume big-endian. class TTCFileHandler { private: std::string filepath; char ttcTag[5]; uint16_t majorVersion; uint16_t minorVersion; uint32_t numFonts; std::vector tableOffsets; uint32_t dsigTag; uint32_t dsigLength; uint32_t dsigOffset; public: TTCFileHandler(const std::string& filepath) : filepath(filepath) { ttcTag[4] = '\0'; decode(); } void decode() { std::ifstream file(filepath, std::ios::binary); if (!file) { throw std::runtime_error("Unable to open file."); } file.read(ttcTag, 4); file.read(reinterpret_cast(&majorVersion), sizeof(uint16_t)); majorVersion = be16toh(majorVersion); // Convert if little-endian system. file.read(reinterpret_cast(&minorVersion), sizeof(uint16_t)); minorVersion = be16toh(minorVersion); file.read(reinterpret_cast(&numFonts), sizeof(uint32_t)); numFonts = be32toh(numFonts); tableOffsets.resize(numFonts); for (auto& offset : tableOffsets) { file.read(reinterpret_cast(&offset), sizeof(uint32_t)); offset = be32toh(offset); } if (majorVersion == 2) { file.read(reinterpret_cast(&dsigTag), sizeof(uint32_t)); dsigTag = be32toh(dsigTag); file.read(reinterpret_cast(&dsigLength), sizeof(uint32_t)); dsigLength = be32toh(dsigLength); file.read(reinterpret_cast(&dsigOffset), sizeof(uint32_t)); dsigOffset = be32toh(dsigOffset); } } void printProperties() const { std::cout << "TTC Tag: " << ttcTag << std::endl; std::cout << "Major Version: " << majorVersion << std::endl; std::cout << "Minor Version: " << minorVersion << std::endl; std::cout << "Number of Fonts: " << numFonts << std::endl; std::cout << "Table Directory Offsets: ["; for (size_t i = 0; i < tableOffsets.size(); ++i) { std::cout << tableOffsets[i] << (i < tableOffsets.size() - 1 ? ", " : ""); } std::cout << "]" << std::endl; if (majorVersion == 2) { std::string dsigTagStr = (dsigTag != 0) ? "DSIG" : "null"; std::cout << "DSIG Tag: " << dsigTagStr << std::endl; std::cout << "DSIG Length: " << dsigLength << std::endl; std::cout << "DSIG Offset: " << dsigOffset << std::endl; } } void write(const std::string& outputPath) const { std::ofstream file(outputPath, std::ios::binary); if (!file) { throw std::runtime_error("Unable to write file."); } file.write(ttcTag, 4); uint16_t beMajor = htobe16(majorVersion); file.write(reinterpret_cast(&beMajor), sizeof(uint16_t)); uint16_t beMinor = htobe16(minorVersion); file.write(reinterpret_cast(&beMinor), sizeof(uint16_t)); uint32_t beNum = htobe32(numFonts); file.write(reinterpret_cast(&beNum), sizeof(uint32_t)); for (const auto& offset : tableOffsets) { uint32_t beOffset = htobe32(offset); file.write(reinterpret_cast(&beOffset), sizeof(uint32_t)); } if (majorVersion == 2) { uint32_t beDsigTag = htobe32(dsigTag); file.write(reinterpret_cast(&beDsigTag), sizeof(uint32_t)); uint32_t beDsigLen = htobe32(dsigLength); file.write(reinterpret_cast(&beDsigLen), sizeof(uint32_t)); uint32_t beDsigOff = htobe32(dsigOffset); file.write(reinterpret_cast(&beDsigOff), sizeof(uint32_t)); } // Note: This writes only the header; full writing requires table data. } }; // Example usage: // int main() { // try { // TTCFileHandler handler("example.ttc"); // handler.printProperties(); // handler.write("output.ttc"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-739 .TTC ===== // ===== task-740 .TTF [C++] ===== #include #include #include #include #include #include struct TableEntry { std::string tag; uint32_t checksum; uint32_t offset; uint32_t length; }; class TTFHandler { private: std::string filepath; uint32_t scaler_type; uint16_t num_tables; uint16_t search_range; uint16_t entry_selector; uint16_t range_shift; std::vector tables; std::vector data; public: TTFHandler(const std::string& fp) : filepath(fp), scaler_type(0), num_tables(0), search_range(0), entry_selector(0), range_shift(0) {} void read() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) throw std::runtime_error("Cannot open file"); size_t size = file.tellg(); data.resize(size); file.seekg(0); file.read(data.data(), size); if (size < 12) throw std::runtime_error("Invalid .TTF file: too short"); memcpy(&scaler_type, data.data(), 4); memcpy(&num_tables, data.data() + 4, 2); memcpy(&search_range, data.data() + 6, 2); memcpy(&entry_selector, data.data() + 8, 2); memcpy(&range_shift, data.data() + 10, 2); // Swap if little-endian host (assuming big-endian file) scaler_type = __builtin_bswap32(scaler_type); num_tables = __builtin_bswap16(num_tables); search_range = __builtin_bswap16(search_range); entry_selector = __builtin_bswap16(entry_selector); range_shift = __builtin_bswap16(range_shift); size_t pos = 12; tables.resize(num_tables); for (uint16_t i = 0; i < num_tables; ++i) { if (pos + 16 > size) throw std::runtime_error("Invalid .TTF file: incomplete directory"); char tag_buf[5] = {0}; memcpy(tag_buf, data.data() + pos, 4); tables[i].tag = std::string(tag_buf).substr(0, strnlen(tag_buf, 4)); memcpy(&tables[i].checksum, data.data() + pos + 4, 4); memcpy(&tables[i].offset, data.data() + pos + 8, 4); memcpy(&tables[i].length, data.data() + pos + 12, 4); tables[i].checksum = __builtin_bswap32(tables[i].checksum); tables[i].offset = __builtin_bswap32(tables[i].offset); tables[i].length = __builtin_bswap32(tables[i].length); pos += 16; } } void printProperties() const { std::cout << "Scaler Type: 0x" << std::hex << std::setw(8) << std::setfill('0') << scaler_type << std::dec << std::endl; std::cout << "Number of Tables: " << num_tables << std::endl; std::cout << "Search Range: " << search_range << std::endl; std::cout << "Entry Selector: " << entry_selector << std::endl; std::cout << "Range Shift: " << range_shift << std::endl; std::cout << "\nTable Directory:" << std::endl; for (size_t i = 0; i < tables.size(); ++i) { std::cout << "Table " << (i + 1) << ":" << std::endl; std::cout << " Tag: " << tables[i].tag << std::endl; std::cout << " Checksum: 0x" << std::hex << std::setw(8) << std::setfill('0') << tables[i].checksum << std::dec << std::endl; std::cout << " Offset: " << tables[i].offset << std::endl; std::cout << " Length: " << tables[i].length << std::endl; } } void write(const std::string& output_filepath) { if (data.empty()) throw std::runtime_error("File not read yet"); // Example modification: increment first table checksum if (!tables.empty()) { tables[0].checksum += 1; size_t pos = 12; for (const auto& table : tables) { uint32_t be_checksum = __builtin_bswap32(table.checksum); uint32_t be_offset = __builtin_bswap32(table.offset); uint32_t be_length = __builtin_bswap32(table.length); char tag_buf[4]; strncpy(tag_buf, table.tag.c_str(), 4); for (size_t j = table.tag.size(); j < 4; ++j) tag_buf[j] = ' '; memcpy(data.data() + pos, tag_buf, 4); memcpy(data.data() + pos + 4, &be_checksum, 4); memcpy(data.data() + pos + 8, &be_offset, 4); memcpy(data.data() + pos + 12, &be_length, 4); pos += 16; } } std::ofstream out(output_filepath, std::ios::binary); if (!out) throw std::runtime_error("Cannot write file"); out.write(data.data(), data.size()); } }; // Example usage: // int main() { // try { // TTFHandler handler("example.ttf"); // handler.read(); // handler.printProperties(); // handler.write("modified.ttf"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-740 .TTF ===== // ===== task-743 .TXZ [C++] ===== #include #include #include #include #include #include class TXZHandler { private: std::string filepath; std::vector> properties; public: TXZHandler(const std::string& fp) : filepath(fp) {} void openAndRead() { // Decompress XZ lzma_stream strm = LZMA_STREAM_INIT; lzma_ret ret = lzma_stream_decoder(&strm, UINT64_MAX, 0); if (ret != LZMA_OK) return; std::ifstream in(filepath, std::ios::binary); std::vector input((std::istreambuf_iterator(in)), std::istreambuf_iterator()); std::vector output(1024 * 1024); // Buffer for decompressed strm.next_in = input.data(); strm.avail_in = input.size(); strm.next_out = output.data(); strm.avail_out = output.size(); ret = lzma_code(&strm, LZMA_FINISH); lzma_end(&strm); if (ret != LZMA_STREAM_END) return; // Parse TAR from output[0..strm.total_out] TAR *t; if (tar_open(&t, nullptr, nullptr, O_RDONLY, 0, TAR_GNU) == -1) return; // Set buffer to decompressed data tar_append_tree(t, const char* rootdir, const char* path); // Pseudo, use memory buffer // For each entry, extract properties // Implementation similar to above, populating properties tar_close(t); } void printProperties() { for (const auto& props : properties) { for (const auto& p : props) { std::cout << p.first << ": " << p.second << std::endl; } std::cout << std::endl; } } void write(const std::string& newFilepath) { // Implementation for writing TAR and compressing with XZ // Use tar_open for write, add files, then compress the TAR output with lzma } }; // Example usage: int main() { TXZHandler handler("example.txz"); handler.openAndRead(); handler.printProperties(); return 0; } // ===== end task-743 .TXZ ===== // ===== task-744 .TZ2 [C] ===== #include #include #include #include #include #include #include #include #include #define BLOCK_SIZE 512 #define MAGIC "ustar" typedef struct { char name[100]; char mode[8]; char uid[8]; char gid[8]; char size[12]; char mtime[12]; char checksum[8]; char typeflag; char linkname[100]; char magic[6]; char version[2]; char uname[32]; char gname[32]; char devmajor[8]; char devminor[8]; char prefix[155]; char pad[12]; } TarHeader; typedef struct { char *filepath; } TZ2Handler; void initTZ2Handler(TZ2Handler *handler, char *filepath) { handler->filepath = strdup(filepath); } void readTZ2(TZ2Handler *handler) { FILE *f = fopen(handler->filepath, "rb"); if (!f) return; bzFile *bz = BZ2_bzopen(handler->filepath, "rb"); // Use libbz2 if (!bz) return; char buffer[BLOCK_SIZE]; while (BZ2_bzread(bz, buffer, BLOCK_SIZE) == BLOCK_SIZE) { TarHeader *header = (TarHeader *)buffer; if (header->name[0] == 0) break; // Parse and print properties printf("Name: %s\nMode: %s\nUID: %s\n...", header->name, header->mode, header->uid); // Abbreviated long size = strtol(header->size, NULL, 8); long blocks = (size + BLOCK_SIZE - 1) / BLOCK_SIZE; for (long i = 0; i < blocks; i++) BZ2_bzread(bz, buffer, BLOCK_SIZE); } BZ2_bzclose(bz); fclose(f); } void writeTZ2(TZ2Handler *handler, char *directory, char *outputPath) { // Implement TAR creation, then bzip2 compression using BZ2_bzWrite // Omitted for brevity; similar to read but in reverse. } void freeTZ2Handler(TZ2Handler *handler) { free(handler->filepath); } // Example usage: // TZ2Handler handler; // initTZ2Handler(&handler, "example.tz2"); // readTZ2(&handler); // writeTZ2(&handler, "source_dir", "new.tz2"); // freeTZ2Handler(&handler); // ===== end task-744 .TZ2 ===== // ===== task-745 .TZST [C++] ===== #include #include #include #include #include #include #include class TZSTHandler { private: std::string filepath; std::vector> properties_list; public: TZSTHandler(const std::string& fp) : filepath(fp) {} std::vector> read_and_print() { std::ifstream file(filepath, std::ios::binary); if (!file) return {}; file.seekg(0, std::ios::end); size_t compressed_size = file.tellg(); file.seekg(0); std::vector compressed(compressed_size); file.read(compressed.data(), compressed_size); size_t const decompressed_size = ZSTD_findDecompressedSize(compressed.data(), compressed_size); std::vector decompressed(decompressed_size); size_t const dSize = ZSTD_decompress(decompressed.data(), decompressed_size, compressed.data(), compressed_size); if (ZSTD_isError(dSize)) { std::cerr << "Decompression error: " << ZSTD_getErrorName(dSize) << std::endl; return {}; } size_t offset = 0; while (offset < dSize) { if (decompressed[offset] == 0) break; std::map props; props["name"] = get_string(decompressed, offset, 100); props["mode"] = std::to_string(get_octal(decompressed, offset + 100, 8)); props["uid"] = std::to_string(get_octal(decompressed, offset + 108, 8)); props["gid"] = std::to_string(get_octal(decompressed, offset + 116, 8)); props["size"] = std::to_string(get_octal(decompressed, offset + 124, 12)); props["mtime"] = std::to_string(get_octal(decompressed, offset + 136, 12)); props["checksum"] = std::to_string(get_octal(decompressed, offset + 148, 8)); props["typeflag"] = std::string(1, decompressed[offset + 156]); props["linkname"] = get_string(decompressed, offset + 157, 100); props["magic"] = get_string(decompressed, offset + 257, 6); props["version"] = get_string(decompressed, offset + 263, 2); props["uname"] = get_string(decompressed, offset + 265, 32); props["gname"] = get_string(decompressed, offset + 297, 32); props["devmajor"] = std::to_string(get_octal(decompressed, offset + 329, 8)); props["devminor"] = std::to_string(get_octal(decompressed, offset + 337, 8)); props["prefix"] = get_string(decompressed, offset + 345, 155); properties_list.push_back(props); // Print for (const auto& p : props) { std::cout << p.first << ": " << p.second << std::endl; } std::cout << std::endl; size_t file_size = std::stoul(props["size"]); offset += 512 + ((file_size + 511) / 512) * 512; } return properties_list; } void write(const std::string& output_path, const std::vector& files_to_add) { std::vector tar_data; for (const auto& file_path : files_to_add) { struct stat st; if (stat(file_path.c_str(), &st) != 0) continue; std::vector header(512, 0); set_string(header, 0, file_path.substr(file_path.find_last_of('/') + 1), 100); set_octal(header, 100, st.st_mode & 0777, 8); set_octal(header, 108, st.st_uid, 8); set_octal(header, 116, st.st_gid, 8); set_octal(header, 124, st.st_size, 12); set_octal(header, 136, st.st_mtime, 12); set_string(header, 157, "", 100); // linkname header[156] = '0'; // typeflag normal file set_string(header, 257, "ustar", 6); set_string(header, 263, "00", 2); set_string(header, 265, "user", 32); set_string(header, 297, "group", 32); // Checksum unsigned chksum = 8 * ' '; for (size_t i = 0; i < 512; ++i) if (i < 148 || i >= 156) chksum += static_cast(header[i]); set_octal(header, 148, chksum, 8); std::ifstream file_data(file_path, std::ios::binary); file_data.seekg(0, std::ios::end); size_t fsize = file_data.tellg(); file_data.seekg(0); std::vector fdata(fsize); file_data.read(fdata.data(), fsize); size_t padded = ((fsize + 511) / 512) * 512; std::vector padded_data(padded, 0); std::copy(fdata.begin(), fdata.end(), padded_data.begin()); tar_data.insert(tar_data.end(), header.begin(), header.end()); tar_data.insert(tar_data.end(), padded_data.begin(), padded_data.end()); } // Add two zero blocks std::vector zero(1024, 0); tar_data.insert(tar_data.end(), zero.begin(), zero.end()); size_t cbuf_size = ZSTD_compressBound(tar_data.size()); std::vector compressed(cbuf_size); size_t cSize = ZSTD_compress(compressed.data(), cbuf_size, tar_data.data(), tar_data.size(), 3); if (ZSTD_isError(cSize)) { std::cerr << "Compression error: " << ZSTD_getErrorName(cSize) << std::endl; return; } std::ofstream out(output_path, std::ios::binary); out.write(compressed.data(), cSize); } private: std::string get_string(const std::vector& buf, size_t off, size_t len) { std::string s(buf.begin() + off, buf.begin() + off + len); s.erase(std::find(s.begin(), s.end(), '\0'), s.end()); return s; } unsigned long get_octal(const std::vector& buf, size_t off, size_t len) { std::string s(buf.begin() + off, buf.begin() + off + len); s.erase(std::find(s.begin(), s.end(), '\0'), s.end()); return std::stoul(s, nullptr, 8); } void set_string(std::vector& buf, size_t off, const std::string& str, size_t len) { size_t copy_len = std::min(str.size(), len - 1); std::copy(str.begin(), str.begin() + copy_len, buf.begin() + off); buf[off + copy_len] = '\0'; } void set_octal(std::vector& buf, size_t off, unsigned long val, size_t len) { char oct[32]; snprintf(oct, sizeof(oct), "%0*lo", static_cast(len - 1), val); std::copy(oct, oct + len - 1, buf.begin() + off); buf[off + len - 1] = '\0'; } }; // ===== end task-745 .TZST ===== // ===== task-746 .UI [C++] ===== #include #include #include "tinyxml2.h" // Assume TinyXML-2 library is included using namespace tinyxml2; class UIFileHandler { private: std::string filepath; XMLDocument doc; public: UIFileHandler(const std::string& filepath) : filepath(filepath) { load(); } void load() { if (doc.LoadFile(filepath.c_str()) != XML_SUCCESS) { std::cout << "Error loading file: " << doc.ErrorStr() << std::endl; exit(1); } XMLElement* root = doc.FirstChildElement("ui"); if (!root) { std::cout << "Invalid .UI file." << std::endl; exit(1); } } void printProperties() { std::cout << "Properties:" << std::endl; XMLElement* root = doc.FirstChildElement("ui"); // Version std::cout << "Version: " << (root->Attribute("version") ? root->Attribute("version") : "N/A") << std::endl; // Language std::cout << "Language: " << (root->Attribute("language") ? root->Attribute("language") : "N/A") << std::endl; // Display Name std::cout << "Display Name: " << (root->Attribute("displayname") ? root->Attribute("displayname") : "N/A") << std::endl; // ID-Based Translation std::cout << "ID-Based Translation: " << (root->Attribute("idbasedtr") ? root->Attribute("idbasedtr") : "N/A") << std::endl; // Connect Slots by Name std::cout << "Connect Slots by Name: " << (root->Attribute("connectslotsbyname") ? root->Attribute("connectslotsbyname") : "N/A") << std::endl; // Standard Set Default (Legacy) std::cout << "stdsetdef: " << (root->Attribute("stdsetdef") ? root->Attribute("stdsetdef") : "N/A") << std::endl; std::cout << "stdSetDef: " << (root->Attribute("stdSetDef") ? root->Attribute("stdSetDef") : "N/A") << std::endl; // Author std::cout << "Author: " << getTextContent(root, "author") << std::endl; // Comment std::cout << "Comment: " << getTextContent(root, "comment") << std::endl; // Export Macro std::cout << "Export Macro: " << getTextContent(root, "exportmacro") << std::endl; // Class Name std::cout << "Class Name: " << getTextContent(root, "class") << std::endl; // Root Widget XMLElement* widget = root->FirstChildElement("widget"); std::string widgetClass = widget ? (widget->Attribute("class") ? widget->Attribute("class") : "N/A") : "N/A"; std::string widgetName = widget ? (widget->Attribute("name") ? widget->Attribute("name") : "N/A") : "N/A"; std::cout << "Root Widget: Class - " << widgetClass << ", Name - " << widgetName << std::endl; // Layout Default XMLElement* layoutDefault = root->FirstChildElement("layoutdefault"); std::string spacing = layoutDefault ? (layoutDefault->Attribute("spacing") ? layoutDefault->Attribute("spacing") : "N/A") : "N/A"; std::string margin = layoutDefault ? (layoutDefault->Attribute("margin") ? layoutDefault->Attribute("margin") : "N/A") : "N/A"; std::cout << "Layout Default: Spacing - " << spacing << ", Margin - " << margin << std::endl; // Layout Function XMLElement* layoutFunction = root->FirstChildElement("layoutfunction"); std::string funcSpacing = layoutFunction ? (layoutFunction->Attribute("spacing") ? layoutFunction->Attribute("spacing") : "N/A") : "N/A"; std::string funcMargin = layoutFunction ? (layoutFunction->Attribute("margin") ? layoutFunction->Attribute("margin") : "N/A") : "N/A"; std::cout << "Layout Function: Spacing - " << funcSpacing << ", Margin - " << funcMargin << std::endl; // Pixmap Function std::cout << "Pixmap Function: " << getTextContent(root, "pixmapfunction") << std::endl; // Custom Widgets std::cout << "Custom Widgets:" << std::endl; XMLElement* customWidgets = root->FirstChildElement("customwidgets"); if (customWidgets) { XMLElement* cw = customWidgets->FirstChildElement("customwidget"); int i = 1; while (cw) { std::cout << " " << i << ". Class: " << getTextContent(cw, "class") << ", Extends: " << getTextContent(cw, "extends") << std::endl; cw = cw->NextSiblingElement("customwidget"); i++; } } else { std::cout << " N/A" << std::endl; } // Tab Stops std::cout << "Tab Stops:" << std::endl; XMLElement* tabStops = root->FirstChildElement("tabstops"); if (tabStops) { XMLElement* ts = tabStops->FirstChildElement("tabstop"); int i = 1; while (ts) { std::cout << " " << i << ". " << (ts->GetText() ? ts->GetText() : "N/A") << std::endl; ts = ts->NextSiblingElement("tabstop"); i++; } } else { std::cout << " N/A" << std::endl; } // Includes std::cout << "Includes:" << std::endl; XMLElement* includes = root->FirstChildElement("includes"); if (includes) { XMLElement* inc = includes->FirstChildElement("include"); int i = 1; while (inc) { std::cout << " " << i << ". Location: " << (inc->Attribute("location") ? inc->Attribute("location") : "N/A") << std::endl; inc = inc->NextSiblingElement("include"); i++; } } else { std::cout << " N/A" << std::endl; } // Resources std::cout << "Resources:" << std::endl; XMLElement* resources = root->FirstChildElement("resources"); if (resources) { XMLElement* res = resources->FirstChildElement("include"); // Note: under int i = 1; while (res) { std::cout << " " << i << ". Location: " << (res->Attribute("location") ? res->Attribute("location") : "N/A") << std::endl; res = res->NextSiblingElement("include"); i++; } } else { std::cout << " N/A" << std::endl; } // Connections std::cout << "Connections:" << std::endl; XMLElement* connections = root->FirstChildElement("connections"); if (connections) { XMLElement* conn = connections->FirstChildElement("connection"); int i = 1; while (conn) { std::cout << " " << i << ". Sender: " << getTextContent(conn, "sender") << ", Signal: " << getTextContent(conn, "signal") << ", Receiver: " << getTextContent(conn, "receiver") << ", Slot: " << getTextContent(conn, "slot") << std::endl; conn = conn->NextSiblingElement("connection"); i++; } } else { std::cout << " N/A" << std::endl; } // Designer Data XMLElement* designerData = root->FirstChildElement("designerdata"); std::cout << "Designer Data: " << (designerData ? "Present" : "N/A") << std::endl; // Slots std::cout << "Slots:" << std::endl; XMLElement* slotsElem = root->FirstChildElement("slots"); if (slotsElem) { XMLElement* sig = slotsElem->FirstChildElement("signal"); int i = 1; while (sig) { std::cout << " Signal " << i << ": " << (sig->GetText() ? sig->GetText() : "N/A") << std::endl; sig = sig->NextSiblingElement("signal"); i++; } XMLElement* slt = slotsElem->FirstChildElement("slot"); i = 1; while (slt) { std::cout << " Slot " << i << ": " << (slt->GetText() ? slt->GetText() : "N/A") << std::endl; slt = slt->NextSiblingElement("slot"); i++; } } else { std::cout << " N/A" << std::endl; } // Button Groups std::cout << "Button Groups:" << std::endl; XMLElement* buttonGroups = root->FirstChildElement("buttongroups"); if (buttonGroups) { XMLElement* bg = buttonGroups->FirstChildElement("buttongroup"); int i = 1; while (bg) { std::cout << " " << i << ". Name: " << (bg->Attribute("name") ? bg->Attribute("name") : "N/A") << std::endl; bg = bg->NextSiblingElement("buttongroup"); i++; } } else { std::cout << " N/A" << std::endl; } } std::string getTextContent(XMLElement* parent, const char* tag) { XMLElement* elem = parent->FirstChildElement(tag); return elem && elem->GetText() ? elem->GetText() : "N/A"; } void write(const std::string& outputPath = "") { std::string path = outputPath.empty() ? filepath : outputPath; if (doc.SaveFile(path.c_str()) != XML_SUCCESS) { std::cout << "Error writing file: " << doc.ErrorStr() << std::endl; } else { std::cout << "File written to " << path << std::endl; } } }; // Example usage: // int main() { // UIFileHandler handler("example.ui"); // handler.printProperties(); // handler.write("modified.ui"); // return 0; // } // ===== end task-746 .UI ===== // ===== task-747 .UMP [C++] ===== #include #include #include #include #include class UMPHandler { private: std::string filepath; std::string content; struct Properties { std::vector classes; std::vector> attributes; std::vector> associations; std::vector> other_directives; } properties; public: UMPHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath); std::string line; content.clear(); while (std::getline(file, line)) { content += line + "\n"; } file.close(); } void decode() { if (content.empty()) { read(); } std::regex classRegex("class\\s+(\\w+)\\s*\\{"); std::regex attrRegex("(\\w+)\\s+(\\w+);"); std::regex assocRegex("(\\d+)\\s+--\\s+(\\d+)\\s+(\\w+);"); std::regex dirRegex("(use|namespace|generate)\\s+([^;]+);"); std::smatch match; std::string::const_iterator searchStart(content.cbegin()); while (std::regex_search(searchStart, content.cend(), match, classRegex)) { properties.classes.push_back(match[1]); searchStart = match.suffix().first; } searchStart = content.cbegin(); while (std::regex_search(searchStart, content.cend(), match, attrRegex)) { properties.attributes.push_back({match[1], match[2]}); searchStart = match.suffix().first; } searchStart = content.cbegin(); while (std::regex_search(searchStart, content.cend(), match, assocRegex)) { properties.associations.push_back({match[1], match[2], match[3]}); searchStart = match.suffix().first; } searchStart = content.cbegin(); while (std::regex_search(searchStart, content.cend(), match, dirRegex)) { properties.other_directives.push_back({match[1], match[2]}); searchStart = match.suffix().first; } } void printProperties() { if (properties.classes.empty() && properties.attributes.empty()) { decode(); } std::cout << "Classes: "; for (const auto& cls : properties.classes) std::cout << cls << " "; std::cout << std::endl; std::cout << "Attributes: "; for (const auto& attr : properties.attributes) std::cout << "(" << attr[0] << ", " << attr[1] << ") "; std::cout << std::endl; std::cout << "Associations: "; for (const auto& assoc : properties.associations) std::cout << "(" << assoc[0] << ", " << assoc[1] << ", " << assoc[2] << ") "; std::cout << std::endl; std::cout << "Other Directives: "; for (const auto& dir : properties.other_directives) std::cout << "(" << dir[0] << ", " << dir[1] << ") "; std::cout << std::endl; } void write(const std::string& newFilepath = "") { std::string outPath = newFilepath.empty() ? filepath : newFilepath; std::ofstream file(outPath); file << content; file.close(); } }; // Example usage: // int main() { // UMPHandler handler("example.ump"); // handler.printProperties(); // return 0; // } // ===== end task-747 .UMP ===== // ===== task-748 .UNV [C] ===== #include #include #include #include #define MAX_LINE 256 #define MAX_DATASETS 100 typedef struct { int type; void* fields; // Use union or struct per type for fields } Dataset; typedef struct { char* filepath; Dataset datasets[MAX_DATASETS]; int num_datasets; } UnvFile; UnvFile* unv_create(const char* filepath) { UnvFile* unv = malloc(sizeof(UnvFile)); unv->filepath = strdup(filepath); unv->num_datasets = 0; return unv; } void unv_read(UnvFile* unv) { FILE* fp = fopen(unv->filepath, "r"); if (!fp) return; char line[MAX_LINE]; int i = 0; while (fgets(line, MAX_LINE, fp)) { char trimmed[MAX_LINE]; strcpy(trimmed, line); // Trim whitespace char* p = trimmed; while (isspace(*p)) p++; char* end = p + strlen(p) - 1; while (end > p && isspace(*end)) end--; *(end + 1) = '\0'; if (strcmp(p, "-1") == 0) { fgets(line, MAX_LINE, fp); int type = atoi(line); Dataset ds; ds.type = type; ds.fields = NULL; // Parse fields here // Simplified: allocate and parse based on type if (type == 2411) { // Parse nodes // Allocate list of nodes } unv->datasets[unv->num_datasets++] = ds; } } fclose(fp); } void unv_write(UnvFile* unv, const char* output_path) { FILE* fp = fopen(output_path, "w"); if (!fp) return; for (int j = 0; j < unv->num_datasets; j++) { fprintf(fp, " -1\n"); fprintf(fp, "%6d\n", unv->datasets[j].type); // Write fields based on type fprintf(fp, " -1\n"); } fclose(fp); } void unv_print_properties(UnvFile* unv) { for (int j = 0; j < unv->num_datasets; j++) { printf("Dataset Type: %d\n", unv->datasets[j].type); printf("Fields: (implement printing per type)\n\n"); } } void unv_destroy(UnvFile* unv) { free(unv->filepath); // Free fields free(unv); } // Example usage: UnvFile* unv = unv_create("example.unv"); unv_read(unv); unv_print_properties(unv); unv_write(unv, "output.unv"); unv_destroy(unv); // ===== end task-748 .UNV ===== // ===== task-749 .UOS [C++] ===== #include #include #include #include #include #include #include class UOSHandler { private: std::string filename; std::string mimetype; std::string rootElement; std::map rootAttributes; std::vector files; public: UOSHandler(const std::string& fn) : filename(fn) {} int read() { zip_t* z = zip_open(filename.c_str(), ZIP_RDONLY, nullptr); if (!z) return 1; zip_int64_t numEntries = zip_get_num_entries(z, 0); for (zip_int64_t i = 0; i < numEntries; ++i) { const char* name = zip_get_name(z, i, 0); if (name) files.push_back(name); } zip_file_t* mimetypeFile = zip_fopen(z, "mimetype", 0); if (mimetypeFile) { char buf[1024]; zip_int64_t len = zip_fread(mimetypeFile, buf, sizeof(buf) - 1); if (len > 0) { buf[len] = '\0'; mimetype = buf; } zip_fclose(mimetypeFile); } zip_file_t* documentFile = zip_fopen(z, "Object 1/document.xml", 0); if (documentFile) { std::string xmlContent; char buf[1024]; zip_int64_t len; while ((len = zip_fread(documentFile, buf, sizeof(buf))) > 0) { xmlContent.append(buf, len); } zip_fclose(documentFile); xmlDocPtr doc = xmlParseMemory(xmlContent.c_str(), xmlContent.size()); if (doc) { xmlNodePtr root = xmlDocGetRootElement(doc); if (root) { rootElement = reinterpret_cast(root->name); for (xmlAttrPtr attr = root->properties; attr; attr = attr->next) { std::string name = reinterpret_cast(attr->name); std::string value = reinterpret_cast(attr->children->content); rootAttributes[name] = value; } } xmlFreeDoc(doc); } } zip_close(z); return 0; } int write(const std::string& outputFilename) { zip_t* z = zip_open(outputFilename.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); if (!z) return 1; zip_source_t* src = zip_source_buffer(z, mimetype.c_str(), mimetype.size(), 0); zip_file_add(z, "mimetype", src, ZIP_FL_ENC_UTF_8); std::string xmlContent = ""; src = zip_source_buffer(z, xmlContent.c_str(), xmlContent.size(), 0); zip_file_add(z, "Object 1/document.xml", src, ZIP_FL_ENC_UTF_8); std::string manifest = ""; src = zip_source_buffer(z, manifest.c_str(), manifest.size(), 0); zip_file_add(z, "META-INF/manifest.xml", src, ZIP_FL_ENC_UTF_8); zip_close(z); return 0; } void printProperties() { std::cout << "Properties:" << std::endl; std::cout << "Files:" << std::endl; for (const auto& f : files) std::cout << f << std::endl; std::cout << "Mimetype: " << mimetype << std::endl; std::cout << "Root Element: " << rootElement << std::endl; std::cout << "Root Attributes:" << std::endl; for (const auto& attr : rootAttributes) { std::cout << attr.first << ": " << attr.second << std::endl; } } }; // Example usage: // int main() { // UOSHandler handler("example.uos"); // handler.read(); // handler.printProperties(); // handler.write("new.uos"); // return 0; // } // ===== end task-749 .UOS ===== // ===== task-750 .UOT [C++] ===== #include #include #include #include #include class UOTFile { private: std::string filename; std::map properties; const char* ns = "uof"; // Prefix; tinyxml2 doesn't support NS directly public: UOTFile(const std::string& fn) : filename(fn) {} void read() { zip_t* z = zip_open(filename.c_str(), ZIP_RDONLY, nullptr); if (z) { int index = zip_name_locate(z, "metadata.xml", 0); if (index >= 0) { zip_file_t* f = zip_fopen_index(z, index, 0); struct zip_stat st; zip_stat_index(z, index, 0, &st); char* contents = new char[st.size + 1]; zip_fread(f, contents, st.size); contents[st.size] = '\0'; zip_fclose(f); tinyxml2::XMLDocument doc; doc.Parse(contents); // Extract; example for Title (assume prefixed tags like uof:title) tinyxml2::XMLElement* title = doc.FirstChildElement("uof:metadata")->FirstChildElement("uof:title"); properties["Title"] = title ? title->GetText() : "Not found"; // Add similar for other properties delete[] contents; } zip_close(z); } } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& newFilename) { // Similar to read, but modify and write new ZIP // Implementation omitted for brevity; copy files, modify metadata.xml } }; // Example usage: // UOTFile uot("example.uot"); // uot.read(); // uot.printProperties(); // uot.write("modified.uot"); // ===== end task-750 .UOT ===== // ===== task-751 .UPD [C] ===== #include #include #include #include #include #include #include #include typedef struct { char *filepath; } UPDFileHandler; UPDFileHandler* createUPDFileHandler(const char *filepath) { UPDFileHandler *handler = malloc(sizeof(UPDFileHandler)); handler->filepath = strdup(filepath); const char *ext = strrchr(filepath, '.'); if (!ext || strcasecmp(ext, ".upd") != 0) { fprintf(stderr, "File must have .upd extension.\n"); free(handler->filepath); free(handler); return NULL; } struct stat st; if (stat(filepath, &st) != 0) { fprintf(stderr, "File does not exist.\n"); free(handler->filepath); free(handler); return NULL; } return handler; } void destroyUPDFileHandler(UPDFileHandler *handler) { free(handler->filepath); free(handler); } void printProperties(UPDFileHandler *handler) { struct stat st; if (stat(handler->filepath, &st) != 0) { fprintf(stderr, "Error reading file stats.\n"); return; } struct passwd *pwd = getpwuid(st.st_uid); struct group *grp = getgrgid(st.st_gid); char perm[10]; snprintf(perm, 10, "%o", st.st_mode & 0777); printf("File name: %s\n", handler->filepath); printf("File size (bytes): %ld\n", st.st_size); printf("Creation time: %s", ctime(&st.st_ctime)); printf("Last modification time: %s", ctime(&st.st_mtime)); printf("Last access time: %s", ctime(&st.st_atime)); printf("File attributes: %o\n", st.st_mode); printf("Owner: %s\n", pwd ? pwd->pw_name : "Unknown"); printf("Group: %s\n", grp ? grp->gr_name : "Unknown"); printf("Permissions: %s\n", perm); } int writeProperty(UPDFileHandler *handler, const char *propertyName, time_t value) { if (strcmp(propertyName, "Last modification time") == 0) { struct utimbuf ut; struct stat st; stat(handler->filepath, &st); ut.actime = st.st_atime; ut.modtime = value; return utime(handler->filepath, &ut); } fprintf(stderr, "Writing %s not supported.\n", propertyName); return -1; } // Example usage: // int main() { // UPDFileHandler *handler = createUPDFileHandler("example.upd"); // if (handler) { // printProperties(handler); // writeProperty(handler, "Last modification time", time(NULL)); // destroyUPDFileHandler(handler); // } // return 0; // } // ===== end task-751 .UPD ===== // ===== task-752 .UPS [C++] ===== #include #include #include #include #include // For CRC32 struct Hunk { uint64_t offset; std::vector xorData; // Including terminating 0 }; class UPSFile { private: std::string magic = "UPS1"; uint64_t sourceSize = 0; uint64_t targetSize = 0; std::vector hunks; uint32_t sourceCRC = 0; uint32_t targetCRC = 0; uint32_t patchCRC = 0; uint64_t readVLE(std::ifstream& file) { uint64_t value = 0; int shift = 0; while (true) { uint8_t byte; file.read(reinterpret_cast(&byte), 1); if (byte & 0x80) { value += static_cast(byte & 0x7F) << shift; break; } value += static_cast(byte | 0x80) << shift; shift += 7; } return value; } void writeVLE(std::ofstream& file, uint64_t value) { while (true) { uint8_t byte = static_cast(value & 0x7F); value >>= 7; if (value == 0) { file.write(reinterpret_cast(& (uint8_t)(byte | 0x80)), 1); break; } file.write(reinterpret_cast(&byte), 1); value--; } } public: void openAndDecode(const std::string& filename) { std::ifstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file"); } char magicBuf[5] = {0}; file.read(magicBuf, 4); magic = magicBuf; if (magic != "UPS1") { throw std::runtime_error("Invalid UPS file"); } sourceSize = readVLE(file); targetSize = readVLE(file); hunks.clear(); file.seekg(0, std::ios::end); size_t fileSize = file.tellg(); file.seekg(file.tellg() - (std::streampos)12, std::ios::beg); // Position before CRCs size_t endPos = file.tellg(); file.seekg(4 + (magic.size() + sizeof(sourceSize) + sizeof(targetSize)), std::ios::beg); // Approximate, but reset properly file.seekg(4, std::ios::beg); // Reset to after magic sourceSize = readVLE(file); targetSize = readVLE(file); size_t pos = file.tellg(); while (pos < endPos) { uint64_t offset = readVLE(file); std::vector xorData; uint8_t byte; do { file.read(reinterpret_cast(&byte), 1); xorData.push_back(byte); pos = file.tellg(); } while (byte != 0 && pos < endPos); hunks.push_back({offset, xorData}); } file.read(reinterpret_cast(&sourceCRC), 4); file.read(reinterpret_cast(&targetCRC), 4); file.read(reinterpret_cast(&patchCRC), 4); } void printProperties() const { std::cout << "Magic Number: " << magic << std::endl; std::cout << "Source File Size: " << sourceSize << std::endl; std::cout << "Target File Size: " << targetSize << std::endl; std::cout << "Patch Hunks:" << std::endl; for (size_t i = 0; i < hunks.size(); ++i) { const auto& hunk = hunks[i]; std::cout << " Hunk " << i << ":" << std::endl; std::cout << " Relative Offset: " << hunk.offset << std::endl; std::cout << " XOR Data (hex): "; for (uint8_t b : hunk.xorData) { std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast(b) << " "; } std::cout << std::dec << std::endl; } std::cout << "Source CRC32: 0x" << std::hex << std::uppercase << std::setw(8) << std::setfill('0') << sourceCRC << std::endl; std::cout << "Target CRC32: 0x" << std::hex << std::uppercase << std::setw(8) << std::setfill('0') << targetCRC << std::endl; std::cout << "Patch CRC32: 0x" << std::hex << std::uppercase << std::setw(8) << std::setfill('0') << patchCRC << std::dec << std::endl; } void write(const std::string& filename) { std::ofstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file for writing"); } file.write(magic.c_str(), 4); writeVLE(file, sourceSize); writeVLE(file, targetSize); for (const auto& hunk : hunks) { writeVLE(file, hunk.offset); file.write(reinterpret_cast(hunk.xorData.data()), hunk.xorData.size()); } file.write(reinterpret_cast(&sourceCRC), 4); file.write(reinterpret_cast(&targetCRC), 4); // Compute patch CRC file.seekp(0, std::ios::end); size_t sizeWithoutCRC = file.tellp(); std::vector tempData(sizeWithoutCRC); file.seekp(0, std::ios::beg); file.read(reinterpret_cast(tempData.data()), sizeWithoutCRC); patchCRC = crc32(0L, tempData.data(), sizeWithoutCRC); file.write(reinterpret_cast(&patchCRC), 4); } }; // ===== end task-752 .UPS ===== // ===== task-753 .URL [C++] ===== #include #include #include #include #include class URLFile { private: std::string filename; std::map properties; public: URLFile(const std::string& fn) : filename(fn) { std::ifstream file(fn); if (!file) { std::cerr << "Error opening file." << std::endl; return; } std::string line; bool inSection = false; while (std::getline(file, line)) { line.erase(std::remove_if(line.begin(), line.end(), isspace), line.end()); if (line == "[InternetShortcut]") { inSection = true; } else if (inSection && line.find('=') != std::string::npos) { size_t pos = line.find('='); std::string key = line.substr(0, pos); std::string value = line.substr(pos + 1); properties[key] = value; } } file.close(); } void printProperties() { std::string propsList[7] = {"URL", "WorkingDirectory", "IconIndex", "IconFile", "Modified", "ShowCommand", "HotKey"}; for (int i = 0; i < 7; ++i) { auto it = properties.find(propsList[i]); std::string value = (it != properties.end()) ? it->second : "Not present"; std::cout << propsList[i] << ": " << value << std::endl; } } void setProperty(const std::string& key, const std::string& value) { properties[key] = value; } void write(const std::string& fn = "") { std::string outFile = fn.empty() ? filename : fn; std::ofstream file(outFile); if (!file) { std::cerr << "Error writing file." << std::endl; return; } file << "[InternetShortcut]" << std::endl; for (const auto& pair : properties) { file << pair.first << "=" << pair.second << std::endl; } file.close(); } }; // ===== end task-753 .URL ===== // ===== task-754 .USDZ [C++] ===== #include #include #include #include #include class USDZHandler { private: std::string filepath; std::string archiveFormat = "Uncompressed, unencrypted ZIP archive"; std::string mimeType = "model/vnd.usdz+zip"; std::string fileExtension = ".usdz"; std::vector alignment; std::vector allowedFileTypes = {".usd", ".usda", ".usdc", ".png", ".jpeg", ".jpg", ".exr", ".avif", ".m4a", ".mp3", ".wav"}; bool defaultLayer; std::string pathConventions = "Forward slashes, UTF-8"; std::vector compression; std::string encryption = "None"; std::string metadata = "Optional in default layer"; public: USDZHandler(const std::string& filepath) : filepath(filepath) {} void readAndPrintProperties() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { std::cerr << "Failed to open file." << std::endl; return; } size_t size = file.tellg(); file.seekg(0); std::vector buffer(size); file.read(buffer.data(), size); // Basic ZIP parsing size_t offset = size - 22; while (offset > 0) { uint32_t sig; memcpy(&sig, &buffer[offset], 4); if (sig == 0x06054b50) { // EOCD uint16_t numEntries; memcpy(&numEntries, &buffer[offset + 10], 2); uint32_t cdOffset; memcpy(&cdOffset, &buffer[offset + 16], 4); std::vector> entries; size_t currentOffset = cdOffset; for (uint16_t i = 0; i < numEntries; ++i) { memcpy(&sig, &buffer[currentOffset], 4); if (sig != 0x02014b50) break; uint16_t compMethod; memcpy(&compMethod, &buffer[currentOffset + 10], 2); compression.push_back(compMethod == 0); uint16_t nameLen; memcpy(&nameLen, &buffer[currentOffset + 28], 2); uint16_t extraLen; memcpy(&extraLen, &buffer[currentOffset + 30], 2); uint16_t commentLen; memcpy(&commentLen, &buffer[currentOffset + 32], 2); uint32_t localOffset; memcpy(&localOffset, &buffer[currentOffset + 42], 4); std::string name(&buffer[currentOffset + 46], nameLen); entries.emplace_back(name, localOffset); alignment.push_back(localOffset % 64 == 0); currentOffset += 46 + nameLen + extraLen + commentLen; } if (!entries.empty()) { size_t dotPos = entries[0].first.find_last_of('.'); std::string ext = (dotPos != std::string::npos) ? entries[0].first.substr(dotPos) : ""; std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); defaultLayer = (ext == ".usd" || ext == ".usda" || ext == ".usdc"); } break; } --offset; } std::cout << "Properties:" << std::endl; std::cout << "Archive Format: " << archiveFormat << std::endl; std::cout << "MIME Type: " << mimeType << std::endl; std::cout << "File Extension: " << fileExtension << std::endl; std::cout << "Alignment: "; for (bool a : alignment) std::cout << a << " "; std::cout << std::endl; std::cout << "Allowed File Types: "; for (const auto& t : allowedFileTypes) std::cout << t << " "; std::cout << std::endl; std::cout << "Default Layer: " << defaultLayer << std::endl; std::cout << "Path Conventions: " << pathConventions << std::endl; std::cout << "Compression: "; for (bool c : compression) std::cout << c << " "; std::cout << std::endl; std::cout << "Encryption: " << encryption << std::endl; std::cout << "Metadata: " << metadata << std::endl; } void writeSampleUsdz(const std::string& outputPath) { std::ofstream out(outputPath, std::ios::binary); if (!out) { std::cerr << "Failed to create file." << std::endl; return; } // Simple ZIP structure for sample // Local header for sample.usda const char localHeader[] = {0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00}; // Placeholder out.write(localHeader, sizeof(localHeader)); out.write("sample.usda", 11); std::string content = "#usda 1.0\n"; out.write(content.c_str(), content.size()); // Add more entries as needed // Central directory and EOCD would be added similarly std::cout << "Wrote sample USDZ to " << outputPath << std::endl; } }; // Example usage: // int main() { // USDZHandler handler("example.usdz"); // handler.readAndPrintProperties(); // handler.writeSampleUsdz("new.usdz"); // return 0; // } // ===== end task-754 .USDZ ===== // ===== task-755 .UST [C++] ===== #include #include #include #include #include #include class USTFile { private: std::string filepath; std::map settings; std::vector> notes; public: USTFile(const std::string& fp) : filepath(fp) { read(); } void read() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "File not found: " << filepath << std::endl; return; } std::string line; std::string currentSection; std::map currentNote; while (std::getline(file, line)) { line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); if (line == "[#VERSION]") { currentSection = "version"; } else if (line == "[#SETTING]") { currentSection = "settings"; } else if (line.rfind("[#", 0) == 0 && line.back() == ']') { if (!currentNote.empty()) { notes.push_back(currentNote); currentNote.clear(); } currentNote["section"] = line; currentSection = "note"; } else if (line == "[#TRACKEND]") { if (!currentNote.empty()) { notes.push_back(currentNote); } currentSection = ""; } else if (line.find('=') != std::string::npos && !currentSection.empty()) { std::istringstream iss(line); std::string key, value; std::getline(iss, key, '='); std::getline(iss, value); if (currentSection == "settings") { settings[key] = value; } else if (currentSection == "note") { currentNote[key] = value; } } } file.close(); } void printProperties() const { std::cout << "Settings:" << std::endl; for (const auto& pair : settings) { std::cout << pair.first << ": " << pair.second << std::endl; } std::cout << "\nNotes:" << std::endl; for (const auto& note : notes) { std::cout << "Section: " << note.at("section") << std::endl; for (const auto& pair : note) { if (pair.first != "section") { std::cout << " " << pair.first << ": " << pair.second << std::endl; } } std::cout << "---" << std::endl; } } void write(const std::string& newFilepath = "") const { std::string outPath = newFilepath.empty() ? filepath : newFilepath; std::ofstream file(outPath); if (!file.is_open()) { std::cerr << "Error writing to file: " << outPath << std::endl; return; } file << "[#VERSION]" << std::endl << "UST1.2" << std::endl; file << "[#SETTING]" << std::endl; for (const auto& pair : settings) { file << pair.first << "=" << pair.second << std::endl; } for (const auto& note : notes) { file << note.at("section") << std::endl; for (const auto& pair : note) { if (pair.first != "section") { file << pair.first << "=" << pair.second << std::endl; } } } file << "[#TRACKEND]" << std::endl; file.close(); } }; // Example usage: // int main() { // USTFile ust("example.ust"); // ust.printProperties(); // ust.write("new.ust"); // return 0; // } // ===== end task-755 .UST ===== // ===== task-756 .USTX [C++] ===== #include #include #include #include #include class USTX { private: YAML::Node data; public: USTX(const std::string& path) { data = YAML::LoadFile(path); } void printProperties() { std::vector properties = { "version", "name", "comment", "outputDir", "cacheDir", "bpm", "beatPerBar", "beatUnit", "resolution", "modes", "expressions", "tempos", "timeSignatures", "tracks", "voiceParts", "waveParts" }; for (const auto& prop : properties) { if (data[prop]) { std::cout << prop << ": " << data[prop] << std::endl; } else { std::cout << prop << ": Not found" << std::endl; } } } void write(const std::string& path) { std::ofstream fout(path); fout << data; fout.close(); } }; // ===== end task-756 .USTX ===== // ===== task-758 .UXF [C++] ===== #include #include #include "tinyxml2.h" class UXFHandler { private: std::string filename; tinyxml2::XMLDocument doc; public: UXFHandler(const std::string& fn) : filename(fn) { read(); } void read() { if (doc.LoadFile(filename.c_str()) != tinyxml2::XML_SUCCESS) { std::cerr << "Error reading file." << std::endl; } } void printProperties() { tinyxml2::XMLElement* root = doc.FirstChildElement("diagram"); if (!root) { std::cout << "Invalid root element." << std::endl; return; } tinyxml2::XMLElement* elem = root->FirstChildElement("element"); int count = 1; while (elem) { std::cout << "Element " << count << " (id: " << elem->Attribute("id") << "):" << std::endl; const tinyxml2::XMLAttribute* attr = elem->FirstAttribute(); while (attr) { std::cout << " " << attr->Name() << ": " << attr->Value() << std::endl; attr = attr->Next(); } const char* text = elem->GetText(); if (text && std::string(text).find_first_not_of(" \t\n\r") != std::string::npos) { std::cout << " Text Content: " << text << std::endl; } std::cout << std::endl; elem = elem->NextSiblingElement("element"); ++count; } } void write(const std::string& newFilename = "") { std::string outFile = newFilename.empty() ? filename : newFilename; if (doc.SaveFile(outFile.c_str()) != tinyxml2::XML_SUCCESS) { std::cerr << "Error writing file." << std::endl; } } void addElement(const std::map& attributes, const std::string& text = "") { tinyxml2::XMLElement* root = doc.FirstChildElement("diagram"); if (!root) return; tinyxml2::XMLElement* newElem = doc.NewElement("element"); for (const auto& pair : attributes) { newElem->SetAttribute(pair.first.c_str(), pair.second.c_str()); } if (!text.empty()) { newElem->SetText(text.c_str()); } root->InsertEndChild(newElem); } }; // ===== end task-758 .UXF ===== // ===== task-759 .V [C] ===== #include #include #include #include #include typedef struct { char* filepath; uint8_t* data; size_t size; size_t offset; int version; // Simplified: use maps or arrays for sections/dynamic; here use placeholders int section_count; // Example property int dynamic_count; // Example property } VFile; bool read_file(VFile* vf, const char* filepath) { FILE* f = fopen(filepath, "rb"); if (!f) return false; fseek(f, 0, SEEK_END); vf->size = ftell(f); fseek(f, 0, SEEK_SET); vf->data = malloc(vf->size); fread(vf->data, 1, vf->size, f); fclose(f); vf->filepath = strdup(filepath); vf->offset = 0; return true; } uint8_t read_byte(VFile* vf) { return vf->data[vf->offset++]; } int16_t read_short(VFile* vf) { int16_t val = *(int16_t*)(vf->data + vf->offset); vf->offset += 2; return val; } int32_t read_long(VFile* vf) { int32_t val = *(int32_t*)(vf->data + vf->offset); vf->offset += 4; return val; } float read_float(VFile* vf) { float val = *(float*)(vf->data + vf->offset); vf->offset += 4; return val; } double read_double(VFile* vf) { double val = *(double*)(vf->data + vf->offset); vf->offset += 8; return val; } char* read_string(VFile* vf, int len) { char* str = malloc(len + 1); memcpy(str, vf->data + vf->offset, len); str[len] = '\0'; for (int i = 0; i < len; i++) if (str[i] == 0) str[i] = '\0'; vf->offset += len; return str; } void parse_header(VFile* vf) { uint8_t id1 = read_byte(vf); uint8_t id2 = read_byte(vf); vf->version = read_short(vf); if (id1 != 0x56 || id2 != 0x23) { fprintf(stderr, "Invalid .V file\n"); exit(1); } } void parse_static_sections(VFile* vf) { int sections = 0; while (true) { int32_t length = read_long(vf); char* id = read_string(vf, 28); size_t pos = vf->offset; if (length == 0 && strlen(id) == 0) { free(id); break; } // Parse records (simplified count) while (true) { int16_t rec_len = read_short(vf); if (rec_len == 0) break; vf->offset += rec_len; } sections++; free(id); vf->offset = pos + length; } vf->section_count = sections; } void parse_dynamic(VFile* vf) { int count = 0; while (vf->offset < vf->size) { int16_t len = read_short(vf); if (len == 0) break; // Safety read_short(vf); // groupId read_long(vf); // frameNum vf->offset += len - 6; count++; } vf->dynamic_count = count; } void parse(VFile* vf) { parse_header(vf); parse_static_sections(vf); parse_dynamic(vf); } void print_properties(VFile* vf) { printf("Properties:\n"); printf("Version: %d\n", vf->version); printf("Section Count: %d\n", vf->section_count); printf("Dynamic Count: %d\n", vf->dynamic_count); } void write_file(VFile* vf, const char* new_filepath) { const char* path = new_filepath ? new_filepath : vf->filepath; FILE* f = fopen(path, "wb"); fwrite(vf->data, 1, vf->size, f); fclose(f); } void destroy(VFile* vf) { free(vf->data); free(vf->filepath); } // Example usage: // int main() { // VFile vf; // if (!read_file(&vf, "example.v")) return 1; // parse(&vf); // print_properties(&vf); // write_file(&vf, "modified.v"); // destroy(&vf); // return 0; // } // ===== end task-759 .V ===== // ===== task-760 .V3 [C++] ===== #include #include #include #include // Assume minizip or libzip class V3FileHandler { private: std::string filepath; std::map data; // Simplified; use nested maps for full std::string meta; std::string gamestate; public: V3FileHandler(const std::string& fp) : filepath(fp) {} void open() { // Use libzip to open and read zip_t* z = zip_open(filepath.c_str(), ZIP_RDONLY, nullptr); if (z) { // Read meta and gamestate (simplified) // zip_file_t* f = zip_fopen(z, "meta", 0); // Read into meta // Similar for gamestate zip_close(z); } data = parseGamestate(gamestate); } std::map parseGamestate(const std::string& text) { std::map result; // Parser implementation return result; } void printProperties() { std::string properties[5] = {"provinces", "pops", "states", "laws", "variables"}; for (auto& prop : properties) { auto it = data.find(prop); std::cout << prop << ": " << (it != data.end() ? it->second : "Not found") << std::endl; } } void write(const std::string& newFilepath) { // Use libzip to write } // Unparse method similar }; // Example usage: // int main() { // V3FileHandler handler("example.v3"); // handler.open(); // handler.printProperties(); // handler.write("modified.v3"); // return 0; // } // ===== end task-760 .V3 ===== // ===== task-761 .V4P [C++] ===== #include #include #include "tinyxml2.h" // Assume TinyXML-2 is included using namespace tinyxml2; class V4PHandler { private: std::string filepath; XMLDocument doc; public: V4PHandler(const std::string& filepath) : filepath(filepath) { load(); } void load() { doc.LoadFile(filepath.c_str()); } void printProperties() { XMLElement* root = doc.FirstChildElement("PATCH"); if (!root) { std::cout << "Invalid .V4P file: Root is not PATCH" << std::endl; return; } std::cout << "PATCH Properties:" << std::endl; for (const XMLAttribute* attr = root->FirstAttribute(); attr; attr = attr->Next()) { std::cout << " " << attr->Name() << ": " << attr->Value() << std::endl; } std::cout << "\nNODE Properties:" << std::endl; XMLElement* node = root->FirstChildElement("NODE"); int nodeCount = 1; while (node) { std::cout << " Node " << nodeCount++ << ":" << std::endl; for (const XMLAttribute* attr = node->FirstAttribute(); attr; attr = attr->Next()) { std::cout << " " << attr->Name() << ": " << attr->Value() << std::endl; } node = node->NextSiblingElement("NODE"); } std::cout << "\nPIN Properties:" << std::endl; XMLElement* pin = doc.FirstChildElement()->FirstChildElement("PIN"); int pinCount = 1; while (pin) { std::cout << " Pin " << pinCount++ << ":" << std::endl; for (const XMLAttribute* attr = pin->FirstAttribute(); attr; attr = attr->Next()) { std::cout << " " << attr->Name() << ": " << attr->Value() << std::endl; } pin = pin->NextSiblingElement("PIN"); } std::cout << "\nBOUNDS Properties:" << std::endl; XMLElement* bound = doc.FirstChildElement()->FirstChildElement("BOUNDS"); int boundCount = 1; while (bound) { std::cout << " Bounds " << boundCount++ << ":" << std::endl; for (const XMLAttribute* attr = bound->FirstAttribute(); attr; attr = attr->Next()) { std::cout << " " << attr->Name() << ": " << attr->Value() << std::endl; } bound = bound->NextSiblingElement("BOUNDS"); } std::cout << "\nLINK Properties:" << std::endl; XMLElement* link = root->FirstChildElement("LINK"); int linkCount = 1; while (link) { std::cout << " Link " << linkCount++ << ":" << std::endl; for (const XMLAttribute* attr = link->FirstAttribute(); attr; attr = attr->Next()) { std::cout << " " << attr->Name() << ": " << attr->Value() << std::endl; } link = link->NextSiblingElement("LINK"); } std::cout << "\nWINDOWBOUNDS Properties:" << std::endl; XMLElement* wb = root->FirstChildElement("WINDOWBOUNDS"); int wbCount = 1; while (wb) { std::cout << " WindowBounds " << wbCount++ << ":" << std::endl; for (const XMLAttribute* attr = wb->FirstAttribute(); attr; attr = attr->Next()) { std::cout << " " << attr->Name() << ": " << attr->Value() << std::endl; } wb = wb->NextSiblingElement("WINDOWBOUNDS"); } } void write(const std::string& newFilepath) { doc.SaveFile(newFilepath.c_str()); } }; // Example usage: // int main() { // V4PHandler handler("example.v4p"); // handler.printProperties(); // handler.write("modified.v4p"); // return 0; // } // ===== end task-761 .V4P ===== // ===== task-762 .V64 [C] ===== #include #include #include #include typedef struct { char* filename; uint8_t* data; size_t size; uint8_t* swapped_data; } V64Handler; void v64_read(V64Handler* handler) { FILE* f = fopen(handler->filename, "rb"); if (!f) { perror("Error opening file"); exit(1); } fseek(f, 0, SEEK_END); handler->size = ftell(f); fseek(f, 0, SEEK_SET); handler->data = malloc(handler->size); fread(handler->data, 1, handler->size, f); fclose(f); // Byte-swap to native for (size_t i = 0; i < handler->size; i += 2) { uint8_t temp = handler->data[i]; handler->data[i] = handler->data[i + 1]; handler->data[i + 1] = temp; } handler->swapped_data = handler->data; } void v64_print_properties(V64Handler* handler) { printf("Reserved_0x00: 0x%02X\n", handler->swapped_data[0]); uint32_t flags = (handler->swapped_data[1] << 16) | (handler->swapped_data[2] << 8) | handler->swapped_data[3]; printf("PI_BSD_DOM1_Flags_0x01: 0x%06X\n", flags); uint32_t clock = *(uint32_t*)(handler->swapped_data + 4); printf("Clock_Rate_0x04: 0x%08X\n", __builtin_bswap32(clock)); uint32_t boot = *(uint32_t*)(handler->swapped_data + 8); printf("Boot_Address_0x08: 0x%08X\n", __builtin_bswap32(boot)); uint32_t version = *(uint32_t*)(handler->swapped_data + 12); printf("Libultra_Version_0x0C: 0x%08X\n", __builtin_bswap32(version)); uint64_t check = *(uint64_t*)(handler->swapped_data + 16); printf("Check_Code_0x10: 0x%016llX\n", __builtin_bswap64(check)); uint64_t res1 = *(uint64_t*)(handler->swapped_data + 24); printf("Reserved_0x18: 0x%016llX\n", __builtin_bswap64(res1)); char title[21]; memcpy(title, handler->swapped_data + 32, 20); title[20] = '\0'; printf("Game_Title_0x20: %s\n", title); uint64_t res2 = *(uint64_t*)(handler->swapped_data + 52) >> 8; printf("Reserved_0x34: 0x%014llX\n", __builtin_bswap64(res2 << 8)); char code[5]; memcpy(code, handler->swapped_data + 59, 4); code[4] = '\0'; printf("Game_Code_0x3B: %s\n", code); printf("ROM_Version_0x3F: 0x%02X\n", handler->swapped_data[63]); } void v64_write(V64Handler* handler, const char* output_filename) { uint8_t* output_data = malloc(handler->size); memcpy(output_data, handler->swapped_data, handler->size); for (size_t i = 0; i < handler->size; i += 2) { uint8_t temp = output_data[i]; output_data[i] = output_data[i + 1]; output_data[i + 1] = temp; } FILE* f = fopen(output_filename, "wb"); if (!f) { perror("Error writing file"); exit(1); } fwrite(output_data, 1, handler->size, f); fclose(f); free(output_data); } void v64_free(V64Handler* handler) { free(handler->data); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s input.v64\n", argv[0]); return 1; } V64Handler handler = { .filename = argv[1] }; v64_read(&handler); v64_print_properties(&handler); v64_write(&handler, "output.v64"); v64_free(&handler); return 0; } // ===== end task-762 .V64 ===== // ===== task-763 .VB [C++] ===== #include #include #include #include #include #include #include // For Shift-JIS conversion class VBFileHandler { private: std::string filename; std::vector data; size_t headerOffset; std::map properties; public: VBFileHandler(const std::string& fn) : filename(fn), headerOffset(0) {} void read() { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) { throw std::runtime_error("Unable to open file."); } size_t size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(reinterpret_cast(data.data()), size); headerOffset = size - 32; if (headerOffset >= size) { throw std::runtime_error("File too small to contain header."); } // Decode properties std::string title(reinterpret_cast(&data[headerOffset]), 20); // Convert Shift-JIS to UTF-8 std::wstring_convert> converter; std::wstring wtitle = converter.from_bytes(title); // Assuming Shift-JIS input needs proper decoder; simplify for example title = converter.to_bytes(wtitle); // Placeholder; use proper Shift-JIS library if needed title.erase(std::remove(title.begin(), title.end(), '\0'), title.end()); title = title.substr(0, title.find_last_not_of(' ') + 1); std::stringstream reservedSs; for (size_t i = 0; i < 5; ++i) { reservedSs << std::hex << std::setfill('0') << std::setw(2) << static_cast(data[headerOffset + 20 + i]) << " "; } std::string reserved = reservedSs.str(); reserved = reserved.substr(0, reserved.find_last_not_of(' ')); std::string makerCode(reinterpret_cast(&data[headerOffset + 25]), 2); makerCode = makerCode.substr(0, makerCode.find_last_not_of('\0') + 1); std::string gameCode(reinterpret_cast(&data[headerOffset + 27]), 4); gameCode = gameCode.substr(0, gameCode.find_last_not_of('\0') + 1); unsigned int version = data[headerOffset + 31]; properties["Game Title"] = title; properties["Reserved"] = reserved; properties["Maker Code"] = makerCode; properties["Game Code"] = gameCode; properties["Version"] = std::to_string(version); } void printProperties() const { if (properties.empty()) { throw std::runtime_error("Properties not read yet."); } for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::map& newProperties = {}) { if (data.empty()) { throw std::runtime_error("File not read yet."); } updateProperties(newProperties); std::ofstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Unable to write file."); } file.write(reinterpret_cast(data.data()), data.size()); } private: void updateProperties(const std::map& newProperties) { if (newProperties.find("Game Title") != newProperties.end()) { std::string title = newProperties.at("Game Title"); // Assume simple ASCII for simplicity; use encoder for Shift-JIS title.resize(20, '\0'); std::copy(title.begin(), title.end(), data.begin() + headerOffset); } if (newProperties.find("Reserved") != newProperties.end()) { std::string reservedStr = newProperties.at("Reserved"); std::stringstream ss(reservedStr); unsigned int byte; for (size_t i = 0; i < 5 && ss >> std::hex >> byte; ++i) { data[headerOffset + 20 + i] = static_cast(byte); } } if (newProperties.find("Maker Code") != newProperties.end()) { std::string maker = newProperties.at("Maker Code"); maker.resize(2, '\0'); std::copy(maker.begin(), maker.end(), data.begin() + headerOffset + 25); } if (newProperties.find("Game Code") != newProperties.end()) { std::string gameCode = newProperties.at("Game Code"); gameCode.resize(4, '\0'); std::copy(gameCode.begin(), gameCode.end(), data.begin() + headerOffset + 27); } if (newProperties.find("Version") != newProperties.end()) { unsigned int version = std::stoi(newProperties.at("Version")); data[headerOffset + 31] = static_cast(version); } } }; // Example usage: // int main() { // try { // VBFileHandler handler("example.vb"); // handler.read(); // handler.printProperties(); // std::map updates; // updates["Version"] = "2"; // handler.write(updates); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-763 .VB ===== // ===== task-764 .VBOX [C++] ===== #include #include #include #include class VBOXFileHandler { private: std::string filename; xmlDocPtr doc; public: VBOXFileHandler(const std::string& fn) : filename(fn), doc(nullptr) {} ~VBOXFileHandler() { if (doc) xmlFreeDoc(doc); } bool read() { doc = xmlParseFile(filename.c_str()); if (!doc) { std::cout << "Error parsing file." << std::endl; return false; } return true; } void printProperties() { if (!doc) { std::cout << "No file read." << std::endl; return; } xmlNodePtr root = xmlDocGetRootElement(doc); xmlNodePtr machine = nullptr; for (xmlNodePtr cur = root->children; cur; cur = cur->next) { if (xmlStrcmp(cur->name, (const xmlChar*)"Machine") == 0) { machine = cur; break; } } if (machine) { std::cout << "Machine UUID: " << (char*)xmlGetProp(machine, (const xmlChar*)"uuid") << std::endl; std::cout << "Machine Name: " << (char*)xmlGetProp(machine, (const xmlChar*)"name") << std::endl; std::cout << "OS Type: " << (char*)xmlGetProp(machine, (const xmlChar*)"OSType") << std::endl; // Add other properties by traversing the tree } // Continue for other elements } bool write(const std::string& newFilename = "") { if (!doc) { std::cout << "No data to write." << std::endl; return false; } const std::string outFile = newFilename.empty() ? filename : newFilename; return xmlSaveFormatFileEnc(outFile.c_str(), doc, "UTF-8", 1) != -1; } void modifyProperty(const char* tagName, const char* attrib, const char* value) { xmlNodePtr root = xmlDocGetRootElement(doc); xmlNodePtr element = nullptr; for (xmlNodePtr cur = root->children; cur; cur = cur->next) { if (xmlStrcmp(cur->name, (const xmlChar*)tagName) == 0) { element = cur; break; } } if (element) { xmlSetProp(element, (const xmlChar*)attrib, (const xmlChar*)value); } } }; // Example usage: // VBOXFileHandler handler("example.vbox"); // if (handler.read()) { // handler.printProperties(); // handler.modifyProperty("Machine", "name", "NewName"); // handler.write(); // } // ===== end task-764 .VBOX ===== // ===== task-765 .VBOXEXTPACK [C++] ===== #include #include #include #include #include #include class VBoxExtPackHandler { private: std::string filepath; struct TarHeader { char name[100]; char mode[8]; char uid[8]; char gid[8]; char size[12]; char mtime[12]; char chksum[8]; char typeflag; char linkname[100]; char magic[6]; char version[2]; char uname[32]; char gname[32]; char devmajor[8]; char devminor[8]; char prefix[155]; char pad[12]; }; public: VBoxExtPackHandler(const std::string& fp) : filepath(fp) {} void readAndPrint() { std::ifstream file(filepath, std::ios::binary); std::vector compressed((std::istreambuf_iterator(file)), std::istreambuf_iterator()); std::vector decompressed = decompressGzip(compressed); size_t offset = 0; std::cout << "Properties of Entries:" << std::endl; while (offset < decompressed.size()) { if (decompressed[offset] == 0) break; TarHeader header; memcpy(&header, decompressed.data() + offset, sizeof(TarHeader)); printHeader(header); unsigned long size = strtoul(header.size, nullptr, 8); offset += 512 + ((size + 511) / 512) * 512; } } void printHeader(const TarHeader& header) { std::cout << "name: " << std::string(header.name, strnlen(header.name, 100)) << std::endl; std::cout << "mode: " << std::string(header.mode, 8) << std::endl; std::cout << "uid: " << std::string(header.uid, 8) << std::endl; // Print other fields similarly... std::cout << std::endl; } std::vector decompressGzip(const std::vector& data) { z_stream stream = {}; inflateInit2(&stream, 16 + MAX_WBITS); std::vector out(1024 * 1024); // Buffer size stream.next_in = (Bytef*)data.data(); stream.avail_in = data.size(); stream.next_out = (Bytef*)out.data(); stream.avail_out = out.size(); inflate(&stream, Z_NO_FLUSH); inflateEnd(&stream); out.resize(out.size() - stream.avail_out); return out; } void write(const std::string& outputPath, const std::vector>>& entries) { std::vector tarData; for (const auto& entry : entries) { TarHeader header = createTarHeader(entry.first, entry.second); std::vector headerBytes(sizeof(TarHeader)); memcpy(headerBytes.data(), &header, sizeof(TarHeader)); tarData.insert(tarData.end(), headerBytes.begin(), headerBytes.end()); tarData.insert(tarData.end(), entry.second.begin(), entry.second.end()); size_t pad = 512 - (entry.second.size() % 512); if (pad < 512) tarData.insert(tarData.end(), pad, 0); } tarData.insert(tarData.end(), 1024, 0); // End padding std::vector compressed = compressGzip(tarData); std::ofstream outFile(outputPath, std::ios::binary); outFile.write(compressed.data(), compressed.size()); } TarHeader createTarHeader(const std::string& name, const std::vector& content) { TarHeader header = {}; strncpy(header.name, name.c_str(), 100); sprintf(header.mode, "%07o", 0644); sprintf(header.size, "%011lo", content.size()); // Set other fields, compute checksum... return header; } std::vector compressGzip(const std::vector& data) { z_stream stream = {}; deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 16 + MAX_WBITS, 8, Z_DEFAULT_STRATEGY); std::vector out(data.size() * 2); stream.next_in = (Bytef*)data.data(); stream.avail_in = data.size(); stream.next_out = (Bytef*)out.data(); stream.avail_out = out.size(); deflate(&stream, Z_FINISH); deflateEnd(&stream); out.resize(out.size() - stream.avail_out); return out; } }; // Example usage: // int main() { // VBoxExtPackHandler handler("example.vbox-extpack"); // handler.readAndPrint(); // handler.write("new.vbox-extpack", {{"file.txt", {'c','o','n','t','e','n','t'}}}); // return 0; // } // ===== end task-765 .VBOXEXTPACK ===== // ===== task-766 .VBPROJ [C++] ===== #include #include #include #include // Assume TinyXML-2 library is included class VBProjHandler { private: std::string filepath; tinyxml2::XMLDocument doc; std::vector properties = { "AdditionalLibPaths", "AddModules", "ALToolPath", "ApplicationIcon", "ApplicationManifest", "AssemblyOriginatorKeyFile", "AssemblySearchPaths", "AssemblyName", "BaseAddress", "BaseIntermediateOutputPath", "BaseOutputPath", "BuildInParallel", "BuildProjectReferences", "CleanFile", "CodePage", "CompilerResponseFile", "Configuration", "CscToolPath", "CustomAfterMicrosoftCommonTargets", "CustomBeforeMicrosoftCommonTargets", "DebugSymbols", "DebugType", "DefineConstants", "DefineDebug", "DefineTrace", "DelaySign", "Deterministic", "DirectoryBuildPropsPath", "DirectoryBuildTargetsPath", "DisableFastUpToDateCheck", "DocumentationFile", "ErrorReport", "ExcludeDeploymentUrl", "FileAlignment", "FrameworkPathOverride", "GenerateDocumentationFile", "GenerateFullPaths", "GenerateResourceUsePreserializedResources", "GenerateSerializationAssemblies", "ImportDirectoryBuildProps", "ImportDirectoryBuildTargets", "IntermediateOutputPath", "KeyContainerName", "KeyOriginatorFile", "ModuleAssemblyName", "MSBuildProjectExtensionsPath", "MSBuildTreatWarningsAsErrors", "MSBuildWarningsAsErrors", "MSBuildWarningsAsMessages", "NoLogo", "NoStdLib", "NoVBRuntimeReference", "NoWarn", "NoWin32Manifest", "Optimize", "OptionCompare", "OptionExplicit", "OptionInfer", "OptionStrict", "OutDir", "OutputPath", "OutputType", "OverwriteReadOnlyFiles", "PathMap", "PdbFile", "Platform", "ProcessorArchitecture", "ProduceOnlyReferenceAssembly", "ProduceReferenceAssembly", "RegisterAssemblyMSBuildArchitecture", "RegisterForCOMInterop", "RemoveIntegerChecks", "RootNamespace", "SGenToolPath", "SGenUseProxyTypes", "SkipInvalidConfigurations", "StartupObject", "SubsystemVersion", "TargetCompactFramework", "TargetFrameworkVersion", "TreatWarningsAsErrors", "UseCommonOutputDirectory", "UseHostCompilerIfAvailable", "Utf8Output", "VbcToolPath", "VbcVerbosity", "VisualStudioVersion", "WarningsAsErrors", "WarningLevel", "WarningsNotAsErrors", "Win32Manifest", "Win32Resource" }; public: VBProjHandler(const std::string& filepath) : filepath(filepath) {} bool read() { return doc.LoadFile(filepath.c_str()) == tinyxml2::XML_SUCCESS; } void printProperties() { if (doc.Error()) { std::cout << "File not read. Call read() first." << std::endl; return; } tinyxml2::XMLElement* root = doc.FirstChildElement("Project"); if (!root) return; for (const std::string& prop : properties) { tinyxml2::XMLElement* elem = root->FirstChildElement(prop.c_str()); while (elem) { const char* text = elem->GetText(); std::cout << prop << ": " << (text ? text : "Not set") << std::endl; elem = elem->NextSiblingElement(prop.c_str()); } } } void setProperty(const std::string& propName, const std::string& value) { auto it = std::find(properties.begin(), properties.end(), propName); if (it == properties.end()) { std::cout << "Property " << propName << " not in allowed list." << std::endl; return; } if (doc.Error()) { std::cout << "File not read. Call read() first." << std::endl; return; } tinyxml2::XMLElement* root = doc.FirstChildElement("Project"); if (!root) return; tinyxml2::XMLElement* group = root->FirstChildElement("PropertyGroup"); if (!group) { group = doc.NewElement("PropertyGroup"); root->InsertEndChild(group); } tinyxml2::XMLElement* elem = group->FirstChildElement(propName.c_str()); if (!elem) { elem = doc.NewElement(propName.c_str()); group->InsertEndChild(elem); } elem->SetText(value.c_str()); } bool write(const std::string& outputPath = "") { if (doc.Error()) { std::cout << "No data to write. Call read() first." << std::endl; return false; } std::string path = outputPath.empty() ? filepath : outputPath; return doc.SaveFile(path.c_str()) == tinyxml2::XML_SUCCESS; } }; // Example usage: // int main() { // VBProjHandler handler("example.vbproj"); // if (handler.read()) { // handler.printProperties(); // handler.setProperty("AssemblyName", "NewAssembly"); // handler.write(); // } // return 0; // } // ===== end task-766 .VBPROJ ===== // ===== task-767 .VBR [C++] ===== #include #include #include #include #include #include class VBRFile { public: std::string magic = "GIMP-VBR"; std::string version; std::string name; std::string shape; float spacing; float radius; int spikes = -1; // -1 indicates not set float hardness; float aspect_ratio; float angle; VBRFile() {} VBRFile(const std::string& filename) { read(filename); } void read(const std::string& filename) { std::ifstream file(filename); if (!file.is_open()) { throw std::runtime_error("Unable to open file."); } std::vector lines; std::string line; while (std::getline(file, line)) { // Trim trailing whitespace, including \r if any line.erase(std::find_if(line.rbegin(), line.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), line.end()); lines.push_back(line); } file.close(); if (lines.size() < 8 || lines[0] != "GIMP-VBR") { throw std::runtime_error("Invalid .VBR file: Missing or incorrect magic string."); } magic = lines[0]; version = lines[1]; name = lines[2]; if (version == "1.0") { if (lines.size() != 8) { throw std::runtime_error("Invalid .VBR file: Incorrect number of lines for version 1.0."); } spacing = std::stof(lines[3]); radius = std::stof(lines[4]); hardness = std::stof(lines[5]); aspect_ratio = std::stof(lines[6]); angle = std::stof(lines[7]); shape = ""; spikes = -1; } else if (version == "1.5") { if (lines.size() != 10) { throw std::runtime_error("Invalid .VBR file: Incorrect number of lines for version 1.5."); } shape = lines[3]; spacing = std::stof(lines[4]); radius = std::stof(lines[5]); spikes = std::stoi(lines[6]); hardness = std::stof(lines[7]); aspect_ratio = std::stof(lines[8]); angle = std::stof(lines[9]); } else { throw std::runtime_error("Unsupported .VBR version."); } } void write(const std::string& filename) { if (version != "1.0" && version != "1.5") { throw std::runtime_error("Version must be set to 1.0 or 1.5 before writing."); } std::ofstream file(filename); if (!file.is_open()) { throw std::runtime_error("Unable to open file for writing."); } file << magic << "\n"; file << version << "\n"; file << name << "\n"; if (version == "1.5") { if (shape.empty() || spikes == -1) { throw std::runtime_error("Shape and spikes must be set for version 1.5."); } file << shape << "\n"; file << spacing << "\n"; file << radius << "\n"; file << spikes << "\n"; file << hardness << "\n"; file << aspect_ratio << "\n"; file << angle << "\n"; } else { if (!shape.empty() || spikes != -1) { throw std::runtime_error("Shape and spikes should not be set for version 1.0."); } file << spacing << "\n"; file << radius << "\n"; file << hardness << "\n"; file << aspect_ratio << "\n"; file << angle << "\n"; } file.close(); } void print_properties() { std::cout << "Magic string: " << magic << std::endl; std::cout << "Version: " << version << std::endl; std::cout << "Name: " << name << std::endl; if (version == "1.5") { std::cout << "Shape: " << shape << std::endl; } std::cout << "Spacing: " << spacing << std::endl; std::cout << "Radius: " << radius << std::endl; if (version == "1.5") { std::cout << "Spikes: " << spikes << std::endl; } std::cout << "Hardness: " << hardness << std::endl; std::cout << "Aspect ratio: " << aspect_ratio << std::endl; std::cout << "Angle: " << angle << std::endl; } }; // ===== end task-767 .VBR ===== // ===== task-768 .VBS [C++] ===== #include #include #include #include // For stat #include // For time formatting #include // For strerror class VBSFileHandler { private: std::string filepath; std::string content; public: VBSFileHandler(const std::string& fp) : filepath(fp) {} std::string read() { std::ifstream file(filepath, std::ios::in | std::ios::binary); if (!file) { throw std::runtime_error("Failed to open file for reading."); } content.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); return content; } void write(const std::string& newContent) { std::ofstream file(filepath, std::ios::out | std::ios::binary); if (!file) { throw std::runtime_error("Failed to open file for writing."); } file << newContent; content = newContent; } void printProperties() { struct stat st; if (stat(filepath.c_str(), &st) != 0) { std::cerr << "Error getting file stats: " << strerror(errno) << std::endl; return; } std::cout << "File Name: " << filepath.substr(filepath.find_last_of("/\\") + 1) << std::endl; std::cout << "File Path: " << filepath << std::endl; // Absolute path requires realpath() std::cout << "File Size: " << st.st_size << std::endl; std::cout << "Creation Time: " << std::ctime(&st.st_ctime); std::cout << "Last Modification Time: " << std::ctime(&st.st_mtime); std::cout << "Last Access Time: " << std::ctime(&st.st_atime); std::cout << "File Attributes: " << (S_ISREG(st.st_mode) ? "Regular File" : "Other") << std::endl; std::cout << "Owner: " << st.st_uid << std::endl; // UID; use getpwuid for name std::cout << "Permissions: " << std::oct << (st.st_mode & 0777) << std::endl; std::cout << "MIME Type: text/vbscript" << std::endl; std::cout << "Encoding: UTF-8 (assumed)" << std::endl; } }; // Example usage: // int main() { // try { // VBSFileHandler handler("example.vbs"); // handler.read(); // handler.printProperties(); // handler.write("New VBScript code"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-768 .VBS ===== // ===== task-769 .VBX [C] ===== #include #include #include #include typedef struct { char* filename; long ne_offset; uint8_t* data; size_t size; // Properties (use a struct or map, but for simplicity, individual fields) char sig[3]; uint8_t MajLinkerVersion; uint8_t MinLinkerVersion; uint16_t EntryTableOffset; uint16_t EntryTableLength; uint32_t FileLoadCRC; uint16_t FlagWord; uint16_t AutoDataSegIndex; uint16_t InitHeapSize; uint16_t InitStackSize; uint32_t EntryPoint; uint32_t InitStack; uint16_t SegCount; uint16_t ModRefs; uint16_t NoResNamesTabSiz; uint16_t SegTableOffset; uint16_t ResTableOffset; uint16_t ResidNamTable; uint16_t ModRefTable; uint16_t ImportNameTable; uint32_t OffStartNonResTab; uint16_t MovEntryCount; uint16_t FileAlnSzShftCnt; uint16_t nResTabEntries; uint8_t targOS; uint8_t OS2EXEFlags; uint16_t retThunkOffset; uint16_t segrefthunksoff; uint16_t mincodeswap; char expctwinver[6]; // "minor.major" } VBXParser; VBXParser* vbx_parser_create(const char* filename) { VBXParser* parser = malloc(sizeof(VBXParser)); parser->filename = strdup(filename); FILE* f = fopen(filename, "rb"); if (!f) { free(parser); return NULL; } fseek(f, 0, SEEK_END); parser->size = ftell(f); fseek(f, 0, SEEK_SET); parser->data = malloc(parser->size); fread(parser->data, 1, parser->size, f); fclose(f); // Read ne_offset memcpy(&parser->ne_offset, parser->data + 0x3C, 4); memcpy(parser->sig, parser->data + parser->ne_offset, 2); parser->sig[2] = '\0'; if (strcmp(parser->sig, "NE") != 0) { free(parser->data); free(parser->filename); free(parser); return NULL; } long offset = parser->ne_offset + 2; parser->MajLinkerVersion = parser->data[offset++]; parser->MinLinkerVersion = parser->data[offset++]; memcpy(&parser->EntryTableOffset, parser->data + offset, 2); offset += 2; memcpy(&parser->EntryTableLength, parser->data + offset, 2); offset += 2; memcpy(&parser->FileLoadCRC, parser->data + offset, 4); offset += 4; memcpy(&parser->FlagWord, parser->data + offset, 2); offset += 2; memcpy(&parser->AutoDataSegIndex, parser->data + offset, 2); offset += 2; memcpy(&parser->InitHeapSize, parser->data + offset, 2); offset += 2; memcpy(&parser->InitStackSize, parser->data + offset, 2); offset += 2; memcpy(&parser->EntryPoint, parser->data + offset, 4); offset += 4; memcpy(&parser->InitStack, parser->data + offset, 4); offset += 4; memcpy(&parser->SegCount, parser->data + offset, 2); offset += 2; memcpy(&parser->ModRefs, parser->data + offset, 2); offset += 2; memcpy(&parser->NoResNamesTabSiz, parser->data + offset, 2); offset += 2; memcpy(&parser->SegTableOffset, parser->data + offset, 2); offset += 2; memcpy(&parser->ResTableOffset, parser->data + offset, 2); offset += 2; memcpy(&parser->ResidNamTable, parser->data + offset, 2); offset += 2; memcpy(&parser->ModRefTable, parser->data + offset, 2); offset += 2; memcpy(&parser->ImportNameTable, parser->data + offset, 2); offset += 2; memcpy(&parser->OffStartNonResTab, parser->data + offset, 4); offset += 4; memcpy(&parser->MovEntryCount, parser->data + offset, 2); offset += 2; memcpy(&parser->FileAlnSzShftCnt, parser->data + offset, 2); offset += 2; memcpy(&parser->nResTabEntries, parser->data + offset, 2); offset += 2; parser->targOS = parser->data[offset++]; parser->OS2EXEFlags = parser->data[offset++]; memcpy(&parser->retThunkOffset, parser->data + offset, 2); offset += 2; memcpy(&parser->segrefthunksoff, parser->data + offset, 2); offset += 2; memcpy(&parser->mincodeswap, parser->data + offset, 2); offset += 2; uint8_t minor = parser->data[offset++]; uint8_t major = parser->data[offset]; sprintf(parser->expctwinver, "%u.%u", minor, major); return parser; } void vbx_parser_print(VBXParser* parser) { printf("sig: %s\n", parser->sig); printf("MajLinkerVersion: %u\n", parser->MajLinkerVersion); printf("MinLinkerVersion: %u\n", parser->MinLinkerVersion); printf("EntryTableOffset: %u\n", parser->EntryTableOffset); printf("EntryTableLength: %u\n", parser->EntryTableLength); printf("FileLoadCRC: %u\n", parser->FileLoadCRC); printf("FlagWord: %u\n", parser->FlagWord); printf("AutoDataSegIndex: %u\n", parser->AutoDataSegIndex); printf("InitHeapSize: %u\n", parser->InitHeapSize); printf("InitStackSize: %u\n", parser->InitStackSize); printf("EntryPoint: %u\n", parser->EntryPoint); printf("InitStack: %u\n", parser->InitStack); printf("SegCount: %u\n", parser->SegCount); printf("ModRefs: %u\n", parser->ModRefs); printf("NoResNamesTabSiz: %u\n", parser->NoResNamesTabSiz); printf("SegTableOffset: %u\n", parser->SegTableOffset); printf("ResTableOffset: %u\n", parser->ResTableOffset); printf("ResidNamTable: %u\n", parser->ResidNamTable); printf("ModRefTable: %u\n", parser->ModRefTable); printf("ImportNameTable: %u\n", parser->ImportNameTable); printf("OffStartNonResTab: %u\n", parser->OffStartNonResTab); printf("MovEntryCount: %u\n", parser->MovEntryCount); printf("FileAlnSzShftCnt: %u\n", parser->FileAlnSzShftCnt); printf("nResTabEntries: %u\n", parser->nResTabEntries); printf("targOS: %u\n", parser->targOS); printf("OS2EXEFlags: %u\n", parser->OS2EXEFlags); printf("retThunkOffset: %u\n", parser->retThunkOffset); printf("segrefthunksoff: %u\n", parser->segrefthunksoff); printf("mincodeswap: %u\n", parser->mincodeswap); printf("expctwinver: %s\n", parser->expctwinver); } void vbx_parser_write(VBXParser* parser, const char* output_filename) { // Example: Update MajLinkerVersion in data parser->data[parser->ne_offset + 2] = parser->MajLinkerVersion; // Repeat for other fields FILE* f = fopen(output_filename, "wb"); if (f) { fwrite(parser->data, 1, parser->size, f); fclose(f); } } void vbx_parser_destroy(VBXParser* parser) { free(parser->data); free(parser->filename); free(parser); } // Usage example: // int main() { // VBXParser* parser = vbx_parser_create("example.vbx"); // if (parser) { // vbx_parser_print(parser); // parser->MajLinkerVersion = 5; // Modify // vbx_parser_write(parser, "modified.vbx"); // vbx_parser_destroy(parser); // } // return 0; // } // ===== end task-769 .VBX ===== // ===== task-770 .VC [C++] ===== #include #include #include #include #include #include class VCFileHandler { private: std::string filepath; std::map> cells; // address: {type, content} public: VCFileHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath); if (!file.is_open()) { throw std::runtime_error("File " + filepath + " not found."); } std::stringstream content; std::string line; while (std::getline(file, line, '\r')) { // Handle CR endings content << line << '\n'; } file.close(); std::string cleaned = content.str(); cleaned.erase(std::remove(cleaned.begin(), cleaned.end(), '\0'), cleaned.end()); // Remove null std::stringstream ss(cleaned); while (std::getline(ss, line, '\n')) { line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); if (!line.empty() && line[0] == '>') { size_t colonPos = line.find(':'); std::string address = line.substr(1, colonPos - 1); std::string entry = (colonPos != std::string::npos) ? line.substr(colonPos + 1) : ""; std::string type = "Unknown"; if (!entry.empty()) { char first = entry[0]; if (first == '"' || first == '\'' || first == '^') type = "Label"; else if (first == '+') type = "Formula"; else if (first == '@') type = "Function"; else { bool isNum = true; for (char c : entry) { if (!std::isdigit(c) && c != '.' && c != '-') { isNum = false; break; } } if (isNum) type = "Value"; } } cells[address] = {type, entry}; } } } void printProperties() { std::cout << "Dumped .VC Properties:" << std::endl; for (const auto& pair : cells) { std::string address = pair.first; auto data = pair.second; std::cout << "Cell: " << address << " | Type: " << data.first << " | Content: " << data.second << std::endl; } } void write(const std::string& newFilepath) { std::ofstream file(newFilepath); if (!file.is_open()) { throw std::runtime_error("Cannot open " + newFilepath + " for writing."); } for (const auto& pair : cells) { std::string address = pair.first; std::string content = pair.second.second; file << ">" << address << ":" << content << "\n"; } file << '\0'; file.close(); } }; // Example usage: // int main() { // try { // VCFileHandler handler("sample.vc"); // handler.read(); // handler.printProperties(); // handler.write("new.vc"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-770 .VC ===== // ===== task-771 .VC6 [C] ===== #include #include typedef struct { char* filepath; unsigned char* data; size_t size; } VC6FileHandler; VC6FileHandler* createVC6Handler(const char* filepath) { VC6FileHandler* handler = malloc(sizeof(VC6FileHandler)); handler->filepath = strdup(filepath); handler->data = NULL; handler->size = 0; return handler; } void openAndRead(VC6FileHandler* handler) { FILE* file = fopen(handler->filepath, "rb"); if (!file) { printf("Error opening file: %s\n", handler->filepath); return; } fseek(file, 0, SEEK_END); handler->size = ftell(file); fseek(file, 0, SEEK_SET); handler->data = malloc(handler->size); fread(handler->data, 1, handler->size, file); fclose(file); printf("File opened: %s\n", handler->filepath); printf("File size: %zu bytes\n", handler->size); } void decodeAndPrintProperties(VC6FileHandler* handler) { if (!handler->data) { printf("File not opened.\n"); return; } // Placeholder: No real decoding possible without spec. printf("Properties not extractable without format specification.\n"); // Example high-level properties from documentation (static). const char* properties[] = { "Multiple sheets", "Models (3D geometry, dimensions, text, fills, hatching)", "Views (from cameras)", "Layers", "Parametrics", "Symbols" }; for (int i = 0; i < sizeof(properties)/sizeof(properties[0]); i++) { printf("%s\n", properties[i]); } } void write(VC6FileHandler* handler, const char* outputPath) { if (!handler->data) { printf("No data to write.\n"); return; } FILE* file = fopen(outputPath, "wb"); if (!file) { printf("Error writing to file: %s\n", outputPath); return; } fwrite(handler->data, 1, handler->size, file); fclose(file); printf("File written to: %s\n", outputPath); } void destroyVC6Handler(VC6FileHandler* handler) { free(handler->data); free(handler->filepath); free(handler); } // Usage example: // int main() { // VC6FileHandler* handler = createVC6Handler("example.vc6"); // openAndRead(handler); // decodeAndPrintProperties(handler); // write(handler, "output.vc6"); // destroyVC6Handler(handler); // return 0; // } // ===== end task-771 .VC6 ===== // ===== task-772 .VCLS [C++] ===== #include #include #include #include #include typedef struct { char* filepath; xmlDocPtr doc; } VCLSHandler; void vcls_init(VCLSHandler* handler, const char* filepath) { handler->filepath = strdup(filepath); handler->doc = NULL; vcls_load(handler); } void vcls_load(VCLSHandler* handler) { handler->doc = xmlReadFile(handler->filepath, NULL, 0); if (handler->doc == NULL) { printf("Error loading file: %s\n", handler->filepath); } } void vcls_print_properties(VCLSHandler* handler) { if (handler->doc == NULL) { printf("No file loaded.\n"); return; } xmlNode* root = xmlDocGetRootElement(handler->doc); xmlNode* classNode = NULL; for (xmlNode* node = root->children; node; node = node->next) { if (node->type == XML_ELEMENT_NODE && strcmp((char*)node->name, "class") == 0) { classNode = node; break; } } if (classNode) { char* className = (char*)xmlGetProp(classNode, (xmlChar*)"name"); printf("Class Name: %s\n", className ? className : "Not found"); xmlFree(className); xmlNode* dataNode = NULL; xmlNode* propertiesNode = NULL; for (xmlNode* child = classNode->children; child; child = child->next) { if (child->type == XML_ELEMENT_NODE) { if (strcmp((char*)child->name, "data") == 0) dataNode = child; if (strcmp((char*)child->name, "properties") == 0) propertiesNode = child; } } char* data = dataNode ? (char*)xmlNodeGetContent(dataNode) : NULL; printf("Data Structures: %s\n", data ? data : "Not found"); xmlFree(data); char* properties = propertiesNode ? (char*)xmlNodeGetContent(propertiesNode) : NULL; printf("Property Declarations: %s\n", properties ? properties : "Not found"); xmlFree(properties); } else { printf("Class element not found.\n"); } } void vcls_write(VCLSHandler* handler, const char* new_filepath) { if (handler->doc == NULL) { printf("No data to write.\n"); return; } const char* path = new_filepath ? new_filepath : handler->filepath; if (xmlSaveFormatFileEnc(path, handler->doc, "UTF-8", 1) == -1) { printf("Error writing file: %s\n", path); } else { printf("File written to %s\n", path); } } void vcls_free(VCLSHandler* handler) { if (handler->doc) xmlFreeDoc(handler->doc); free(handler->filepath); } // Example usage: // int main() { // VCLSHandler handler; // vcls_init(&handler, "example.vcls"); // vcls_print_properties(&handler); // vcls_write(&handler, "new.vcls"); // vcls_free(&handler); // return 0; // } // ===== end task-772 .VCLS ===== // ===== task-773 .VDA [C] ===== #include #include typedef struct { unsigned char idLength; unsigned char colorMapType; unsigned char imageType; unsigned short colorMapOrigin; unsigned short colorMapLength; unsigned char colorMapDepth; unsigned short xOrigin; unsigned short yOrigin; unsigned short width; unsigned short height; unsigned char bitsPerPixel; unsigned char imageDescriptor; } VDAProperties; struct VDAFile { char* filename; VDAProperties properties; }; struct VDAFile* createVDAFile(const char* filename) { struct VDAFile* vda = malloc(sizeof(struct VDAFile)); vda->filename = (char*)filename; return vda; } void readVDA(struct VDAFile* vda) { FILE* file = fopen(vda->filename, "rb"); if (file == NULL) { perror("Error opening file"); return; } unsigned char header[18]; if (fread(header, 1, 18, file) < 18) { fprintf(stderr, "Invalid .VDA file header\n"); fclose(file); return; } vda->properties.idLength = header[0]; vda->properties.colorMapType = header[1]; vda->properties.imageType = header[2]; vda->properties.colorMapOrigin = header[3] | (header[4] << 8); vda->properties.colorMapLength = header[5] | (header[6] << 8); vda->properties.colorMapDepth = header[7]; vda->properties.xOrigin = header[8] | (header[9] << 8); vda->properties.yOrigin = header[10] | (header[11] << 8); vda->properties.width = header[12] | (header[13] << 8); vda->properties.height = header[14] | (header[15] << 8); vda->properties.bitsPerPixel = header[16]; vda->properties.imageDescriptor = header[17]; fclose(file); } void printProperties(VDAProperties props) { printf("ID Length: %u\n", props.idLength); printf("Color Map Type: %u\n", props.colorMapType); printf("Image Type: %u\n", props.imageType); printf("Color Map Origin: %u\n", props.colorMapOrigin); printf("Color Map Length: %u\n", props.colorMapLength); printf("Color Map Depth: %u\n", props.colorMapDepth); printf("X Origin: %u\n", props.xOrigin); printf("Y Origin: %u\n", props.yOrigin); printf("Width: %u\n", props.width); printf("Height: %u\n", props.height); printf("Bits Per Pixel: %u\n", props.bitsPerPixel); printf("Image Descriptor: %u\n", props.imageDescriptor); } void writeVDA(const char* newFilename, VDAProperties props, const unsigned char* imageData, size_t dataSize) { FILE* file = fopen(newFilename, "wb"); if (file == NULL) { perror("Error opening file"); return; } unsigned char header[18] = {0}; header[0] = props.idLength; header[1] = props.colorMapType; header[2] = props.imageType; header[3] = props.colorMapOrigin & 0xFF; header[4] = (props.colorMapOrigin >> 8) & 0xFF; header[5] = props.colorMapLength & 0xFF; header[6] = (props.colorMapLength >> 8) & 0xFF; header[7] = props.colorMapDepth; header[8] = props.xOrigin & 0xFF; header[9] = (props.xOrigin >> 8) & 0xFF; header[10] = props.yOrigin & 0xFF; header[11] = (props.yOrigin >> 8) & 0xFF; header[12] = props.width & 0xFF; header[13] = (props.width >> 8) & 0xFF; header[14] = props.height & 0xFF; header[15] = (props.height >> 8) & 0xFF; header[16] = props.bitsPerPixel; header[17] = props.imageDescriptor; fwrite(header, 1, 18, file); fwrite(imageData, 1, dataSize, file); fclose(file); } int main() { struct VDAFile* vda = createVDAFile("example.vda"); readVDA(vda); printProperties(vda->properties); // To write VDAProperties newProps = {0}; newProps.width = 100; newProps.height = 100; newProps.bitsPerPixel = 24; newProps.imageType = 2; writeVDA("new.vda", newProps, NULL, 0); free(vda); return 0; } // ===== end task-773 .VDA ===== // ===== task-774 .VDI [C++] ===== #include #include #include #include #include #include #include class VDIFile { private: std::string filepath; std::map properties; public: VDIFile(const std::string& fp) : filepath(fp) { parse(); } void parse() { std::ifstream file(filepath, std::ios::binary); if (!file) { std::cerr << "Cannot open file" << std::endl; return; } std::vector buffer(1024); file.read(buffer.data(), 1024); size_t offset = 0; // Text std::string text(buffer.begin() + offset, buffer.begin() + offset + 64); properties["text"] = text.substr(0, text.find('\0')); offset += 64; // Signature uint32_t sig; std::memcpy(&sig, buffer.data() + offset, 4); if (sig != 0xBEDA107F) { // LE std::cerr << "Invalid signature" << std::endl; return; } properties["signature"] = "0x7F10DABE"; offset += 4; // Version uint16_t major, minor; std::memcpy(&major, buffer.data() + offset, 2); offset += 2; std::memcpy(&minor, buffer.data() + offset, 2); offset += 2; properties["version"] = std::to_string(major) + "." + std::to_string(minor); bool hasExtended = major >= 1; uint32_t headerSize = 336; if (hasExtended) { std::memcpy(&headerSize, buffer.data() + offset, 4); offset += 4; properties["header_size"] = std::to_string(headerSize); } // Image Type uint32_t imageType; std::memcpy(&imageType, buffer.data() + offset, 4); offset += 4; std::string typeStr; switch (imageType) { case 1: typeStr = "dynamic"; break; case 2: typeStr = "static"; break; case 3: typeStr = "undo"; break; case 4: typeStr = "diff"; break; default: typeStr = "unknown"; } properties["image_type"] = typeStr; // Image Flags uint32_t flags; std::memcpy(&flags, buffer.data() + offset, 4); offset += 4; std::stringstream ss; ss << "0x" << std::hex << flags << " (zero_expand: " << bool(flags & (1 << 15)) << ", diff: " << bool(flags & (1 << 22)) << ", fixed: " << bool(flags & (1 << 23)) << ")"; properties["image_flags"] = ss.str(); // Description std::string desc(buffer.begin() + offset, buffer.begin() + offset + 256); properties["description"] = desc.substr(0, desc.find('\0')); offset += 256; if (hasExtended) { uint32_t val; std::memcpy(&val, buffer.data() + offset, 4); offset += 4; properties["blocks_map_offset"] = std::to_string(val); std::memcpy(&val, buffer.data() + offset, 4); offset += 4; properties["offset_data"] = std::to_string(val); } // Geometry uint32_t cyl, heads, sects, sectSize; std::memcpy(&cyl, buffer.data() + offset, 4); offset += 4; std::memcpy(&heads, buffer.data() + offset, 4); offset += 4; std::memcpy(§s, buffer.data() + offset, 4); offset += 4; std::memcpy(§Size, buffer.data() + offset, 4); offset += 4; ss.str(""); ss << "C=" << cyl << ", H=" << heads << ", S=" << sects << ", Sector Size=" << sectSize; properties["geometry"] = ss.str(); if (hasExtended) { uint32_t reserved1; std::memcpy(&reserved1, buffer.data() + offset, 4); offset += 4; properties["reserved1"] = std::to_string(reserved1); } // Disk Size uint64_t diskSize; std::memcpy(&diskSize, buffer.data() + offset, 8); offset += 8; properties["disk_size"] = std::to_string(diskSize); // Block Data Size uint32_t blockDataSize; std::memcpy(&blockDataSize, buffer.data() + offset, 4); offset += 4; properties["block_data_size"] = std::to_string(blockDataSize); if (hasExtended) { uint32_t blockMetaSize; std::memcpy(&blockMetaSize, buffer.data() + offset, 4); offset += 4; properties["block_metadata_size"] = std::to_string(blockMetaSize); } // Blocks in Image uint32_t blocksInImage; std::memcpy(&blocksInImage, buffer.data() + offset, 4); offset += 4; properties["blocks_in_image"] = std::to_string(blocksInImage); // Blocks Allocated uint32_t blocksAllocated; std::memcpy(&blocksAllocated, buffer.data() + offset, 4); offset += 4; properties["blocks_allocated"] = std::to_string(blocksAllocated); // UUIDs auto hexUuid = [](const char* buf) -> std::string { std::stringstream s; for (int i = 0; i < 16; ++i) s << std::hex << std::setfill('0') << std::setw(2) << (unsigned char)buf[i]; return s.str(); }; properties["uuid_image"] = hexUuid(buffer.data() + offset); offset += 16; properties["uuid_last_snap"] = hexUuid(buffer.data() + offset); offset += 16; properties["uuid_link"] = hexUuid(buffer.data() + offset); offset += 16; if (hasExtended) { properties["uuid_parent"] = hexUuid(buffer.data() + offset); offset += 16; } // LCHC Geometry if (hasExtended && offset + 16 <= buffer.size()) { uint32_t lcyl, lheads, lsects, lsectSize; std::memcpy(&lcyl, buffer.data() + offset, 4); offset += 4; std::memcpy(&lheads, buffer.data() + offset, 4); offset += 4; std::memcpy(&lsects, buffer.data() + offset, 4); offset += 4; std::memcpy(&lsectSize, buffer.data() + offset, 4); offset += 4; ss.str(""); ss << "C=" << lcyl << ", H=" << lheads << ", S=" << lsects << ", Sector Size=" << lsectSize; properties["lchc_geometry"] = ss.str(); } } void printProperties() const { for (const auto& [key, value] : properties) { std::string title = key; title[0] = std::toupper(title[0]); std::replace(title.begin(), title.end(), '_', ' '); std::cout << title << ": " << value << std::endl; } } void write(const std::string& newFilepath = "") const { std::string outPath = newFilepath.empty() ? filepath + ".new" : newFilepath; std::ifstream in(filepath, std::ios::binary); std::ofstream out(outPath, std::ios::binary); out << in.rdbuf(); std::cout << "Written to " << outPath << std::endl; } }; // Example // int main() { // VDIFile vdi("example.vdi"); // vdi.printProperties(); // vdi.write(); // return 0; // } // ===== end task-774 .VDI ===== // ===== task-775 .VDW [C] ===== #include #include #include typedef struct { char *filename; unsigned char *data; long size; // Map-like for properties (simple array for demo) char *keys[10]; char *values[10]; int propCount; } VDWFile; VDWFile *vdw_create(const char *filename) { VDWFile *vdw = malloc(sizeof(VDWFile)); vdw->filename = strdup(filename); vdw->data = NULL; vdw->size = 0; vdw->propCount = 0; return vdw; } void vdw_open(VDWFile *vdw) { FILE *f = fopen(vdw->filename, "rb"); if (f) { fseek(f, 0, SEEK_END); vdw->size = ftell(f); fseek(f, 0, SEEK_SET); vdw->data = malloc(vdw->size); fread(vdw->data, 1, vdw->size, f); fclose(f); } } void vdw_decode(VDWFile *vdw) { unsigned char magic[8] = {0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1}; if (memcmp(vdw->data, magic, 8) != 0) { printf("Invalid .VDW file\n"); return; } // Simulate vdw->keys[vdw->propCount] = "Magic"; vdw->values[vdw->propCount++] = "D0 CF 11 E0 A1 B1 1A E1"; unsigned short major = *(unsigned short*)(vdw->data + 24); char buf[10]; sprintf(buf, "%u", major); vdw->keys[vdw->propCount] = "Major Version"; vdw->values[vdw->propCount++] = strdup(buf); // Add more vdw->keys[vdw->propCount] = "ZIP Files"; vdw->values[vdw->propCount++] = "app.xml, core.xml"; } void vdw_print_properties(VDWFile *vdw) { for (int i = 0; i < vdw->propCount; i++) { printf("%s: %s\n", vdw->keys[i], vdw->values[i]); } } void vdw_write(VDWFile *vdw, const char *newFilename) { FILE *f = fopen(newFilename, "wb"); if (f) { fwrite(vdw->data, 1, vdw->size, f); fclose(f); } } void vdw_destroy(VDWFile *vdw) { free(vdw->data); for (int i = 0; i < vdw->propCount; i++) { free(vdw->values[i]); } free(vdw->filename); free(vdw); } // Example usage // VDWFile *vdw = vdw_create("example.vdw"); // vdw_open(vdw); // vdw_decode(vdw); // vdw_print_properties(vdw); // vdw_write(vdw, "new.vdw"); // vdw_destroy(vdw); // ===== end task-775 .VDW ===== // ===== task-776 .VDX [C++] ===== #include #include #include #include using namespace std; class VDXHandler { private: string filepath; string xmlContent; vector properties = { "DocumentProperties", "DocumentSettings", "Colors", "FaceNames", "StyleSheets", "DocumentSheet", "Masters", "Pages", "Windows", "EventList", "HeaderFooter", "VBProjectData", "EmailRoutingData", "SolutionXML" }; public: VDXHandler(const string& fp) : filepath(fp) {} bool read() { ifstream file(filepath); if (!file.is_open()) return false; xmlContent = string((istreambuf_iterator(file)), istreambuf_iterator()); file.close(); if (xmlContent.find("", start); if (end != string::npos) { end += prop.length() + 3; // Include closing tag cout << prop << ":" << endl << xmlContent.substr(start, end - start) << endl << endl; } else { cout << prop << ": Incomplete" << endl << endl; } } else { cout << prop << ": Not present" << endl << endl; } } } void write(const string& newFilepath = "") { string path = newFilepath.empty() ? filepath : newFilepath; ofstream file(path); if (file.is_open()) { file << xmlContent; file.close(); } } // Example method to modify (append a dummy tag to DocumentProperties) void modifyExample() { size_t pos = xmlContent.find(""); if (pos != string::npos) { string insert = "Modified Value"; xmlContent.insert(pos, insert); } } }; // Usage example: // int main() { // VDXHandler handler("sample.vdx"); // if (handler.read()) { // handler.printProperties(); // handler.modifyExample(); // handler.write("modified.vdx"); // } else { // cout << "Failed to read file" << endl; // } // return 0; // } // ===== end task-776 .VDX ===== // ===== task-777 .VFD [C++] ===== #include #include #include #include #include #include class VFDHandler { private: std::string filepath; std::map properties; std::string toHex(uint8_t val, int width) { std::stringstream ss; ss << std::hex << std::uppercase << std::setfill('0') << std::setw(width) << static_cast(val); return ss.str(); } std::string getString(const char* data, size_t offset, size_t length) { std::string str; for (size_t i = 0; i < length; ++i) { char c = data[offset + i]; str += (c >= 32 && c <= 126) ? c : ' '; } // Trim trailing spaces size_t end = str.find_last_not_of(' '); return (end != std::string::npos) ? str.substr(0, end + 1) : ""; } public: VFDHandler(const std::string& fp) : filepath(fp) { read(); } void read() { std::ifstream file(filepath, std::ios::binary); if (!file) { std::cerr << "Error opening file" << std::endl; return; } char buffer[512]; file.read(buffer, 512); if (file.gcount() < 512) { std::cerr << "Invalid .VFD file" << std::endl; return; } properties["Boot Jump"] = toHex(static_cast(buffer[0]), 2) + " " + toHex(static_cast(buffer[1]), 2) + " " + toHex(static_cast(buffer[2]), 2); properties["OEM Identifier"] = getString(buffer, 3, 8); properties["Bytes per Sector"] = std::to_string(*reinterpret_cast(buffer + 11)); properties["Sectors per Cluster"] = std::to_string(static_cast(buffer[13])); properties["Reserved Sectors"] = std::to_string(*reinterpret_cast(buffer + 14)); properties["Number of FATs"] = std::to_string(static_cast(buffer[16])); properties["Root Directory Entries"] = std::to_string(*reinterpret_cast(buffer + 17)); properties["Total Sectors (16-bit)"] = std::to_string(*reinterpret_cast(buffer + 19)); properties["Media Descriptor Type"] = "0x" + toHex(static_cast(buffer[21]), 2); properties["Sectors per FAT"] = std::to_string(*reinterpret_cast(buffer + 22)); properties["Sectors per Track"] = std::to_string(*reinterpret_cast(buffer + 24)); properties["Number of Heads"] = std::to_string(*reinterpret_cast(buffer + 26)); properties["Hidden Sectors"] = std::to_string(*reinterpret_cast(buffer + 28)); properties["Total Sectors (32-bit)"] = std::to_string(*reinterpret_cast(buffer + 32)); properties["Drive Number"] = "0x" + toHex(static_cast(buffer[36]), 2); properties["Reserved (NT Flags)"] = "0x" + toHex(static_cast(buffer[37]), 2); properties["Signature"] = "0x" + toHex(static_cast(buffer[38]), 2); properties["Volume ID"] = "0x" + toHex(*reinterpret_cast(buffer + 39), 8); properties["Volume Label"] = getString(buffer, 43, 11); properties["File System Type"] = getString(buffer, 54, 8); properties["Boot Signature"] = "0x" + toHex(*reinterpret_cast(buffer + 510), 4); } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void writeProperty(const std::string& key, const std::string& value) { std::fstream file(filepath, std::ios::in | std::ios::out | std::ios::binary); if (!file) return; char buffer[512]; file.read(buffer, 512); if (key == "Bytes per Sector") { *reinterpret_cast(buffer + 11) = std::stoi(value); } // Add similar for other keys... file.seekp(0); file.write(buffer, 512); read(); } }; int main(int argc, char* argv[]) { if (argc > 1) { VFDHandler vfd(argv[1]); vfd.printProperties(); } return 0; } // ===== end task-777 .VFD ===== // ===== task-778 .VI [C] ===== #include #include #include #include #include typedef struct { uint8_t *buffer; size_t size; // Add maps or arrays for chunks and props (simplified) } VIParser; VIParser* vi_parser_new(const char* filename) { VIParser* parser = malloc(sizeof(VIParser)); FILE* f = fopen(filename, "rb"); fseek(f, 0, SEEK_END); parser->size = ftell(f); fseek(f, 0, SEEK_SET); parser->buffer = malloc(parser->size); fread(parser->buffer, 1, parser->size, f); fclose(f); // Parse (similar logic, but in C: use memcpy for big-endian swaps if needed) // ... (implement parse, store props in struct fields or a map) return parser; } void vi_parser_print_properties(VIParser* parser) { // Print props (e.g., printf for each) printf("{\"fileType\": \"LVIN\", ...}\n"); // Placeholder } void vi_parser_write(VIParser* parser, const char* output_filename) { FILE* f = fopen(output_filename, "wb"); fwrite(parser->buffer, 1, parser->size, f); fclose(f); } void vi_parser_free(VIParser* parser) { free(parser->buffer); free(parser); } // Usage: VIParser* p = vi_parser_new("example.vi"); vi_parser_print_properties(p); vi_parser_write(p, "output.vi"); vi_parser_free(p); // ===== end task-778 .VI ===== // ===== task-779 .VCMZ [C] ===== #include #include #include #include // Link with libzip: e.g., apt install libzip-dev, compile with -lzip typedef struct { char* filepath; char* properties[7][2]; // Static properties char** contents; // Dynamic contents list int contents_count; } VMCZHandler; void init_VMCZHandler(VMCZHandler* handler, char* filepath) { handler->filepath = strdup(filepath); handler->properties[0][0] = "File Extension"; handler->properties[0][1] = ".vmcz"; handler->properties[1][0] = "Archive Type"; handler->properties[1][1] = "ZIP-based compression format"; handler->properties[2][0] = "Extractable"; handler->properties[2][1] = "Yes"; handler->properties[3][0] = "Internal Structure"; handler->properties[3][1] = "Folders: Virtual Machines, Virtual Hard Disks (optional Snapshots)"; handler->properties[4][0] = "Purpose"; handler->properties[4][1] = "Sharing and transferring virtual machines between Hyper-V environments"; handler->properties[5][0] = "Import Mechanism"; handler->properties[5][1] = "Triggers vmimport.exe on open in Hyper-V"; handler->properties[6][0] = NULL; // End handler->contents = NULL; handler->contents_count = 0; } void read_VMCZ(VMCZHandler* handler) { zip_t* za = zip_open(handler->filepath, ZIP_RDONLY, NULL); if (!za) { printf("Error: Not a valid .VMCZ (ZIP) file\n"); return; } int num_entries = zip_get_num_entries(za, 0); handler->contents = malloc(num_entries * sizeof(char*)); for (int i = 0; i < num_entries; i++) { const char* name = zip_get_name(za, i, 0); handler->contents[i] = strdup(name); } handler->contents_count = num_entries; zip_close(za); } void write_VMCZ(VMCZHandler* handler, char* output_path) { zip_t* za = zip_open(output_path, ZIP_CREATE | ZIP_TRUNCATE, NULL); if (!za) { printf("Error creating .VMCZ\n"); return; } // Demo contents; add real data as needed zip_source_t* src = zip_source_buffer(za, "", 0, 0); zip_file_add(za, "Virtual Machines/example.vmcx", src, ZIP_FL_OVERWRITE); src = zip_source_buffer(za, "", 0, 0); zip_file_add(za, "Virtual Machines/example.vmrs", src, ZIP_FL_OVERWRITE); src = zip_source_buffer(za, "", 0, 0); zip_file_add(za, "Virtual Hard Disks/example.vhdx", src, ZIP_FL_OVERWRITE); zip_close(za); printf("Written new .VMCZ to %s\n", output_path); } void print_properties(VMCZHandler* handler) { for (int i = 0; handler->properties[i][0]; i++) { printf("%s: %s\n", handler->properties[i][0], handler->properties[i][1]); } printf("Contents:\n"); for (int i = 0; i < handler->contents_count; i++) { printf(" - %s\n", handler->contents[i]); } } void free_VMCZHandler(VMCZHandler* handler) { free(handler->filepath); for (int i = 0; i < handler->contents_count; i++) { free(handler->contents[i]); } free(handler->contents); } // Example usage: // int main() { // VMCZHandler handler; // init_VMCZHandler(&handler, "example.vmcz"); // read_VMCZ(&handler); // print_properties(&handler); // write_VMCZ(&handler, "new.vmcz"); // free_VMCZHandler(&handler); // return 0; // } // ===== end task-779 .VCMZ ===== // ===== task-780 .VMDK [C++] ===== #include #include #include #include #include #include #include class VMDKHandler { private: std::string filepath; std::map properties; std::vector> extents; std::map ddb; bool is_sparse = false; std::vector file_content; void parse_sparse_header(const char* data) { uint32_t magic = *(uint32_t*)(data + 0); if (magic != 0x4b444d56) return; is_sparse = true; properties["magicNumber"] = std::to_string(magic); properties["version"] = std::to_string(*(uint32_t*)(data + 4)); properties["flags"] = std::to_string(*(uint32_t*)(data + 8)); properties["capacity"] = std::to_string(*(uint64_t*)(data + 12)); properties["grainSize"] = std::to_string(*(uint64_t*)(data + 20)); properties["descriptorOffset"] = std::to_string(*(uint64_t*)(data + 28)); properties["descriptorSize"] = std::to_string(*(uint64_t*)(data + 36)); properties["numGTEsPerGT"] = std::to_string(*(uint32_t*)(data + 44)); properties["rgdOffset"] = std::to_string(*(uint64_t*)(data + 48)); properties["gdOffset"] = std::to_string(*(uint64_t*)(data + 56)); properties["overHead"] = std::to_string(*(uint64_t*)(data + 64)); properties["uncleanShutdown"] = std::to_string(static_cast(*(uint8_t*)(data + 72))); properties["singleEndLineChar"] = std::string(1, *(char*)(data + 73)); properties["nonEndLineChar"] = std::string(1, *(char*)(data + 74)); properties["doubleEndLineChar1"] = std::string(1, *(char*)(data + 75)); properties["doubleEndLineChar2"] = std::string(1, *(char*)(data + 76)); properties["compressAlgorithm"] = std::to_string(*(uint16_t*)(data + 77)); } void parse_descriptor(const std::string& text) { std::istringstream iss(text); std::string line; while (std::getline(iss, line)) { line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); if (line.empty() || line[0] == '#') continue; if (line.find("RW ") == 0 || line.find("RDONLY ") == 0 || line.find("NOACCESS ") == 0) { std::map extent; std::istringstream ext_iss(line); ext_iss >> extent["access"] >> extent["sizeInSectors"] >> extent["type"]; std::string filename; ext_iss >> filename; filename.erase(remove(filename.begin(), filename.end(), '"'), filename.end()); extent["filename"] = filename; std::string offset; if (ext_iss >> offset) extent["offset"] = offset; else extent["offset"] = "0"; extents.push_back(extent); } else if (line.find("ddb.") == 0) { size_t eq_pos = line.find(" = "); if (eq_pos != std::string::npos) { std::string key = line.substr(4, eq_pos - 4); std::string value = line.substr(eq_pos + 3); value.erase(remove(value.begin(), value.end(), '"'), value.end()); ddb[key] = value; } } else if (line.find('=') != std::string::npos) { size_t eq_pos = line.find('='); std::string key = line.substr(0, eq_pos); key.erase(key.find_last_not_of(" \t") + 1); std::string value = line.substr(eq_pos + 1); value.erase(0, value.find_first_not_of(" \t")); value.erase(remove(value.begin(), value.end(), '"'), value.end()); properties[key] = value; } } } public: VMDKHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); file_content.resize(size); file.read(file_content.data(), size); const char* data = file_content.data(); if (size >= 512) { parse_sparse_header(data); if (is_sparse) { uint64_t desc_offset = std::stoull(properties["descriptorOffset"]) * 512; uint64_t desc_size = std::stoull(properties["descriptorSize"]) * 512; if (desc_offset > 0 && desc_size > 0 && desc_offset + desc_size <= size) { std::string desc_text(data + desc_offset, desc_size); parse_descriptor(desc_text); } return; } } std::string text(file_content.begin(), file_content.end()); parse_descriptor(text); } void print_properties() { std::cout << "{\n"; for (const auto& p : properties) { std::cout << " \"" << p.first << "\": \"" << p.second << "\",\n"; } std::cout << " \"extents\": [\n"; for (const auto& ext : extents) { std::cout << " {\n"; for (const auto& e : ext) { std::cout << " \"" << e.first << "\": \"" << e.second << "\",\n"; } std::cout << " },\n"; } std::cout << " ],\n"; std::cout << " \"ddb\": {\n"; for (const auto& d : ddb) { std::cout << " \"" << d.first << "\": \"" << d.second << "\",\n"; } std::cout << " }\n"; std::cout << "}\n"; } void write(const std::string& new_filepath = "") { std::string out_path = new_filepath.empty() ? filepath : new_filepath; std::ofstream out(out_path, std::ios::binary); out.write(file_content.data(), file_content.size()); // Extend for modifications by updating file_content } }; // Usage example: // int main() { // VMDKHandler handler("example.vmdk"); // handler.read(); // handler.print_properties(); // handler.write("modified.vmdk"); // return 0; // } // ===== end task-780 .VMDK ===== // ===== task-781 .VMG [C++] ===== #include #include #include #include #include #include #include class VMGHandler { private: std::string filepath; std::map properties; public: VMGHandler(const std::string& fp) : filepath(fp) { readAndDecode(); } void readAndDecode() { std::wifstream file(filepath, std::ios::binary); file.imbue(std::locale(file.getloc(), new std::codecvt_utf16)); std::vector lines; std::wstring wline; while (std::getline(file, wline)) { std::wstring_convert> converter; lines.push_back(converter.to_bytes(wline)); } properties = parseVMG(lines); } std::map parseVMG(const std::vector& lines) { std::map props; props["VERSION"] = ""; props["X-IRMC-STATUS"] = ""; props["X-IRMC-BOX"] = ""; props["Sender Name"] = ""; props["Sender Telephone"] = ""; props["Recipient Name"] = ""; props["Recipient Telephone"] = ""; props["Date"] = ""; props["Message Text"] = ""; props["From"] = ""; props["To"] = ""; props["Subject"] = ""; props["Message-ID"] = ""; props["Content-Type"] = ""; props["Priority"] = ""; props["Attachments"] = ""; std::string currentSection = ""; std::vector bodyText; for (const auto& line : lines) { std::string trimmed = line; // Trim logic (remove leading/trailing spaces) size_t start = trimmed.find_first_not_of(" \t"); if (start == std::string::npos) continue; trimmed = trimmed.substr(start); size_t end = trimmed.find_last_not_of(" \t"); trimmed = trimmed.substr(0, end + 1); if (trimmed.find("BEGIN:") == 0) { currentSection = trimmed.substr(6); } else if (trimmed.find("END:") == 0) { currentSection = ""; } else if (currentSection == "VMSG" && trimmed.find(':') != std::string::npos) { size_t pos = trimmed.find(':'); std::string key = trimmed.substr(0, pos); std::string value = trimmed.substr(pos + 1); if (props.count(key)) props[key] = value; } else if (currentSection.find("VCARD") == 0 && trimmed.find(':') != std::string::npos) { size_t pos = trimmed.find(':'); std::string key = trimmed.substr(0, pos); std::string value = trimmed.substr(pos + 1); if (key == "N") props["Sender Name"] = value; if (key == "TEL") props["Sender Telephone"] = value; } else if (currentSection.find("VENV") == 0 && trimmed.find(':') != std::string::npos) { if (currentSection.find("VCARD") != std::string::npos) { size_t pos = trimmed.find(':'); std::string key = trimmed.substr(0, pos); std::string value = trimmed.substr(pos + 1); if (key == "N") props["Recipient Name"] = value; if (key == "TEL") props["Recipient Telephone"] = value; } } else if (currentSection == "VBODY") { if (trimmed.find("Date:") == 0) { props["Date"] = trimmed.substr(5); } else if (!trimmed.empty()) { bodyText.push_back(trimmed); } } } props["Message Text"] = ""; for (const auto& bt : bodyText) { props["Message Text"] += bt + "\n"; } if (!props["Message Text"].empty()) props["Message Text"].pop_back(); // Remove trailing \n return props; } void printProperties() { std::cout << "VMG Properties:" << std::endl; for (const auto& pair : properties) { if (!pair.second.empty()) { std::cout << pair.first << ": " << pair.second << std::endl; } } } void write(const std::string& newFilepath = "") { std::string target = newFilepath.empty() ? filepath : newFilepath; std::wstring content = buildVMGContent(); std::wofstream file(target, std::ios::binary); file.imbue(std::locale(file.getloc(), new std::codecvt_utf16)); file << content; } std::wstring buildVMGContent() { std::wstring_convert> converter; std::string narrowContent = "BEGIN:VMSG\n"; if (!properties["VERSION"].empty()) narrowContent += "VERSION:" + properties["VERSION"] + "\n"; if (!properties["X-IRMC-STATUS"].empty()) narrowContent += "X-IRMC-STATUS:" + properties["X-IRMC-STATUS"] + "\n"; if (!properties["X-IRMC-BOX"].empty()) narrowContent += "X-IRMC-BOX:" + properties["X-IRMC-BOX"] + "\n"; narrowContent += "BEGIN:VCARD\n"; if (!properties["VERSION"].empty()) narrowContent += "VERSION:" + properties["VERSION"] + "\n"; if (!properties["Sender Name"].empty()) narrowContent += "N:" + properties["Sender Name"] + "\n"; if (!properties["Sender Telephone"].empty()) narrowContent += "TEL:" + properties["Sender Telephone"] + "\n"; narrowContent += "END:VCARD\n"; narrowContent += "BEGIN:VENV\n"; narrowContent += "BEGIN:VCARD\n"; if (!properties["VERSION"].empty()) narrowContent += "VERSION:" + properties["VERSION"] + "\n"; if (!properties["Recipient Name"].empty()) narrowContent += "N:" + properties["Recipient Name"] + "\n"; if (!properties["Recipient Telephone"].empty()) narrowContent += "TEL:" + properties["Recipient Telephone"] + "\n"; narrowContent += "END:VCARD\n"; narrowContent += "BEGIN:VBODY\n"; if (!properties["Date"].empty()) narrowContent += "Date:" + properties["Date"] + "\n"; narrowContent += properties["Message Text"] + "\n"; narrowContent += "END:VBODY\n"; narrowContent += "END:VENV\n"; narrowContent += "END:VMSG\n"; return converter.from_bytes(narrowContent); } }; // Example usage: // int main() { // VMGHandler handler("example.vmg"); // handler.printProperties(); // handler.write("new.vmg"); // return 0; // } // ===== end task-781 .VMG ===== // ===== task-782 .VMX [C++] ===== #include #include #include #include #include class VMXHandler { private: std::string filepath; std::map properties; public: VMXHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath); if (!file.is_open()) { throw std::runtime_error("File " + filepath + " not found."); } std::string line; while (std::getline(file, line)) { line.erase(std::remove_if(line.begin(), line.end(), isspace), line.end()); // Trim if (line.empty() || line[0] == '#') continue; size_t pos = line.find('='); if (pos != std::string::npos) { std::string key = line.substr(0, pos); std::string value = line.substr(pos + 1); // Strip quotes if (!value.empty() && (value[0] == '"' || value[0] == '\'')) value.erase(0, 1); if (!value.empty() && (value.back() == '"' || value.back() == '\'')) value.pop_back(); properties[key] = value; } } file.close(); } void printProperties() const { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::map& newProperties = {}) { for (const auto& pair : newProperties) { properties[pair.first] = pair.second; } std::ofstream file(filepath); if (!file.is_open()) { throw std::runtime_error("Unable to write to " + filepath); } for (const auto& pair : properties) { file << pair.first << " = \"" << pair.second << "\"\n"; } file.close(); } }; // Example usage: // int main() { // try { // VMXHandler handler("example.vmx"); // handler.read(); // handler.printProperties(); // std::map updates = {{"new_key", "new_value"}}; // handler.write(updates); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-782 .VMX ===== // ===== task-783 .VOB [C++] ===== #include #include #include #include #include #include #include class VOBHandler { private: std::string filepath; std::map properties; std::vector data; public: VOBHandler(const std::string& fp) : filepath(fp) {} void decodeAndRead() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { std::cerr << "Failed to open file." << std::endl; return; } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(reinterpret_cast(data.data()), size); properties = parseProperties(); printProperties(); } std::map parseProperties() { std::map props; props["directoryLocation"] = "VIDEO_TS (inferred from format)"; props["fileExtension"] = ".vob"; props["maxFileSize"] = "1 GB (specification limit)"; size_t pos = filepath.find_last_of("/\\"); std::string filename = (pos == std::string::npos) ? filepath : filepath.substr(pos + 1); props["namingConvention"] = "VTS_xx_y.VOB (inferred from filename: " + filename + ")"; props["fileSegmentation"] = (data.size() > 1073741824) ? "Segmented (exceeds 1 GB)" : "Single segment"; props["physicalLayout"] = "Contiguous allocation required"; props["companionFiles"] = ".IFO and .BUP (associated)"; props["copyProtection"] = "Potential CSS (not parsed)"; props["fileSystemCompatibility"] = "UDF/ISO 9660"; props["contiguityAndOrdering"] = "Ascending order required"; // Parse MPEG PS size_t offset = 0; bool hasNavPack = false; std::set videoStreams; std::set audioStreams; std::set subtitleStreams; while (offset + 14 < data.size()) { uint32_t packStart = (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]; if (packStart == 0x000001BA) { offset += 14; while (offset + 6 < data.size()) { uint32_t pesStart = (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]; if (pesStart == 0x000001E0) { videoStreams.insert("MPEG-2 Video"); } else if (pesStart == 0x000001BD) { uint8_t subId = data[offset + 9]; if (subId >= 0x20 && subId <= 0x3F) { subtitleStreams.insert("Subtitle"); } else if (subId == 0x80) { audioStreams.insert("AC-3"); } } else if (pesStart == 0x000001BF) { hasNavPack = true; } uint16_t pesLength = (data[offset + 4] << 8) | data[offset + 5]; offset += pesLength + 6; } } offset++; } props["hasNavigationPacks"] = hasNavPack ? "Yes" : "No"; props["numberOfVideoStreams"] = std::to_string(videoStreams.size()); props["numberOfAudioStreams"] = std::to_string(audioStreams.size()); props["numberOfSubtitleStreams"] = std::to_string(subtitleStreams.size()); return props; } void printProperties() { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& outputPath) { if (!data.empty()) { std::vector dummyHeader = {0x00, 0x00, 0x01, 0xBA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; std::vector modifiedData; modifiedData.reserve(dummyHeader.size() + data.size()); modifiedData.insert(modifiedData.end(), dummyHeader.begin(), dummyHeader.end()); modifiedData.insert(modifiedData.end(), data.begin(), data.end()); std::ofstream outFile(outputPath, std::ios::binary); outFile.write(reinterpret_cast(modifiedData.data()), modifiedData.size()); std::cout << "File written to " << outputPath << std::endl; } } }; // Example usage: // int main() { // VOBHandler handler("example.vob"); // handler.decodeAndRead(); // handler.write("modified.vob"); // return 0; // } // ===== end task-783 .VOB ===== // ===== task-784 .VPK [C++] ===== #include #include #include #include #include #include #include class VPK { private: std::vector data; std::map properties; std::string bytesToHex(const char* bytes, size_t size) { std::stringstream ss; for (size_t i = 0; i < size; ++i) { ss << std::hex << std::setfill('0') << std::setw(2) << (int)(unsigned char)bytes[i]; } return ss.str(); } std::string readString(size_t& offset) { std::string str; while (data[offset] != 0) { str += data[offset]; ++offset; } ++offset; return str; } public: VPK(const std::string& filename) { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) throw std::runtime_error("Failed to open file"); size_t size = file.tellg(); data.resize(size); file.seekg(0); file.read(data.data(), size); parse(); } void parse() { size_t offset = 0; uint32_t signature = *reinterpret_cast(&data[offset]); offset += 4; properties["signature"] = signature; uint32_t version = *reinterpret_cast(&data[offset]); offset += 4; properties["version"] = version; uint32_t treeSize = *reinterpret_cast(&data[offset]); offset += 4; properties["treeSize"] = treeSize; if (version == 2) { uint32_t fileDataSectionSize = *reinterpret_cast(&data[offset]); offset += 4; properties["fileDataSectionSize"] = fileDataSectionSize; uint32_t archiveMD5SectionSize = *reinterpret_cast(&data[offset]); offset += 4; properties["archiveMD5SectionSize"] = archiveMD5SectionSize; uint32_t otherMD5SectionSize = *reinterpret_cast(&data[offset]); offset += 4; properties["otherMD5SectionSize"] = otherMD5SectionSize; uint32_t signatureSectionSize = *reinterpret_cast(&data[offset]); offset += 4; properties["signatureSectionSize"] = signatureSectionSize; } std::vector> files; size_t treeEnd = offset + treeSize; while (offset < treeEnd) { std::string extension = readString(offset); if (extension.empty()) break; while (offset < treeEnd) { std::string path = readString(offset); if (path.empty()) break; while (offset < treeEnd) { std::string filename = readString(offset); if (filename.empty()) break; std::map fileProp; fileProp["extension"] = extension; fileProp["path"] = path; fileProp["filename"] = filename; uint32_t crc = *reinterpret_cast(&data[offset]); offset += 4; fileProp["crc"] = crc; uint16_t preloadBytes = *reinterpret_cast(&data[offset]); offset += 2; fileProp["preloadBytes"] = preloadBytes; uint16_t archiveIndex = *reinterpret_cast(&data[offset]); offset += 2; fileProp["archiveIndex"] = archiveIndex; uint32_t entryOffset = *reinterpret_cast(&data[offset]); offset += 4; fileProp["entryOffset"] = entryOffset; uint32_t entryLength = *reinterpret_cast(&data[offset]); offset += 4; fileProp["entryLength"] = entryLength; uint16_t terminator = *reinterpret_cast(&data[offset]); offset += 2; if (terminator != 0xFFFF) { throw std::runtime_error("Invalid terminator"); } if (preloadBytes > 0) { std::vector preload(data.begin() + offset, data.begin() + offset + preloadBytes); fileProp["preloadData"] = preload; offset += preloadBytes; } files.push_back(fileProp); } } } properties["files"] = files; if (version == 2) { std::vector> archiveMD5Entries; size_t md5End = offset + std::any_cast(properties["fileDataSectionSize"]) + std::any_cast(properties["archiveMD5SectionSize"]); while (offset < md5End) { std::map entry; uint32_t archiveIndex = *reinterpret_cast(&data[offset]); offset += 4; entry["archiveIndex"] = archiveIndex; uint32_t startingOffset = *reinterpret_cast(&data[offset]); offset += 4; entry["startingOffset"] = startingOffset; uint32_t count = *reinterpret_cast(&data[offset]); offset += 4; entry["count"] = count; std::string md5Checksum = bytesToHex(&data[offset], 16); entry["md5Checksum"] = md5Checksum; offset += 16; archiveMD5Entries.push_back(entry); } properties["archiveMD5Entries"] = archiveMD5Entries; uint32_t otherMD5SectionSize = std::any_cast(properties["otherMD5SectionSize"]); if (otherMD5SectionSize == 48) { std::string treeChecksum = bytesToHex(&data[offset], 16); offset += 16; properties["treeChecksum"] = treeChecksum; std::string archiveMD5SectionChecksum = bytesToHex(&data[offset], 16); offset += 16; properties["archiveMD5SectionChecksum"] = archiveMD5SectionChecksum; std::string wholeFileChecksum = bytesToHex(&data[offset], 16); offset += 16; properties["wholeFileChecksum"] = wholeFileChecksum; } uint32_t signatureSectionSize = std::any_cast(properties["signatureSectionSize"]); if (signatureSectionSize == 296) { uint32_t publicKeySize = *reinterpret_cast(&data[offset]); offset += 4; properties["publicKeySize"] = publicKeySize; std::string publicKey = bytesToHex(&data[offset], publicKeySize); offset += publicKeySize; properties["publicKey"] = publicKey; uint32_t signatureSize = *reinterpret_cast(&data[offset]); offset += 4; properties["signatureSize"] = signatureSize; std::string signature = bytesToHex(&data[offset], signatureSize); offset += signatureSize; properties["signature"] = signature; } } } void printProperties() { // For brevity, print as JSON-like string; extend for full output std::cout << "Properties: " << std::endl; for (const auto& [key, value] : properties) { std::cout << key << ": " << std::any_cast(value) << std::endl; // Adapt for types } } void write(const std::string& filename) { std::ofstream file(filename, std::ios::binary); if (!file) throw std::runtime_error("Failed to write file"); file.write(data.data(), data.size()); } }; // ===== end task-784 .VPK ===== // ===== task-785 .VPM [C++] ===== #include #include #include #include #include class VPMFile { private: std::string filename; std::string signature; std::string version; uint8_t timestamp[7]; // sec, min, hr, day, mon, year1, year2 uint16_t firstAudio; uint8_t langId; std::vector> phrases; // numSamples, samplePtr std::vector audioData; uint8_t checksum; std::vector data; public: VPMFile(const std::string& fn) : filename(fn) {} bool read() { std::ifstream file(filename, std::ios::binary | std::ios::ate); if (!file) return false; size_t size = file.tellg(); file.seekg(0); data.resize(size); file.read(reinterpret_cast(data.data()), size); file.close(); // Signature signature.assign(data.begin(), data.begin() + 6); // Version version.assign(data.begin() + 6, data.begin() + 9); // Timestamp memcpy(timestamp, data.data() + 9, 7); // First audio (little-endian) firstAudio = data[16] | (data[17] << 8); // Lang ID langId = data[18]; // Phrases size_t offset = 19; while (offset + 3 < firstAudio) { uint16_t numSamples = data[offset] | (data[offset + 1] << 8); uint16_t samplePtr = data[offset + 2] | (data[offset + 3] << 8); phrases.emplace_back(numSamples, samplePtr); offset += 4; } // Audio data audioData.assign(data.begin() + firstAudio, data.end() - 1); // Checksum checksum = data.back(); return true; } void printProperties() const { std::cout << "Signature: " << signature << std::endl; std::cout << "Version: " << version << std::endl; std::cout << "Timestamp: " << static_cast(timestamp[2]) << ":" << static_cast(timestamp[1]) << ":" << static_cast(timestamp[0]) << " " << static_cast(timestamp[3]) << "/" << static_cast(timestamp[4]) << "/" << (2000 + static_cast(timestamp[5])) << " (redundant: " << static_cast(timestamp[6]) << ")" << std::endl; std::cout << "First Audio Pointer: " << firstAudio << std::endl; std::cout << "Language ID: " << static_cast(langId) << std::endl; std::cout << "Phrases:" << std::endl; for (size_t i = 0; i < phrases.size(); ++i) { auto [num, ptr] = phrases[i]; std::cout << " Phrase " << (i + 1) << ": Num Samples = " << num << ", First Sample Index = " << ptr << std::endl; } std::cout << "Audio Data Length: " << audioData.size() << " bytes" << std::endl; uint8_t sum = 0; for (auto b : data) sum = (sum + b) % 256; std::cout << "Checksum Valid: " << (sum == 0) << std::endl; std::cout << "File Size: " << data.size() << " bytes" << std::endl; } bool write(const std::string& newFilename) const { if (data.empty()) return false; std::ofstream file(newFilename, std::ios::binary); if (!file) return false; file.write(reinterpret_cast(data.data()), data.size()); file.close(); return true; } }; int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Usage: " << argv[0] << " " << std::endl; return 1; } VPMFile vpm(argv[1]); if (!vpm.read()) { std::cerr << "Failed to read file." << std::endl; return 1; } vpm.printProperties(); // To write: vpm.write("output.vpm"); return 0; } // ===== end task-785 .VPM ===== // ===== task-786 .VPP [C] ===== #include #include #include #include #define ALIGNMENT 2048 typedef struct { char *filename; uint32_t size; } VPPFileEntry; typedef struct { uint32_t magic; uint32_t version; uint32_t num_files; uint32_t total_size; char *header_padding_desc; char *dir_offset_desc; char *dir_entry_size_desc; char *compression_desc; char *dir_structure_desc; char *timestamps_desc; char *endianness_desc; char *file_alignment_desc; char *padding_desc; VPPFileEntry *files; uint32_t first_data_offset; } VPPProperties; void read_vpp(const char *filepath, VPPProperties *props) { FILE *f = fopen(filepath, "rb"); if (!f) { perror("Failed to open file"); return; } fseek(f, 0, SEEK_END); long file_size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(file_size); fread(data, 1, file_size, f); fclose(f); uint32_t offset = 0; memcpy(&props->magic, data + offset, 4); offset += 4; memcpy(&props->version, data + offset, 4); offset += 4; memcpy(&props->num_files, data + offset, 4); offset += 4; memcpy(&props->total_size, data + offset, 4); offset += 4; props->header_padding_desc = "2032 bytes of zeros"; offset += 2032; props->dir_offset_desc = "0x0800"; props->dir_entry_size_desc = "64 bytes"; props->compression_desc = "None"; props->dir_structure_desc = "Flat"; props->timestamps_desc = "Absent"; props->endianness_desc = "Little-endian"; props->file_alignment_desc = "2048 bytes"; props->padding_desc = "Zero bytes"; props->files = malloc(props->num_files * sizeof(VPPFileEntry)); for (uint32_t i = 0; i < props->num_files; i++) { props->files[i].filename = malloc(61); strncpy(props->files[i].filename, (char *)(data + offset), 60); props->files[i].filename[60] = '\0'; offset += 60; memcpy(&props->files[i].size, data + offset, 4); offset += 4; } uint32_t directory_size = props->num_files * 64; props->first_data_offset = ((2048 + directory_size + ALIGNMENT - 1) / ALIGNMENT) * ALIGNMENT; free(data); } void print_vpp_properties(const VPPProperties *props) { printf("Magic Signature: 0x%X\n", props->magic); printf("Version Number: 0x%X\n", props->version); printf("Number of Files: %u\n", props->num_files); printf("Total File Size: %u\n", props->total_size); printf("Header Padding: %s\n", props->header_padding_desc); printf("Directory Offset: %s\n", props->dir_offset_desc); printf("Directory Entry Size: %s\n", props->dir_entry_size_desc); printf("Compression: %s\n", props->compression_desc); printf("Directory Structure: %s\n", props->dir_structure_desc); printf("Timestamps: %s\n", props->timestamps_desc); printf("Endianness: %s\n", props->endianness_desc); printf("File Data Alignment: %s\n", props->file_alignment_desc); printf("Padding in File Data: %s\n", props->padding_desc); printf("First File Data Offset: %u\n", props->first_data_offset); printf("Files:\n"); for (uint32_t i = 0; i < props->num_files; i++) { printf(" - Filename: %s, Size: %u bytes\n", props->files[i].filename, props->files[i].size); } } void free_vpp_properties(VPPProperties *props) { for (uint32_t i = 0; i < props->num_files; i++) { free(props->files[i].filename); } free(props->files); } void write_vpp(const char *output_path, VPPFileEntry *files, uint32_t num_files, uint8_t **file_datas) { FILE *f = fopen(output_path, "wb"); if (!f) { perror("Failed to open output file"); return; } // Temp header uint32_t magic = 0x51890ACE; uint32_t version = 1; uint32_t total_size = 0; // Temp fwrite(&magic, 4, 1, f); fwrite(&version, 4, 1, f); fwrite(&num_files, 4, 1, f); fwrite(&total_size, 4, 1, f); // Padding uint8_t padding[2032] = {0}; fwrite(padding, 2032, 1, f); // Directory for (uint32_t i = 0; i < num_files; i++) { uint8_t filename_padded[60] = {0}; strncpy((char *)filename_padded, files[i].filename, 59); fwrite(filename_padded, 60, 1, f); fwrite(&files[i].size, 4, 1, f); } // File data long current_pos = ftell(f); long aligned_pos = ((current_pos + ALIGNMENT - 1) / ALIGNMENT) * ALIGNMENT; uint8_t align_padding[ALIGNMENT] = {0}; fwrite(align_padding, aligned_pos - current_pos, 1, f); for (uint32_t i = 0; i < num_files; i++) { fwrite(file_datas[i], files[i].size, 1, f); long data_end = ftell(f); long padded_end = ((data_end + ALIGNMENT - 1) / ALIGNMENT) * ALIGNMENT; fwrite(align_padding, padded_end - data_end, 1, f); } // Update total size total_size = ftell(f); fseek(f, 12, SEEK_SET); fwrite(&total_size, 4, 1, f); fclose(f); } // ===== end task-786 .VPP ===== // ===== task-787 .VPR [C++] ===== #include #include #include #include #include #include namespace fs = std::filesystem; using json = nlohmann::json; class VprHandler { private: std::string filepath; json data; public: VprHandler(const std::string& fp = "") : filepath(fp) { if (!fp.empty()) { read(fp); } } void read(const std::string& fp) { filepath = fp; zip_t* za = zip_open(fp.c_str(), 0, 'r'); if (za) { int index = zip_entry_open(za, "Project/sequence.json"); if (index == 0) { void* buf = nullptr; size_t bufsize = 0; zip_entry_read(za, &buf, &bufsize); std::string jsonStr(static_cast(buf), bufsize); data = json::parse(jsonStr); free(buf); zip_entry_close(za); } else { throw std::runtime_error("Project/sequence.json not found."); } zip_close(za); } else { throw std::runtime_error("Failed to open ZIP."); } } void printProperties() { if (!data.is_null()) { std::cout << data.dump(4) << std::endl; } else { std::cout << "No data loaded." << std::endl; } } void write(const std::string& outputFilepath) { if (data.is_null()) { throw std::runtime_error("No data to write."); } fs::create_directory("temp_vpr/Project"); std::ofstream jsonFile("temp_vpr/Project/sequence.json"); jsonFile << data.dump(4); jsonFile.close(); zip_t* za = zip_open(outputFilepath.c_str(), ZIP_DEFAULT_COMPRESSION_LEVEL, 'w'); if (za) { addToZip(za, "temp_vpr", ""); zip_close(za); } else { throw std::runtime_error("Failed to create ZIP."); } fs::remove_all("temp_vpr"); } private: void addToZip(zip_t* za, const std::string& dir, const std::string& base) { for (const auto& entry : fs::directory_iterator(dir)) { std::string path = entry.path().string(); std::string relPath = base + entry.path().filename().string(); if (entry.is_directory()) { addToZip(za, path, relPath + "/"); } else { zip_entry_open(za, relPath.c_str()); std::ifstream file(path, std::ios::binary); std::vector buffer(std::istreambuf_iterator(file), {}); zip_entry_write(za, buffer.data(), buffer.size()); zip_entry_close(za); } } } }; // Example usage: // int main() { // try { // VprHandler handler("example.vpr"); // handler.printProperties(); // handler.write("modified.vpr"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-787 .VPR ===== // ===== task-788 .VQM [C++] ===== #include #include #include #include #include #include #include class VQMParser { private: std::string content; std::map properties; void parse() { properties["File Extension"] = ".vqm"; properties["Content Type"] = "Text"; properties["Syntax"] = std::regex_search(content, std::regex("module")) ? "Structural Verilog HDL" : "Unknown"; std::smatch matches; std::regex hierarchyRegex("\\\\[\\\\w:]+"); std::string hierarchyStr; int count = 0; auto words_begin = std::sregex_iterator(content.begin(), content.end(), hierarchyRegex); auto words_end = std::sregex_iterator(); for (std::sregex_iterator i = words_begin; i != words_end && count < 5; ++i) { if (count > 0) hierarchyStr += ", "; hierarchyStr += (*i).str(); count++; } if (count > 0) hierarchyStr += "..."; properties["Hierarchy Examples"] = !hierarchyStr.empty() ? hierarchyStr : "None found"; std::regex primitiveRegex("(\\w+)\\s+\\w+\\s*\\("); std::set primitives; for (std::sregex_iterator i = std::sregex_iterator(content.begin(), content.end(), primitiveRegex); i != std::sregex_iterator(); ++i) { primitives.insert((*i)[1].str()); } std::string primStr; for (auto it = primitives.begin(); it != primitives.end(); ++it) { if (!primStr.empty()) primStr += ", "; primStr += *it; } properties["Primitives"] = !primStr.empty() ? primStr : "None found"; std::regex paramRegex("defparam\\s+[\\w\\\\|~.]+\\.(\\w+)\\s*="); std::set params; for (std::sregex_iterator i = std::sregex_iterator(content.begin(), content.end(), paramRegex); i != std::sregex_iterator(); ++i) { params.insert((*i)[1].str()); } std::string paramStr; for (auto it = params.begin(); it != params.end(); ++it) { if (!paramStr.empty()) paramStr += ", "; paramStr += *it; } properties["Parameters"] = !paramStr.empty() ? paramStr : "None found"; std::regex signalRegex("__ALT_INV__[\\w~]+"); std::string signalStr; count = 0; for (std::sregex_iterator i = std::sregex_iterator(content.begin(), content.end(), signalRegex); i != std::sregex_iterator() && count < 5; ++i) { if (count > 0) signalStr += ", "; signalStr += (*i).str(); count++; } if (count > 0) signalStr += "..."; properties["Special Signals"] = !signalStr.empty() ? signalStr : "None found"; std::regex initRegex("init_file\\s*=\\s*\"([^\"]+\\.hex)\""); std::vector inits; for (std::sregex_iterator i = std::sregex_iterator(content.begin(), content.end(), initRegex); i != std::sregex_iterator(); ++i) { inits.push_back((*i)[1].str()); } std::string initStr; for (auto& init : inits) { if (!initStr.empty()) initStr += ", "; initStr += init; } properties["Initialization Files"] = !initStr.empty() ? initStr : "None found"; std::regex deviceRegex("(cyclonev_|stratix_|\\w+)_"); std::smatch deviceMatch; if (std::regex_search(content, deviceMatch, deviceRegex)) { std::string dev = deviceMatch[1].str(); dev.erase(std::remove(dev.begin(), dev.end(), '_'), dev.end()); properties["Target Device Family"] = dev; } else { properties["Target Device Family"] = "Unknown"; } std::string constStr; if (content.find("vcc") != std::string::npos) constStr += "vcc"; if (content.find("gnd") != std::string::npos) { if (!constStr.empty()) constStr += ", "; constStr += "gnd"; } properties["Constants"] = !constStr.empty() ? constStr : "None found"; } public: VQMParser(const std::string& filename) { std::ifstream file(filename); if (file) { std::string line; while (std::getline(file, line)) { content += line + "\n"; } parse(); } else { throw std::runtime_error("Failed to open file"); } } void printProperties() const { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& filename) const { std::ofstream out(filename); if (out) { out << content; } else { throw std::runtime_error("Failed to write file"); } } }; // Example usage: // int main() { // try { // VQMParser parser("example.vqm"); // parser.printProperties(); // parser.write("output.vqm"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-788 .VQM ===== // ===== task-789 .VRB [C++] ===== #include #include #include #include #include #include #include // Assume tinyxml2 library for XML parsing; include via external dependency if needed. using namespace std; using namespace tinyxml2; class VRBFile { private: string filepath; map, vector>>> properties; // Use variant for mixed types (C++17+). public: VRBFile(const string& fp) : filepath(fp) {} void decodeRead() { ifstream file(filepath, ios::binary); if (!file) throw runtime_error("Cannot open file."); stringstream buffer; buffer << file.rdbuf(); string data = buffer.str(); string start = ""; string end = ""; vector positions; size_t pos = 0; while ((pos = data.find(start, pos)) != string::npos) { size_t endPos = data.find(end, pos) + end.length(); string block = data.substr(pos, endPos - pos); positions.push_back(block); pos = endPos; } if (positions.empty()) throw runtime_error("No OibSummary found in the file."); string lastBlock = positions.back(); XMLDocument doc; doc.Parse(lastBlock.c_str()); if (doc.Error()) throw runtime_error("XML parsing error."); XMLElement* root = doc.RootElement(); vector tags = {"Backup", "Point", "Storage", "OIB", "Object", "TargetHost", "PrevFileName", "BackupVersion", "LogBackupInfo", "SourceHost"}; for (const string& tag : tags) { XMLElement* elem = root->FirstChildElement(tag.c_str()); if (elem) { if (tag == "PrevFileName" || tag == "BackupVersion" || tag == "LogBackupInfo") { properties[tag] = elem->GetText() ? string(elem->GetText()) : ""; } else { map attrs; for (const XMLAttribute* attr = elem->FirstAttribute(); attr; attr = attr->Next()) { attrs[attr->Name()] = attr->Value(); } properties[tag] = attrs; } } } XMLElement* oibFilesElem = root->FirstChildElement("OibFiles"); if (oibFilesElem) { vector> oibFiles; for (XMLElement* fileElem = oibFilesElem->FirstChildElement("File"); fileElem; fileElem = fileElem->NextSiblingElement("File")) { map fileProps; for (const XMLAttribute* attr = fileElem->FirstAttribute(); attr; attr = attr->Next()) { fileProps[attr->Name()] = attr->Value(); } oibFiles.push_back(fileProps); } properties["OibFiles"] = oibFiles; } } void printProperties() { for (const auto& [key, val] : properties) { cout << key << ": "; if (holds_alternative(val)) { cout << get(val); } else if (holds_alternative>(val)) { const auto& attrs = get>(val); for (const auto& [a, v] : attrs) { cout << a << "=" << v << " "; } } else if (holds_alternative>>(val)) { const auto& files = get>>(val); cout << "["; for (const auto& file : files) { for (const auto& [a, v] : file) { cout << a << "=" << v << " "; } cout << "; "; } cout << "]"; } cout << endl; } } void write(const string& newFilepath, const map, vector>>>& newProperties = {}) { if (!newProperties.empty()) { properties = newProperties; } XMLDocument doc; XMLElement* root = doc.NewElement("OibSummary"); doc.InsertFirstChild(root); for (const auto& [key, val] : properties) { XMLElement* sub = doc.NewElement(key.c_str()); if (holds_alternative>>(val)) { const auto& files = get>>(val); for (const auto& fileProps : files) { XMLElement* fileElem = doc.NewElement("File"); for (const auto& [attr, v] : fileProps) { fileElem->SetAttribute(attr.c_str(), v.c_str()); } sub->InsertEndChild(fileElem); } } else if (holds_alternative>(val)) { const auto& attrs = get>(val); for (const auto& [attr, v] : attrs) { sub->SetAttribute(attr.c_str(), v.c_str()); } } else if (holds_alternative(val)) { sub->SetText(get(val).c_str()); } root->InsertEndChild(sub); } // Note: This writes only the metadata XML, not a full .VRB file, as the complete binary structure is proprietary. ofstream out(newFilepath); XMLPrinter printer; doc.Accept(&printer); out << printer.CStr(); out.close(); } }; // Example usage: // int main() { // VRBFile vrb("example.vrb"); // vrb.decodeRead(); // vrb.printProperties(); // vrb.write("new.vrb"); // return 0; // } // ===== end task-789 .VRB ===== // ===== task-790 .VS [C++] ===== #include #include #include #include #include class VSFileHandler { private: std::string filepath; std::string content; struct stat fileStat; public: VSFileHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::in); if (file) { content.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); } stat(filepath.c_str(), &fileStat); } void decodeAndPrint() { if (content.empty()) { read(); } std::cout << "File Name: " << filepath.substr(filepath.find_last_of("/\\") + 1) << std::endl; std::cout << "File Size: " << fileStat.st_size << " bytes" << std::endl; std::cout << "Creation Timestamp: " << std::ctime(&fileStat.st_ctime); std::cout << "Last Modification Timestamp: " << std::ctime(&fileStat.st_mtime); std::cout << "Last Access Timestamp: " << std::ctime(&fileStat.st_atime); std::cout << "File Permissions: " << std::oct << (fileStat.st_mode & 0777) << std::endl; std::cout << "Owner ID: " << fileStat.st_uid << std::endl; std::cout << "Group ID: " << fileStat.st_gid << std::endl; std::cout << "Shader Source Code:\n" << content << std::endl; } void write(const std::string& newContent) { std::ofstream file(filepath, std::ios::out); if (file) { file << newContent; file.close(); std::cout << "File written successfully." << std::endl; } } }; // Example usage: // int main() { // VSFileHandler handler("example.vs"); // handler.decodeAndPrint(); // handler.write("#version 330 core\n..."); // return 0; // } // ===== end task-790 .VS ===== // ===== task-791 .VSD [C] ===== #include #include #include #include #define HEADER_SIZE 512 typedef struct { uint8_t signature[8]; uint8_t clsid[16]; uint16_t minor_version; uint16_t major_version; uint16_t byte_order; uint16_t sector_shift; uint16_t mini_sector_shift; uint8_t reserved[6]; uint32_t num_directory_sectors; uint32_t num_fat_sectors; uint32_t first_directory_sector; uint32_t transaction_signature; uint32_t mini_stream_cutoff; uint32_t first_mini_fat_sector; uint32_t num_mini_fat_sectors; uint32_t first_difat_sector; uint32_t num_difat_sectors; uint32_t difat[109]; } VSDHeader; void read_and_decode(const char* filepath, VSDHeader* header) { FILE* file = fopen(filepath, "rb"); if (!file) { perror("Failed to open file"); exit(1); } uint8_t buffer[HEADER_SIZE]; if (fread(buffer, 1, HEADER_SIZE, file) < HEADER_SIZE) { fprintf(stderr, "File too small\n"); fclose(file); exit(1); } fclose(file); memcpy(header->signature, buffer, 8); memcpy(header->clsid, buffer + 8, 16); memcpy(&header->minor_version, buffer + 24, 2); memcpy(&header->major_version, buffer + 26, 2); memcpy(&header->byte_order, buffer + 28, 2); memcpy(&header->sector_shift, buffer + 30, 2); memcpy(&header->mini_sector_shift, buffer + 32, 2); memcpy(header->reserved, buffer + 34, 6); memcpy(&header->num_directory_sectors, buffer + 40, 4); memcpy(&header->num_fat_sectors, buffer + 44, 4); memcpy(&header->first_directory_sector, buffer + 48, 4); memcpy(&header->transaction_signature, buffer + 52, 4); memcpy(&header->mini_stream_cutoff, buffer + 56, 4); memcpy(&header->first_mini_fat_sector, buffer + 60, 4); memcpy(&header->num_mini_fat_sectors, buffer + 64, 4); memcpy(&header->first_difat_sector, buffer + 68, 4); memcpy(&header->num_difat_sectors, buffer + 72, 4); for (int i = 0; i < 109; i++) { memcpy(&header->difat[i], buffer + 76 + i * 4, 4); } print_properties(header); } void print_properties(const VSDHeader* header) { printf("Extracted .VSD Properties:\n"); printf("Header Signature: "); for (int i = 0; i < 8; i++) printf("%02X ", header->signature[i]); printf("\n"); printf("Header CLSID: "); for (int i = 0; i < 16; i++) printf("%02X ", header->clsid[i]); printf("\n"); printf("Minor Version: 0x%04X\n", header->minor_version); printf("Major Version: 0x%04X\n", header->major_version); printf("Byte Order: 0x%04X\n", header->byte_order); printf("Sector Shift: 0x%04X\n", header->sector_shift); printf("Mini Sector Shift: 0x%04X\n", header->mini_sector_shift); printf("Reserved: "); for (int i = 0; i < 6; i++) printf("%02X ", header->reserved[i]); printf("\n"); printf("Number of Directory Sectors: %u\n", header->num_directory_sectors); printf("Number of FAT Sectors: %u\n", header->num_fat_sectors); printf("First Directory Sector Location: %u\n", header->first_directory_sector); printf("Transaction Signature Number: %u\n", header->transaction_signature); printf("Mini Stream Cutoff Size: %u\n", header->mini_stream_cutoff); printf("First Mini FAT Sector Location: %u\n", header->first_mini_fat_sector); printf("Number of Mini FAT Sectors: %u\n", header->num_mini_fat_sectors); printf("First DIFAT Sector Location: %u\n", header->first_difat_sector); printf("Number of DIFAT Sectors: %u\n", header->num_difat_sectors); printf("DIFAT Array (sample): "); for (int i = 0; i < 5; i++) printf("0x%08X ", header->difat[i]); printf("... (109 entries)\n"); } void write_header(const char* filepath, const VSDHeader* header) { FILE* file = fopen(filepath, "r+b"); if (!file) { perror("Failed to open file for writing"); exit(1); } uint8_t buffer[HEADER_SIZE] = {0}; memcpy(buffer, header->signature, 8); memcpy(buffer + 8, header->clsid, 16); memcpy(buffer + 24, &header->minor_version, 2); memcpy(buffer + 26, &header->major_version, 2); memcpy(buffer + 28, &header->byte_order, 2); memcpy(buffer + 30, &header->sector_shift, 2); memcpy(buffer + 32, &header->mini_sector_shift, 2); memcpy(buffer + 34, header->reserved, 6); memcpy(buffer + 40, &header->num_directory_sectors, 4); memcpy(buffer + 44, &header->num_fat_sectors, 4); memcpy(buffer + 48, &header->first_directory_sector, 4); memcpy(buffer + 52, &header->transaction_signature, 4); memcpy(buffer + 56, &header->mini_stream_cutoff, 4); memcpy(buffer + 60, &header->first_mini_fat_sector, 4); memcpy(buffer + 64, &header->num_mini_fat_sectors, 4); memcpy(buffer + 68, &header->first_difat_sector, 4); memcpy(buffer + 72, &header->num_difat_sectors, 4); for (int i = 0; i < 109; i++) { memcpy(buffer + 76 + i * 4, &header->difat[i], 4); } fwrite(buffer, 1, HEADER_SIZE, file); fclose(file); } int main(int argc, char** argv) { if (argc < 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } VSDHeader header; read_and_decode(argv[1], &header); // To write: modify header, then write_header(argv[1], &header); return 0; } // ===== end task-791 .VSD ===== // ===== task-792 .VSDX [C++] ===== #include #include #include // Assume minizip library #include // Assume TinyXML2 library class VsdxHandler { private: std::string filePath; tinyxml2::XMLDocument coreDoc; tinyxml2::XMLDocument appDoc; public: VsdxHandler(const std::string& path) : filePath(path) { loadProperties(); } void loadProperties() { unzFile zf = unzOpen(filePath.c_str()); if (zf) { if (unzLocateFile(zf, "docProps/core.xml", 0) == UNZ_OK) { unz_file_info fileInfo; unzGetCurrentFileInfo(zf, &fileInfo, nullptr, 0, nullptr, 0, nullptr, 0); char* buffer = new char[fileInfo.uncompressed_size + 1]; unzOpenCurrentFile(zf); unzReadCurrentFile(zf, buffer, fileInfo.uncompressed_size); buffer[fileInfo.uncompressed_size] = '\0'; coreDoc.Parse(buffer); delete[] buffer; unzCloseCurrentFile(zf); } if (unzLocateFile(zf, "docProps/app.xml", 0) == UNZ_OK) { unz_file_info fileInfo; unzGetCurrentFileInfo(zf, &fileInfo, nullptr, 0, nullptr, 0, nullptr, 0); char* buffer = new char[fileInfo.uncompressed_size + 1]; unzOpenCurrentFile(zf); unzReadCurrentFile(zf, buffer, fileInfo.uncompressed_size); buffer[fileInfo.uncompressed_size] = '\0'; appDoc.Parse(buffer); delete[] buffer; unzCloseCurrentFile(zf); } unzClose(zf); } } void printProperties() { std::cout << "Core Properties:" << std::endl; if (!coreDoc.Error()) { tinyxml2::XMLElement* root = coreDoc.FirstChildElement(); for (tinyxml2::XMLElement* elem = root->FirstChildElement(); elem != nullptr; elem = elem->NextSiblingElement()) { std::cout << elem->Name() << ": " << (elem->GetText() ? elem->GetText() : "") << std::endl; } } std::cout << "\nApp Properties:" << std::endl; if (!appDoc.Error()) { tinyxml2::XMLElement* root = appDoc.FirstChildElement(); for (tinyxml2::XMLElement* elem = root->FirstChildElement(); elem != nullptr; elem = elem->NextSiblingElement()) { if (std::string(elem->Name()) != "HeadingPairs" && std::string(elem->Name()) != "TitlesOfParts") { std::cout << elem->Name() << ": " << (elem->GetText() ? elem->GetText() : "") << std::endl; } } } } void writeProperties(const std::string& outputPath, const std::string& propType, const std::string& key, const std::string& value) { // Simplified: Reload and modify in memory, then rewrite entire ZIP (complex; production code would use zip library for write) // For brevity, assume external tool or extend with minizip's zip support. std::cout << "Write operation simulated; use full zip library for production." << std::endl; loadProperties(); // Reload post-write in full impl } }; // ===== end task-792 .VSDX ===== // ===== task-795 .VSQX [C++] ===== #include #include #include class VSQXParser { private: std::string filename; tinyxml2::XMLDocument doc; public: VSQXParser(const std::string& fn) : filename(fn) { parse(); } void parse() { doc.LoadFile(filename.c_str()); } void printProperties() { std::cout << "VSQX Properties:" << std::endl; // Voicebanks tinyxml2::XMLElement* root = doc.FirstChildElement("vsqx"); if (!root) return; tinyxml2::XMLElement* vVoiceTable = root->FirstChildElement("vVoiceTable"); if (vVoiceTable) { std::cout << "\nVoicebanks:" << std::endl; tinyxml2::XMLElement* vVoice = vVoiceTable->FirstChildElement("vVoice"); while (vVoice) { std::cout << "- ID: " << (vVoice->Attribute("id") ? vVoice->Attribute("id") : "N/A") << ", Name: " << (vVoice->Attribute("name") ? vVoice->Attribute("name") : "N/A") << std::endl; vVoice = vVoice->NextSiblingElement("vVoice"); } } // Mixer tinyxml2::XMLElement* mixer = root->FirstChildElement("mixer"); if (mixer) std::cout << "\nMixer Attributes: " << mixer->GetText() << std::endl; // Master track tinyxml2::XMLElement* masterTrack = root->FirstChildElement("masterTrack"); if (masterTrack) { std::string timeSig = masterTrack->FirstChildElement("timeSig") ? masterTrack->FirstChildElement("timeSig")->GetText() : "N/A"; std::string tempo = masterTrack->FirstChildElement("tempo") ? masterTrack->FirstChildElement("tempo")->GetText() : "N/A"; std::cout << "\nMaster Track:" << std::endl; std::cout << "- Time Signature: " << timeSig << std::endl; std::cout << "- Tempo: " << tempo << std::endl; } // Tracks tinyxml2::XMLElement* track = root->FirstChildElement("vsTrack"); int trackIdx = 1; std::cout << "\nTracks:" << std::endl; while (track) { std::cout << "Track " << trackIdx << ":" << std::endl; std::string name = track->FirstChildElement("name") ? track->FirstChildElement("name")->GetText() : "N/A"; std::string playTime = track->FirstChildElement("playTime") ? track->FirstChildElement("playTime")->GetText() : "N/A"; std::cout << "- Name: " << name << std::endl; std::cout << "- Play Time: " << playTime << std::endl; tinyxml2::XMLElement* vsPart = track->FirstChildElement("vsPart"); if (vsPart) { tinyxml2::XMLElement* pStyle = vsPart->FirstChildElement("pStyle"); if (pStyle) { std::cout << "Part Style:" << std::endl; const char* props[] = {"accent", "bendDep", "bendLen", "decay", "opening", "fallPort", "risePort"}; for (const char* prop : props) { tinyxml2::XMLElement* v = pStyle->FirstChildElement("v"); std::string val = "N/A"; while (v) { if (std::string(v->Attribute("id")) == prop) { val = v->GetText() ? v->GetText() : "N/A"; break; } v = v->NextSiblingElement("v"); } std::cout << " - " << prop << ": " << val << std::endl; } } // Notes tinyxml2::XMLElement* note = vsPart->FirstChildElement("note"); int noteIdx = 1; std::cout << "Notes:" << std::endl; while (note) { std::cout << " Note " << noteIdx << ":" << std::endl; std::string t = note->FirstChildElement("t") ? note->FirstChildElement("t")->GetText() : "N/A"; std::string dur = note->FirstChildElement("dur") ? note->FirstChildElement("dur")->GetText() : "N/A"; std::string n = note->FirstChildElement("n") ? note->FirstChildElement("n")->GetText() : "N/A"; std::string v = note->FirstChildElement("v") ? note->FirstChildElement("v")->GetText() : "N/A"; std::string y = note->FirstChildElement("y") ? note->FirstChildElement("y")->GetText() : "N/A"; std::string p = note->FirstChildElement("p") ? note->FirstChildElement("p")->GetText() : "N/A"; std::cout << " - Timestamp (t): " << t << std::endl; std::cout << " - Duration (dur): " << dur << std::endl; std::cout << " - Note Number (n): " << n << std::endl; std::cout << " - Velocity (v): " << v << std::endl; std::cout << " - Lyrics (y): " << y << std::endl; std::cout << " - Phoneme (p): " << p << std::endl; tinyxml2::XMLElement* nStyle = note->FirstChildElement("nStyle"); if (nStyle) { std::cout << " Note Style:" << std::endl; const char* nProps[] = {"accent", "bendDep", "bendLen", "decay", "fallPort", "opening", "risePort", "vibLen", "vibType"}; for (const char* prop : nProps) { tinyxml2::XMLElement* v = nStyle->FirstChildElement("v"); std::string val = "N/A"; while (v) { if (std::string(v->Attribute("id")) == prop) { val = v->GetText() ? v->GetText() : "N/A"; break; } v = v->NextSiblingElement("v"); } std::cout << " - " << prop << ": " << val << std::endl; } } note = note->NextSiblingElement("note"); noteIdx++; } } track = track->NextSiblingElement("vsTrack"); trackIdx++; } } void write(const std::string& outputFilename) { doc.SaveFile(outputFilename.c_str()); } }; // Example usage: // int main() { // VSQXParser parser("example.vsqx"); // parser.printProperties(); // parser.write("modified.vsqx"); // return 0; // } // ===== end task-795 .VSQX ===== // ===== task-796 .VST [C] ===== #include #include #include #include #include #include #include #include typedef struct { char *filename; struct stat stat_info; char *owner; char *group; } VSTFile; VSTFile* vstfile_create(const char *filename) { VSTFile *vst = malloc(sizeof(VSTFile)); vst->filename = strdup(filename); vst->owner = NULL; vst->group = NULL; return vst; } void vstfile_read(VSTFile *vst) { if (stat(vst->filename, &vst->stat_info) == 0) { struct passwd *pw = getpwuid(vst->stat_info.st_uid); struct grp *gr = getgrgid(vst->stat_info.st_gid); vst->owner = pw ? strdup(pw->pw_name) : "Unknown"; vst->group = gr ? strdup(gr->gr_name) : "Unknown"; } } void vstfile_print_to_console(VSTFile *vst) { printf("File Name: %s\n", vst->filename); printf("Size: %ld bytes\n", vst->stat_info.st_size); printf("Device ID: %ld\n", vst->stat_info.st_dev); printf("Inode Number: %ld\n", vst->stat_info.st_ino); printf("Number of Hard Links: %ld\n", vst->stat_info.st_nlink); printf("User ID of Owner: %d\n", vst->stat_info.st_uid); printf("Group ID of Owner: %d\n", vst->stat_info.st_gid); printf("Mode: %o\n", vst->stat_info.st_mode); printf("Access Time: %s", ctime(&vst->stat_info.st_atime)); printf("Modification Time: %s", ctime(&vst->stat_info.st_mtime)); printf("Change Time: %s", ctime(&vst->stat_info.st_ctime)); printf("Owner: %s\n", vst->owner); printf("Group: %s\n", vst->group); } void vstfile_write(VSTFile *vst, time_t modification_time, mode_t permissions) { if (modification_time > 0) { struct utimbuf times; times.actime = vst->stat_info.st_atime; times.modtime = modification_time; utime(vst->filename, ×); } if (permissions > 0) { chmod(vst->filename, permissions); } } void vstfile_destroy(VSTFile *vst) { free(vst->filename); free(vst->owner); free(vst->group); free(vst); } // ===== end task-796 .VST ===== // ===== task-797 .VSTO [C] ===== #include #include #include #include typedef struct { const char *filepath; xmlDocPtr doc; } VSTOHandler; void vsto_open_and_decode(VSTOHandler *handler) { handler->doc = xmlParseFile(handler->filepath); if (handler->doc == NULL) { printf("Error parsing file.\n"); } } void vsto_read_and_print_properties(VSTOHandler *handler) { if (handler->doc == NULL) { printf("File not opened. Call vsto_open_and_decode first.\n"); return; } xmlNodePtr root = xmlDocGetRootElement(handler->doc); if (root == NULL) { printf("Empty document.\n"); return; } printf("VSTO Properties:\n"); // assembly printf("assembly: manifestVersion = %s\n", xmlGetProp(root, (const xmlChar*)"manifestVersion")); // assemblyIdentity xmlNodePtr cur = root->children; while (cur != NULL) { if (xmlStrcmp(cur->name, (const xmlChar*)"assemblyIdentity") == 0) { printf("assemblyIdentity: name = %s, version = %s, publicKeyToken = %s, processorArchitecture = %s, language = %s, type = %s\n", xmlGetProp(cur, (const xmlChar*)"name"), xmlGetProp(cur, (const xmlChar*)"version"), xmlGetProp(cur, (const xmlChar*)"publicKeyToken"), xmlGetProp(cur, (const xmlChar*)"processorArchitecture"), xmlGetProp(cur, (const xmlChar*)"language"), xmlGetProp(cur, (const xmlChar*)"type")); } else if (xmlStrcmp(cur->name, (const xmlChar*)"description") == 0) { printf("description: publisher = %s, product = %s, supportUrl = %s\n", xmlGetNsProp(cur, (const xmlChar*)"publisher", (const xmlChar*)"urn:schemas-microsoft-com:asm.v2"), xmlGetNsProp(cur, (const xmlChar*)"product", (const xmlChar*)"urn:schemas-microsoft-com:asm.v2"), xmlGetNsProp(cur, (const xmlChar*)"supportUrl", (const xmlChar*)"urn:schemas-microsoft-com:asm.v2")); } else if (xmlStrcmp(cur->name, (const xmlChar*)"deployment") == 0) { printf("deployment: install = %s, minimumRequiredVersion = %s, mapFileExtensions = %s, disallowUrlActivation = %s, trustUrlParameters = %s\n", xmlGetProp(cur, (const xmlChar*)"install"), xmlGetProp(cur, (const xmlChar*)"minimumRequiredVersion"), xmlGetProp(cur, (const xmlChar*)"mapFileExtensions"), xmlGetProp(cur, (const xmlChar*)"disallowUrlActivation"), xmlGetProp(cur, (const xmlChar*)"trustUrlParameters")); } else if (xmlStrcmp(cur->name, (const xmlChar*)"compatibleFrameworks") == 0) { printf("compatibleFrameworks: SupportUrl = %s\n", xmlGetProp(cur, (const xmlChar*)"SupportUrl")); } else if (xmlStrcmp(cur->name, (const xmlChar*)"dependency") == 0) { printf("dependency: preRequisite = %s, visible = %s, dependencyType = %s, codebase = %s, size = %s\n", xmlGetProp(cur, (const xmlChar*)"preRequisite"), xmlGetProp(cur, (const xmlChar*)"visible"), xmlGetProp(cur, (const xmlChar*)"dependencyType"), xmlGetProp(cur, (const xmlChar*)"codebase"), xmlGetProp(cur, (const xmlChar*)"size")); xmlNodePtr depChild = cur->children; while (depChild != NULL) { if (xmlStrcmp(depChild->name, (const xmlChar*)"dependentAssembly") == 0) { printf("dependentAssembly: dependencyType = %s, codebase = %s, size = %s\n", xmlGetProp(depChild, (const xmlChar*)"dependencyType"), xmlGetProp(depChild, (const xmlChar*)"codebase"), xmlGetProp(depChild, (const xmlChar*)"size")); xmlNodePtr asmChild = depChild->children; while (asmChild != NULL) { if (xmlStrcmp(asmChild->name, (const xmlChar*)"assemblyIdentity") == 0) { printf("dependentAssembly assemblyIdentity: name = %s, version = %s, publicKeyToken = %s, processorArchitecture = %s, language = %s, type = %s\n", xmlGetProp(asmChild, (const xmlChar*)"name"), xmlGetProp(asmChild, (const xmlChar*)"version"), xmlGetProp(asmChild, (const xmlChar*)"publicKeyToken"), xmlGetProp(asmChild, (const xmlChar*)"processorArchitecture"), xmlGetProp(asmChild, (const xmlChar*)"language"), xmlGetProp(asmChild, (const xmlChar*)"type")); } else if (xmlStrcmp(asmChild->name, (const xmlChar*)"hash") == 0) { xmlNodePtr hashChild = asmChild->children; while (hashChild != NULL) { if (xmlStrcmp(hashChild->name, (const xmlChar*)"DigestValue") == 0) { printf("dependentAssembly hash: digestValue = %s\n", (char*)hashChild->children->content); } hashChild = hashChild->next; } } asmChild = asmChild->next; } } depChild = depChild->next; } } else if (xmlStrcmp(cur->name, (const xmlChar*)"publisherIdentity") == 0) { printf("publisherIdentity: name = %s, issuerKeyHash = %s\n", xmlGetProp(cur, (const xmlChar*)"name"), xmlGetProp(cur, (const xmlChar*)"issuerKeyHash")); } else if (xmlStrcmp(cur->name, (const xmlChar*)"Signature") == 0) { printf("signature: present = true\n"); } else if (xmlStrcmp(cur->name, (const xmlChar*)"customErrorReporting") == 0) { printf("customErrorReporting: Uri = %s\n", xmlGetProp(cur, (const xmlChar*)"Uri")); } cur = cur->next; } } void vsto_write_property(VSTOHandler *handler, const char *tagName, const char *namespace, const char *attribute, const char *newValue) { if (handler->doc == NULL) { printf("File not opened. Call vsto_open_and_decode first.\n"); return; } xmlNsPtr ns = xmlSearchNsByHref(handler->doc, xmlDocGetRootElement(handler->doc), (const xmlChar*)namespace); xmlNodePtr cur = root->children; while (cur != NULL) { if (xmlStrcmp(cur->name, (const xmlChar*)tagName) == 0 && cur->ns == ns) { xmlSetProp(cur, (const xmlChar*)attribute, (const xmlChar*)newValue); char modifiedPath[256]; snprintf(modifiedPath, sizeof(modifiedPath), "%s.modified", handler->filepath); xmlSaveFormatFileEnc(modifiedPath, handler->doc, "UTF-8", 1); printf("File written with modified property.\n"); return; } cur = cur->next; } printf("Element not found.\n"); } void vsto_free(VSTOHandler *handler) { if (handler->doc != NULL) { xmlFreeDoc(handler->doc); } } // Example usage: // int main() { // VSTOHandler handler = {.filepath = "sample.vsto", .doc = NULL}; // vsto_open_and_decode(&handler); // vsto_read_and_print_properties(&handler); // vsto_write_property(&handler, "assemblyIdentity", "urn:schemas-microsoft-com:asm.v1", "version", "2.0.0.0"); // vsto_free(&handler); // return 0; // } // ===== end task-797 .VSTO ===== // ===== task-798 .VSVNBAK [C] ===== #include #include #include typedef struct { char* filepath; char* file_extension; char* repo_name; char* backup_date; char* backup_time; char* backup_type; char* version_compat; } VSVNBAKHandler; VSVNBAKHandler* create_handler(const char* filepath) { VSVNBAKHandler* handler = (VSVNBAKHandler*)malloc(sizeof(VSVNBAKHandler)); handler->filepath = strdup(filepath); char* filename = strrchr(filepath, '/'); filename = filename ? filename + 1 : (char*)filepath; if (strcasestr(filename, ".vsvnbak") == NULL) { free(handler); fprintf(stderr, "Invalid file extension\n"); return NULL; } char* base_name = strdup(filename); base_name[strlen(base_name) - 9] = '\0'; // Remove .vsvnbak char* parts[10]; int part_count = 0; char* token = strtok(base_name, "-"); while (token && part_count < 10) { parts[part_count++] = token; token = strtok(NULL, "-"); } if (part_count < 5) { free(base_name); free(handler); fprintf(stderr, "Invalid filename format\n"); return NULL; } int repo_len = 0; for (int i = 0; i < part_count - 4; i++) { repo_len += strlen(parts[i]) + 1; } handler->repo_name = (char*)malloc(repo_len); strcpy(handler->repo_name, parts[0]); for (int i = 1; i < part_count - 4; i++) { strcat(handler->repo_name, "-"); strcat(handler->repo_name, parts[i]); } char* year = parts[part_count - 4]; char* month = parts[part_count - 3]; char* day = parts[part_count - 2]; char* time_type = parts[part_count - 1]; char* time_delim = strchr(time_type, '-'); char* backup_time = time_type; char* backup_type = time_delim ? time_delim + 1 : time_type; if (time_delim) *time_delim = '\0'; handler->backup_date = (char*)malloc(11); sprintf(handler->backup_date, "%s-%s-%s", year, month, day); handler->backup_time = strdup(backup_time); handler->backup_type = strdup(backup_type); handler->file_extension = strdup(".vsvnbak"); handler->version_compat = strdup("VisualSVN Server 3.6+"); free(base_name); return handler; } void open_and_decode(VSVNBAKHandler* handler) { // Placeholder printf("Opening and decoding .VSVNBAK file (filename-based properties only):\n"); print_properties(handler); } void read(VSVNBAKHandler* handler) { // Placeholder printf("Reading internal data not supported for proprietary format.\n"); } void write(VSVNBAKHandler* handler, /* new props */) { // Placeholder printf("Writing to .VSVNBAK not supported.\n"); } void print_properties(VSVNBAKHandler* handler) { printf("File Extension: %s\n", handler->file_extension); printf("Repository Name: %s\n", handler->repo_name); printf("Backup Date: %s\n", handler->backup_date); printf("Backup Time: %s\n", handler->backup_time); printf("Backup Type: %s\n", handler->backup_type); printf("Version Compatibility: %s\n", handler->version_compat); } void destroy_handler(VSVNBAKHandler* handler) { free(handler->filepath); free(handler->file_extension); free(handler->repo_name); free(handler->backup_date); free(handler->backup_time); free(handler->backup_type); free(handler->version_compat); free(handler); } // Example usage: // int main() { // VSVNBAKHandler* handler = create_handler("path/to/MyRepo-2025-12-17-120000-full.vsvnbak"); // if (handler) { // open_and_decode(handler); // destroy_handler(handler); // } // return 0; // } // ===== end task-798 .VSVNBAK ===== // ===== task-799 .VTF [C] ===== #include #include #include #include typedef struct { char signature[5]; uint32_t major_version; uint32_t minor_version; uint32_t header_size; uint16_t width; uint16_t height; uint32_t flags; uint16_t frame_count; uint16_t start_frame; float reflectivity[3]; float bump_scale; uint32_t image_format; uint8_t mip_count; uint32_t thumbnail_format; uint8_t thumbnail_width; uint8_t thumbnail_height; uint16_t depth; // v7.2+ uint32_t resource_count; // v7.3+ struct Resource { char type[4]; uint8_t flags; uint32_t data; } *resources; // Array of resources } VTFProperties; void read_vtf(const char* filepath, VTFProperties* props) { FILE* f = fopen(filepath, "rb"); if (!f) return; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); uint32_t offset = 0; // Signature memcpy(props->signature, data + offset, 4); props->signature[4] = '\0'; offset += 4; // Versions memcpy(&props->major_version, data + offset, 4); offset += 4; memcpy(&props->minor_version, data + offset, 4); offset += 4; // Header size memcpy(&props->header_size, data + offset, 4); offset += 4; // Width, height memcpy(&props->width, data + offset, 2); offset += 2; memcpy(&props->height, data + offset, 2); offset += 2; // Flags memcpy(&props->flags, data + offset, 4); offset += 4; // Frames memcpy(&props->frame_count, data + offset, 2); offset += 2; memcpy(&props->start_frame, data + offset, 2); offset += 2; // Padding 0 offset += 4; // Reflectivity memcpy(props->reflectivity, data + offset, 12); offset += 12; // Padding 1 offset += 4; // Bump scale memcpy(&props->bump_scale, data + offset, 4); offset += 4; // Image format memcpy(&props->image_format, data + offset, 4); offset += 4; // Mip count props->mip_count = data[offset++]; // Thumbnail memcpy(&props->thumbnail_format, data + offset, 4); offset += 4; props->thumbnail_width = data[offset++]; props->thumbnail_height = data[offset++]; // Depth (v7.2+) if (props->minor_version >= 2) { memcpy(&props->depth, data + offset, 2); offset += 2; } else { props->depth = 1; } // Resources (v7.3+) if (props->minor_version >= 3) { offset += 3; // Padding 2 memcpy(&props->resource_count, data + offset, 4); offset += 4; offset += 8; // Padding 3 props->resources = malloc(sizeof(struct Resource) * props->resource_count); for (uint32_t i = 0; i < props->resource_count; i++) { memcpy(props->resources[i].type, data + offset, 3); props->resources[i].type[3] = '\0'; props->resources[i].flags = data[offset + 3]; memcpy(&props->resources[i].data, data + offset + 4, 4); offset += 8; } } else { props->resource_count = 0; props->resources = NULL; } free(data); } void print_properties(const VTFProperties* props) { printf("signature: %s\n", props->signature); printf("major_version: %u\n", props->major_version); printf("minor_version: %u\n", props->minor_version); printf("header_size: %u\n", props->header_size); printf("width: %u\n", props->width); printf("height: %u\n", props->height); printf("flags: %u\n", props->flags); printf("frame_count: %u\n", props->frame_count); printf("start_frame: %u\n", props->start_frame); printf("reflectivity: [%f, %f, %f]\n", props->reflectivity[0], props->reflectivity[1], props->reflectivity[2]); printf("bump_scale: %f\n", props->bump_scale); printf("image_format: %u\n", props->image_format); printf("mip_count: %u\n", props->mip_count); printf("thumbnail_format: %u\n", props->thumbnail_format); printf("thumbnail_width: %u\n", props->thumbnail_width); printf("thumbnail_height: %u\n", props->thumbnail_height); printf("depth: %u\n", props->depth); printf("resource_count: %u\n", props->resource_count); for (uint32_t i = 0; i < props->resource_count; i++) { printf("resource %u: type=%s, flags=%u, data=%u\n", i, props->resources[i].type, props->resources[i].flags, props->resources[i].data); } } void write_vtf(const char* filepath, const VTFProperties* props) { FILE* f = fopen(filepath, "wb"); if (!f) return; uint32_t offset = 0; uint8_t buffer[1024] = {0}; // Signature memcpy(buffer + offset, props->signature, 4); offset += 4; // Versions memcpy(buffer + offset, &props->major_version, 4); offset += 4; memcpy(buffer + offset, &props->minor_version, 4); offset += 4; // Header size (placeholder) uint32_t header_size_pos = offset; offset += 4; // Width, height memcpy(buffer + offset, &props->width, 2); offset += 2; memcpy(buffer + offset, &props->height, 2); offset += 2; // Flags memcpy(buffer + offset, &props->flags, 4); offset += 4; // Frames memcpy(buffer + offset, &props->frame_count, 2); offset += 2; memcpy(buffer + offset, &props->start_frame, 2); offset += 2; // Padding 0 offset += 4; // Reflectivity memcpy(buffer + offset, props->reflectivity, 12); offset += 12; // Padding 1 offset += 4; // Bump scale memcpy(buffer + offset, &props->bump_scale, 4); offset += 4; // Image format memcpy(buffer + offset, &props->image_format, 4); offset += 4; // Mip count buffer[offset++] = props->mip_count; // Thumbnail memcpy(buffer + offset, &props->thumbnail_format, 4); offset += 4; buffer[offset++] = props->thumbnail_width; buffer[offset++] = props->thumbnail_height; // Depth (v7.2+) if (props->minor_version >= 2) { memcpy(buffer + offset, &props->depth, 2); offset += 2; } // Resources (v7.3+) if (props->minor_version >= 3) { offset += 3; // Padding 2 memcpy(buffer + offset, &props->resource_count, 4); offset += 4; offset += 8; // Padding 3 for (uint32_t i = 0; i < props->resource_count; i++) { memcpy(buffer + offset, props->resources[i].type, 3); offset += 3; buffer[offset++] = props->resources[i].flags; memcpy(buffer + offset, &props->resources[i].data, 4); offset += 4; } } // Update header size memcpy(buffer + header_size_pos, &offset, 4); // Write fwrite(buffer, 1, offset, f); fclose(f); } void free_vtf(VTFProperties* props) { if (props->resources) free(props->resources); } int main(int argc, char** argv) { if (argc > 1) { VTFProperties props = {0}; read_vtf(argv[1], &props); print_properties(&props); write_vtf("output.vtf", &props); free_vtf(&props); } return 0; } // ===== end task-799 .VTF ===== // ===== task-800 .VUE [C++] ===== #include #include #include #include #include #include struct StyleBlock { std::string content; bool scoped; bool module; std::string lang; std::string src; }; struct CustomBlock { std::string tag; std::string content; std::string lang; std::string src; }; class VueFileHandler { private: std::string filepath; std::string filename; std::string templateBlock; std::string templateLang; std::string templateSrc; std::string scriptBlock; bool scriptSetup; std::string scriptLang; std::string scriptSrc; std::vector styleBlocks; std::vector customBlocks; std::vector comments; void extractAttribute(const std::string& block, const std::string& attr, std::string& value) { std::regex attrRegex(attr + R"(="([^"]*)")"); std::smatch match; if (std::regex_search(block, match, attrRegex)) { value = match[1]; } } bool hasAttribute(const std::string& block, const std::string& attr) { return block.find(attr + " ") != std::string::npos || block.find(attr + ">") != std::string::npos || block.find(attr + "=\"") != std::string::npos; } public: VueFileHandler(const std::string& fp) : filepath(fp), scriptSetup(false) { size_t pos = filepath.find_last_of('/'); filename = (pos == std::string::npos ? filepath : filepath.substr(pos + 1)).substr(0, filepath.rfind(".vue")); parse(); } void parse() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Failed to open file." << std::endl; return; } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); // Extract comments std::regex commentRegex(R"()"); std::sregex_iterator iter(content.begin(), content.end(), commentRegex); std::sregex_iterator end; for (; iter != end; ++iter) { comments.push_back(iter->str(1)); } // Simplified block extraction using regex (not full parser) std::regex blockRegex(R"(<(\w+)([^>]*)>([\s\S]*?))"); std::sregex_iterator blockIter(content.begin(), content.end(), blockRegex); for (; blockIter != end; ++blockIter) { std::string tag = blockIter->str(1); std::string attrs = blockIter->str(2); std::string inner = blockIter->str(3); if (tag == "template") { templateBlock = inner; extractAttribute(attrs, "lang", templateLang); extractAttribute(attrs, "src", templateSrc); } else if (tag == "script") { scriptBlock = inner; scriptSetup = hasAttribute(attrs, "setup"); extractAttribute(attrs, "lang", scriptLang); extractAttribute(attrs, "src", scriptSrc); } else if (tag == "style") { StyleBlock sb; sb.content = inner; sb.scoped = hasAttribute(attrs, "scoped"); sb.module = hasAttribute(attrs, "module"); extractAttribute(attrs, "lang", sb.lang); extractAttribute(attrs, "src", sb.src); styleBlocks.push_back(sb); } else { CustomBlock cb; cb.tag = tag; cb.content = inner; extractAttribute(attrs, "lang", cb.lang); extractAttribute(attrs, "src", cb.src); customBlocks.push_back(cb); } } } void printProperties() { std::cout << "{\n"; std::cout << " \"filename\": \"" << filename << "\",\n"; std::cout << " \"templateBlock\": " << (templateBlock.empty() ? "null" : "\"" + templateBlock + "\"") << ",\n"; std::cout << " \"templateLang\": " << (templateLang.empty() ? "null" : "\"" + templateLang + "\"") << ",\n"; std::cout << " \"templateSrc\": " << (templateSrc.empty() ? "null" : "\"" + templateSrc + "\"") << ",\n"; std::cout << " \"scriptBlock\": " << (scriptBlock.empty() ? "null" : "\"" + scriptBlock + "\"") << ",\n"; std::cout << " \"scriptSetup\": " << (scriptSetup ? "true" : "false") << ",\n"; std::cout << " \"scriptLang\": " << (scriptLang.empty() ? "null" : "\"" + scriptLang + "\"") << ",\n"; std::cout << " \"scriptSrc\": " << (scriptSrc.empty() ? "null" : "\"" + scriptSrc + "\"") << ",\n"; std::cout << " \"styleBlocks\": [\n"; for (size_t i = 0; i < styleBlocks.size(); ++i) { auto& sb = styleBlocks[i]; std::cout << " {\n"; std::cout << " \"content\": \"" << sb.content << "\",\n"; std::cout << " \"scoped\": " << (sb.scoped ? "true" : "false") << ",\n"; std::cout << " \"module\": " << (sb.module ? "true" : "false") << ",\n"; std::cout << " \"lang\": " << (sb.lang.empty() ? "null" : "\"" + sb.lang + "\"") << ",\n"; std::cout << " \"src\": " << (sb.src.empty() ? "null" : "\"" + sb.src + "\"") << "\n"; std::cout << " }" << (i < styleBlocks.size() - 1 ? "," : "") << "\n"; } std::cout << " ],\n"; std::cout << " \"customBlocks\": [\n"; for (size_t i = 0; i < customBlocks.size(); ++i) { auto& cb = customBlocks[i]; std::cout << " {\n"; std::cout << " \"tag\": \"" << cb.tag << "\",\n"; std::cout << " \"content\": \"" << cb.content << "\",\n"; std::cout << " \"lang\": " << (cb.lang.empty() ? "null" : "\"" + cb.lang + "\"") << ",\n"; std::cout << " \"src\": " << (cb.src.empty() ? "null" : "\"" + cb.src + "\"") << "\n"; std::cout << " }" << (i < customBlocks.size() - 1 ? "," : "") << "\n"; } std::cout << " ],\n"; std::cout << " \"comments\": [\n"; for (size_t i = 0; i < comments.size(); ++i) { std::cout << " \"" << comments[i] << "\"" << (i < comments.size() - 1 ? "," : "") << "\n"; } std::cout << " ]\n"; std::cout << "}\n"; } void write(const std::string& outputPath) { std::ofstream file(outputPath.empty() ? filepath : outputPath); if (!file.is_open()) { std::cerr << "Failed to write file." << std::endl; return; } for (const auto& c : comments) { file << "\n"; } if (!templateBlock.empty()) { file << "" << templateBlock << "\n"; } if (!scriptBlock.empty()) { file << "" << scriptBlock << "\n"; } for (const auto& sb : styleBlocks) { file << "" << sb.content << "\n"; } for (const auto& cb : customBlocks) { file << "<" << cb.tag; if (!cb.lang.empty()) file << " lang=\"" << cb.lang << "\""; if (!cb.src.empty()) file << " src=\"" << cb.src << "\""; file << ">" << cb.content << "\n"; } file.close(); } }; // Example usage: // int main() { // VueFileHandler handler("path/to/file.vue"); // handler.printProperties(); // handler.write("path/to/output.vue"); // return 0; // } // ===== end task-800 .VUE ===== // ===== task-801 .VVVVVV [C] ===== #include #include #include #include #include typedef struct { const char *filepath; xmlDocPtr doc; xmlNodePtr data; } VVVVVVFileHandler; VVVVVVFileHandler* vvvvvv_create(const char *filepath) { VVVVVVFileHandler *handler = malloc(sizeof(VVVVVVFileHandler)); handler->filepath = filepath; handler->doc = NULL; handler->data = NULL; return handler; } int vvvvvv_load(VVVVVVFileHandler *handler) { handler->doc = xmlParseFile(handler->filepath); if (handler->doc == NULL) { fprintf(stderr, "Failed to parse file: %s\n", handler->filepath); return -1; } xmlNodePtr root = xmlDocGetRootElement(handler->doc); handler->data = xmlFirstElementChild(root); // Assuming is first child if (handler->data == NULL || strcmp((const char*)handler->data->name, "Data") != 0) { fprintf(stderr, "Invalid VVVVVV file structure\n"); return -1; } return 0; } void vvvvvv_print_properties(VVVVVVFileHandler *handler) { if (handler->data == NULL) { printf("No data loaded.\n"); return; } xmlNodePtr metadata = xmlFirstElementChild(handler->data); // Find MetaData while (metadata && strcmp((const char*)metadata->name, "MetaData") != 0) { metadata = metadata->next; } if (metadata) { printf("Creator: %s\n", (char*)xmlNodeGetContent(xmlFirstElementChild(metadata))); // Simplified; assumes order // Repeat for other metadata fields (Title, Created, etc.) using similar traversal // For brevity, not all implemented here; extend as needed. } // Similarly for other fields; this is a skeleton. // For contents, edEntities, etc., traverse nodes and print attributes/content. printf("Note: Full implementation requires traversing all nodes; partial shown.\n"); } int vvvvvv_write(VVVVVVFileHandler *handler, const char *new_filepath) { if (handler->doc == NULL) { fprintf(stderr, "No data to write\n"); return -1; } return xmlSaveFormatFileEnc(new_filepath ? new_filepath : handler->filepath, handler->doc, "UTF-8", 1); } void vvvvvv_destroy(VVVVVVFileHandler *handler) { if (handler->doc) xmlFreeDoc(handler->doc); free(handler); } // Example usage: // int main() { // VVVVVVFileHandler *handler = vvvvvv_create("example.vvvvvv"); // if (vvvvvv_load(handler) == 0) { // vvvvvv_print_properties(handler); // vvvvvv_write(handler, "modified.vvvvvv"); // } // vvvvvv_destroy(handler); // return 0; // } // ===== end task-801 .VVVVVV ===== // ===== task-802 .WAB [C++] ===== #include #include #include #include #include #include class WABHandler { private: std::string filepath; std::vector data; std::map properties; // Simplified for string output public: WABHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary); if (!file) throw std::runtime_error("Cannot open file"); data = std::vector((std::istreambuf_iterator(file)), std::istreambuf_iterator()); decode(); } void decode() { if (data.size() < 24 || std::memcmp(&data[0], "\x9c\xcb\xcb\x8d\x13\x75\xd2\x11\x91\x58\x00\xc0\x4f\x79\x56\xa4", 16) != 0) { throw std::runtime_error("Invalid .WAB magic number"); } uint32_t count1 = *reinterpret_cast(&data[16]); uint32_t count2 = *reinterpret_cast(&data[20]); properties["Count1"] = std::to_string(count1); properties["Count2"] = std::to_string(count2); for (int i = 0; i < 6; ++i) { size_t offset = 24 + i * 16; uint32_t td_type = *reinterpret_cast(&data[offset]); uint32_t td_size = *reinterpret_cast(&data[offset + 4]); uint32_t td_offset = *reinterpret_cast(&data[offset + 8]); uint32_t td_count = *reinterpret_cast(&data[offset + 12]); std::string key = "TableDescriptor" + std::to_string(i + 1); properties[key] = "Type: " + std::to_string(td_type) + ", Size: " + std::to_string(td_size) + ", Offset: " + std::to_string(td_offset) + ", Count: " + std::to_string(td_count); } // Extend for records } void printProperties() { for (const auto& kv : properties) { std::cout << kv.first << ": " << kv.second << std::endl; } } void write(const std::string& newFilepath) { // Implementation for writing // Omitted for brevity } }; int main(int argc, char** argv) { if (argc < 2) { std::cout << "Usage: ./wab_handler " << std::endl; return 1; } try { WABHandler handler(argv[1]); handler.read(); handler.printProperties(); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } return 0; } // ===== end task-802 .WAB ===== // ===== task-803 .WAD [C] ===== #include #include #include #include typedef struct { char identification[4]; int32_t numlumps; int32_t infotableofs; } WADHeader; typedef struct { char name[9]; // Null-terminated int32_t offset; int32_t size; uint8_t *data; } WADLump; typedef struct { WADHeader header; WADLump *lumps; } WADFile; WADFile* wad_open(const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); long filesize = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(filesize); fread(data, 1, filesize, f); fclose(f); WADFile *wad = malloc(sizeof(WADFile)); memcpy(wad->header.identification, data, 4); memcpy(&wad->header.numlumps, data + 4, 4); memcpy(&wad->header.infotableofs, data + 8, 4); wad->lumps = malloc(wad->header.numlumps * sizeof(WADLump)); for (int i = 0; i < wad->header.numlumps; i++) { int pos = wad->header.infotableofs + i * 16; memcpy(&wad->lumps[i].offset, data + pos, 4); memcpy(&wad->lumps[i].size, data + pos + 4, 4); memcpy(wad->lumps[i].name, data + pos + 8, 8); wad->lumps[i].name[8] = '\0'; wad->lumps[i].data = malloc(wad->lumps[i].size); memcpy(wad->lumps[i].data, data + wad->lumps[i].offset, wad->lumps[i].size); } free(data); return wad; } void wad_print_properties(WADFile *wad) { printf("Identification: %.4s\n", wad->header.identification); printf("Number of lumps: %d\n", wad->header.numlumps); printf("Directory offset: %d\n", wad->header.infotableofs); printf("Lumps:\n"); for (int i = 0; i < wad->header.numlumps; i++) { printf("Name: %s, Offset: %d, Size: %d\n", wad->lumps[i].name, wad->lumps[i].offset, wad->lumps[i].size); } } void wad_write(WADFile *wad, const char *filename) { FILE *f = fopen(filename, "wb"); if (!f) return; // Write temporary header fwrite(wad->header.identification, 1, 4, f); fwrite(&wad->header.numlumps, 4, 1, f); int32_t temp_ofs = 12; fwrite(&temp_ofs, 4, 1, f); // Write directory (temporary offsets) for (int i = 0; i < wad->header.numlumps; i++) { int32_t temp_offset = 0; fwrite(&temp_offset, 4, 1, f); fwrite(&wad->lumps[i].size, 4, 1, f); char name_padded[8] = {0}; strncpy(name_padded, wad->lumps[i].name, 8); fwrite(name_padded, 1, 8, f); } // Write data and update offsets long dir_pos = ftell(f) - (wad->header.numlumps * 16); int32_t current_offset = 12 + (wad->header.numlumps * 16); for (int i = 0; i < wad->header.numlumps; i++) { wad->lumps[i].offset = current_offset; fwrite(wad->lumps[i].data, 1, wad->lumps[i].size, f); current_offset += wad->lumps[i].size; // Update directory entry fseek(f, dir_pos + i * 16, SEEK_SET); fwrite(&wad->lumps[i].offset, 4, 1, f); fseek(f, 0, SEEK_END); } fclose(f); } void wad_free(WADFile *wad) { for (int i = 0; i < wad->header.numlumps; i++) { free(wad->lumps[i].data); } free(wad->lumps); free(wad); } // ===== end task-803 .WAD ===== // ===== task-804 .WAV [C++] ===== #include #include #include #include #include #include class WavHandler { private: std::string filepath; std::map properties; std::vector audioData; public: WavHandler(const std::string& filepath) : filepath(filepath) { readAndDecode(); } void readAndDecode() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) return; size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(data.data(), size); size_t offset = 0; auto readString = [&](size_t len) -> std::string { std::string str(data.begin() + offset, data.begin() + offset + len); offset += len; // Trim nulls str.erase(std::find(str.begin(), str.end(), '\0'), str.end()); return str; }; auto readUint16 = [&]() -> uint16_t { uint16_t val = *reinterpret_cast(data.data() + offset); offset += 2; return val; }; auto readUint32 = [&]() -> uint32_t { uint32_t val = *reinterpret_cast(data.data() + offset); offset += 4; return val; }; properties["ChunkID"] = readString(4); properties["ChunkSize"] = std::to_string(readUint32()); properties["Format"] = readString(4); properties["Subchunk1ID"] = readString(4); uint32_t fmtSize = readUint32(); properties["Subchunk1Size"] = std::to_string(fmtSize); properties["AudioFormat"] = std::to_string(readUint16()); properties["NumChannels"] = std::to_string(readUint16()); properties["SampleRate"] = std::to_string(readUint32()); properties["ByteRate"] = std::to_string(readUint32()); properties["BlockAlign"] = std::to_string(readUint16()); properties["BitsPerSample"] = std::to_string(readUint16()); if (fmtSize > 16) { uint16_t cbSize = readUint16(); properties["cbSize"] = std::to_string(cbSize); if (fmtSize >= 40) { properties["wValidBitsPerSample"] = std::to_string(readUint16()); properties["dwChannelMask"] = std::to_string(readUint32()); std::stringstream ss; for (size_t i = 0; i < 16; ++i) { ss << std::hex << std::setw(2) << std::setfill('0') << (static_cast(data[offset + i]) & 0xff) << " "; } properties["SubFormat"] = ss.str(); offset += 16; } } while (offset < size) { std::string chunkId = readString(4); uint32_t chunkSize = readUint32(); if (chunkId == "fact") { properties["factChunkID"] = chunkId; properties["factChunkSize"] = std::to_string(chunkSize); properties["dwSampleLength"] = std::to_string(readUint32()); } else if (chunkId == "data") { properties["Subchunk2ID"] = chunkId; properties["Subchunk2Size"] = std::to_string(chunkSize); audioData.assign(data.begin() + offset, data.begin() + offset + chunkSize); offset += chunkSize; if (chunkSize % 2 != 0) ++offset; break; } else { offset += chunkSize; } } } void printProperties() const { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& outputPath) const { std::ofstream file(outputPath, std::ios::binary); if (!file) return; auto writeString = [&](const std::string& str, size_t len) { file.write(str.c_str(), len); }; auto writeUint16 = [&](uint16_t val) { file.write(reinterpret_cast(&val), 2); }; auto writeUint32 = [&](uint32_t val) { file.write(reinterpret_cast(&val), 4); }; writeString(properties.at("ChunkID"), 4); writeUint32(std::stoul(properties.at("ChunkSize"))); writeString(properties.at("Format"), 4); writeString(properties.at("Subchunk1ID"), 4); writeUint32(std::stoul(properties.at("Subchunk1Size"))); writeUint16(std::stoi(properties.at("AudioFormat"))); writeUint16(std::stoi(properties.at("NumChannels"))); writeUint32(std::stoul(properties.at("SampleRate"))); writeUint32(std::stoul(properties.at("ByteRate"))); writeUint16(std::stoi(properties.at("BlockAlign"))); writeUint16(std::stoi(properties.at("BitsPerSample"))); if (properties.count("cbSize")) { writeUint16(std::stoi(properties.at("cbSize"))); if (properties.count("wValidBitsPerSample")) { writeUint16(std::stoi(properties.at("wValidBitsPerSample"))); writeUint32(std::stoul(properties.at("dwChannelMask"))); std::istringstream iss(properties.at("SubFormat")); std::string hex; while (iss >> hex) { unsigned char byte = static_cast(std::stoi(hex, nullptr, 16)); file.write(reinterpret_cast(&byte), 1); } } } if (properties.count("factChunkID")) { writeString(properties.at("factChunkID"), 4); writeUint32(std::stoul(properties.at("factChunkSize"))); writeUint32(std::stoul(properties.at("dwSampleLength"))); } writeString(properties.at("Subchunk2ID"), 4); uint32_t dataSize = std::stoul(properties.at("Subchunk2Size")); writeUint32(dataSize); file.write(audioData.data(), dataSize); if (dataSize % 2 != 0) { char pad = 0; file.write(&pad, 1); } } }; // Example usage: // int main() { // WavHandler handler("input.wav"); // handler.printProperties(); // handler.write("output.wav"); // return 0; // } // ===== end task-804 .WAV ===== // ===== task-805 .WEBM [C++] ===== #include #include #include #include #include #include #include class WebMHandler { private: std::string filepath; std::map properties; // Simplified to string values for print std::vector buffer; std::pair readVint(const std::vector& data, size_t pos) { uint8_t byte = data[pos++]; int length = 0; while (!(byte & (1 << (7 - length)))) ++length; uint64_t value = byte & ((1ULL << (7 - length)) - 1); for (int i = 0; i < length; ++i) { value = (value << 8) | data[pos++]; } return {value, pos}; } public: WebMHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary); if (!file) return; buffer = std::vector((std::istreambuf_iterator(file)), std::istreambuf_iterator()); size_t pos = 0; while (pos < buffer.size()) { auto [id, newPos] = readVint(buffer, pos); pos = newPos; auto [size, newPos2] = readVint(buffer, pos); pos = newPos2; std::stringstream ss; ss << std::hex << std::uppercase << std::setfill('0') << std::setw(4) << id; std::string key = ss.str(); // Parsing logic similar to above, but simplified; store as string std::string value = "parsed_value"; // Implement full parsing as in Python properties[key] = value; pos += size; } } void printProperties() { for (const auto& [key, val] : properties) { std::cout << key << ": " << val << std::endl; } } void write(const std::string& outputPath) { std::ofstream out(outputPath, std::ios::binary); out.write(reinterpret_cast(buffer.data()), buffer.size()); } }; // Usage: // WebMHandler handler("example.webm"); // handler.read(); // handler.printProperties(); // handler.write("modified.webm"); // ===== end task-805 .WEBM ===== // ===== task-806 .WIN [C] ===== #include #include #include #include // Simple struct for properties (use linked list or dict for full, but simplified) typedef struct { char magic[5]; uint32_t size; // Add fields as needed } Chunk; void read_chunk_header(FILE *f, char *magic, uint32_t *size) { fread(magic, 1, 4, f); magic[4] = '\0'; fread(size, sizeof(uint32_t), 1, f); } void parse_and_print(const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) { perror("Error opening file"); return; } char magic[5]; uint32_t size; read_chunk_header(f, magic, &size); if (strcmp(magic, "FORM") != 0) { printf("Invalid .WIN file\n"); fclose(f); return; } printf("FORM Chunk - Size: %u\n", size); while (!feof(f)) { read_chunk_header(f, magic, &size); printf("\nChunk: %s - Size: %u\n", magic, size); if (strcmp(magic, "GEN8") == 0) { uint32_t unknown1; fread(&unknown1, sizeof(uint32_t), 1, f); printf(" Unknown1: %u\n", unknown1); // Read other fields fseek(f, size - sizeof(uint32_t), SEEK_CUR); // Skip for now } else if (strcmp(magic, "STRG") == 0) { uint32_t num_strings; fread(&num_strings, sizeof(uint32_t), 1, f); printf(" Number of Strings: %u\n", num_strings); // Read offsets and strings (need to seek for strings) fseek(f, size - sizeof(uint32_t), SEEK_CUR); } // Add for other chunks else { fseek(f, size, SEEK_CUR); } } fclose(f); } void write_copy(const char *filename, const char *new_filename) { FILE *in = fopen(filename, "rb"); FILE *out = fopen(new_filename, "wb"); char buf[1024]; size_t n; while ((n = fread(buf, 1, sizeof(buf), in)) > 0) { fwrite(buf, 1, n, out); } fclose(in); fclose(out); } int main(int argc, char *argv[]) { if (argc > 1) { parse_and_print(argv[1]); } return 0; } // ===== end task-806 .WIN ===== // ===== task-807 .WITNESS [C] ===== #include #include #include #include #include #include typedef struct { char* filepath; unsigned char* data; size_t size; } WitnessCampaignHandler; void init_handler(WitnessCampaignHandler* handler, const char* filepath) { handler->filepath = strdup(filepath); handler->data = NULL; handler->size = 0; } void read_handler(WitnessCampaignHandler* handler) { FILE* file = fopen(handler->filepath, "rb"); if (!file) { perror("Error opening file"); return; } fseek(file, 0, SEEK_END); handler->size = ftell(file); fseek(file, 0, SEEK_SET); handler->data = malloc(handler->size); if (handler->data) { fread(handler->data, 1, handler->size, file); } fclose(file); } void write_handler(WitnessCampaignHandler* handler, const char* output_path) { if (!handler->data) { fprintf(stderr, "No data to write. Call read first.\n"); return; } const char* path = output_path ? output_path : handler->filepath; FILE* file = fopen(path, "wb"); if (!file) { perror("Error opening file for writing"); return; } fwrite(handler->data, 1, handler->size, file); fclose(file); } void print_properties(WitnessCampaignHandler* handler) { struct stat st; if (stat(handler->filepath, &st) != 0) { perror("Error getting file stats"); return; } char* base = strrchr(handler->filepath, '/'); base = base ? base + 1 : handler->filepath; char* ext = strrchr(base, '.'); printf("File Name: %s\n", base); printf("File Extension: %s\n", ext ? ext : ""); printf("File Size: %ld bytes\n", st.st_size); printf("Creation Time: %s", ctime(&st.st_ctime)); printf("Last Modification Time: %s", ctime(&st.st_mtime)); printf("Last Access Time: %s", ctime(&st.st_atime)); printf("Permissions: %o\n", st.st_mode & 0777); printf("Owner UID: %d\n", st.st_uid); printf("Group GID: %d\n", st.st_gid); printf("File Type: Binary\n"); char abs_path[PATH_MAX]; realpath(handler->filepath, abs_path); printf("Full Path: %s\n", abs_path); } void free_handler(WitnessCampaignHandler* handler) { free(handler->filepath); free(handler->data); } // Example usage: // int main() { // WitnessCampaignHandler handler; // init_handler(&handler, "path/to/file.witness_campaign"); // read_handler(&handler); // print_properties(&handler); // write_handler(&handler, "path/to/new_file.witness_campaign"); // free_handler(&handler); // return 0; // } // ===== end task-807 .WITNESS ===== // ===== task-808 .WK1 [C] ===== #include #include #include #include #include // For le16toh if needed typedef struct { uint8_t *data; size_t size; struct { char magic[18]; // "00 00 02 00 06 04" int version; int revision; int columns; int rows; char calc_mode[10]; char sheet_dimensions[50]; char endianness[15]; } properties; } WK1File; void wk1_read(WK1File *wk1, const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) { perror("fopen"); exit(1); } fseek(f, 0, SEEK_END); wk1->size = ftell(f); fseek(f, 0, SEEK_SET); wk1->data = malloc(wk1->size); fread(wk1->data, 1, wk1->size, f); fclose(f); } void wk1_decode(WK1File *wk1) { uint8_t magic[6]; memcpy(magic, wk1->data, 6); if (memcmp(magic, (uint8_t[]){0,0,2,0,6,4}, 6) != 0) { fprintf(stderr, "Invalid WK1 magic number\n"); exit(1); } sprintf(wk1->properties.magic, "%02x %02x %02x %02x %02x %02x", magic[0], magic[1], magic[2], magic[3], magic[4], magic[5]); size_t offset = 0; while (offset < wk1->size) { uint16_t opcode = *(uint16_t*)(wk1->data + offset); offset += 2; uint16_t length = *(uint16_t*)(wk1->data + offset); offset += 2; uint8_t *rec_data = wk1->data + offset; offset += length; if (opcode == 0) { // BOF wk1->properties.version = rec_data[1]; wk1->properties.revision = rec_data[0]; } if (opcode == 1) break; if (opcode == 6) { // DIMENSIONS uint16_t col_start = *(uint16_t*)rec_data; uint16_t col_end = *(uint16_t*)(rec_data + 2); uint16_t row_start = *(uint16_t*)(rec_data + 4); uint16_t row_end = *(uint16_t*)(rec_data + 6); wk1->properties.columns = col_end - col_start + 1; wk1->properties.rows = row_end - row_start + 1; } if (opcode == 3) { strcpy(wk1->properties.calc_mode, rec_data[0] == 0 ? "Manual" : "Automatic"); } } strcpy(wk1->properties.sheet_dimensions, "Single sheet, max 256 columns, 8192 rows"); strcpy(wk1->properties.endianness, "Little-endian"); } void wk1_print_properties(const WK1File *wk1) { printf("magic: %s\n", wk1->properties.magic); printf("version: %d\n", wk1->properties.version); printf("revision: %d\n", wk1->properties.revision); printf("columns: %d\n", wk1->properties.columns); printf("rows: %d\n", wk1->properties.rows); printf("calc_mode: %s\n", wk1->properties.calc_mode); printf("sheet_dimensions: %s\n", wk1->properties.sheet_dimensions); printf("endianness: %s\n", wk1->properties.endianness); } void wk1_write(const WK1File *wk1, const char *filename) { uint8_t minimal[] = {0, 0, 2, 0, 6, 4, 1, 0, 0, 0}; FILE *f = fopen(filename, "wb"); if (!f) { perror("fopen"); exit(1); } if (wk1->data) { fwrite(wk1->data, 1, wk1->size, f); } else { fwrite(minimal, 1, sizeof(minimal), f); } fclose(f); } void wk1_free(WK1File *wk1) { free(wk1->data); } // Example usage // int main() { // WK1File wk1 = {0}; // wk1_read(&wk1, "sample.wk1"); // wk1_decode(&wk1); // wk1_print_properties(&wk1); // wk1_write(&wk1, "output.wk1"); // wk1_free(&wk1); // return 0; // } // ===== end task-808 .WK1 ===== // ===== task-809 .WK3 [C++] ===== #include #include #include #include #include class WK3Parser { private: std::string filename; std::string getPropertyName(uint16_t opcode) { switch (opcode) { case 0: return "Beginning of File (BOF)"; case 1: return "End of File (EOF)"; case 2: return "Calculation Mode (CALCMODE)"; case 3: return "Calculation Order (CALCORDER)"; case 4: return "Split Window Type (SPLIT)"; case 5: return "Split Window Sync (SYNC)"; case 6: return "Active Worksheet Range (RANGE)"; case 7: return "Window 1 Record (WINDOW1)"; case 8: return "Column Width for Window 1 (COLW1)"; case 9: return "Window 2 Record (WINTWO)"; case 10: return "Column Width for Window 2 (COLW2)"; case 11: return "Named Range (NAME)"; case 12: return "Blank Cell (BLANK)"; case 13: return "Integer Cell (INTEGER)"; case 14: return "Floating Point Number (NUMBER)"; case 15: return "Label Cell (LABEL)"; case 16: return "Formula Cell (FORMULA)"; case 24: return "Data Table Range (TABLE)"; case 25: return "Query Range (ORANGE)"; case 26: return "Print Range (PRANGE)"; case 27: return "Sort Range (SRANGE)"; case 28: return "Fill Range (FRANGE)"; case 29: return "Primary Sort Key Range (KRANGE1)"; case 32: return "Distribution Range (HRANGE)"; case 35: return "Secondary Sort Key Range (KRANGE2)"; case 36: return "Global Protection (PROTEC)"; case 37: return "Print Footer (FOOTER)"; case 38: return "Print Header (HEADER)"; case 39: return "Print Setup (SETUP)"; case 40: return "Print Margins (MARGINS)"; default: return "Unknown Opcode " + std::to_string(opcode); } } public: WK3Parser(const std::string& fn) : filename(fn) {} void read() { std::ifstream file(filename, std::ios::binary); if (!file) { std::cerr << "Cannot open file!" << std::endl; return; } std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); size_t offset = 0; while (offset < data.size()) { uint16_t opcode = *reinterpret_cast(&data[offset]); offset += 2; uint16_t length = *reinterpret_cast(&data[offset]); offset += 2; std::string hexData; for (size_t i = 0; i < length; ++i) { hexData += std::to_string(static_cast(data[offset + i]) & 0xFF) + " "; } std::string propName = getPropertyName(opcode); std::cout << propName << " (Opcode: 0x" << std::hex << std::setw(4) << std::setfill('0') << opcode << ", Length: " << std::dec << length << ") - Data: " << hexData << std::endl; offset += length; if (opcode == 1) break; // EOF } } void write(const std::string& outputFilename) { std::ofstream file(outputFilename, std::ios::binary); if (!file) { std::cerr << "Cannot create file!" << std::endl; return; } // BOF record (example minimal) uint16_t bofOpcode = 0; uint16_t bofLength = 26; file.write(reinterpret_cast(&bofOpcode), 2); file.write(reinterpret_cast(&bofLength), 2); char bofData[26] = {0x00, 0x10, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00}; file.write(bofData, 26); // EOF record uint16_t eofOpcode = 1; uint16_t eofLength = 0; file.write(reinterpret_cast(&eofOpcode), 2); file.write(reinterpret_cast(&eofLength), 2); std::cout << "Wrote minimal .WK3 file to " << outputFilename << std::endl; } }; // Example usage: // int main() { // WK3Parser parser("example.wk3"); // parser.read(); // parser.write("output.wk3"); // return 0; // } // ===== end task-809 .WK3 ===== // ===== task-810 .WKS [C++] ===== #include #include #include #include #include #include struct Record { uint16_t opcode; uint16_t length; std::vector data; }; class WKSFile { private: std::string filename; std::string version; int dimensions[4]; std::vector records; public: WKSFile(const std::string& fn = "") : filename(fn) { memset(dimensions, 0, sizeof(dimensions)); if (!fn.empty()) read(fn); } void read(const std::string& fn) { filename = fn; std::ifstream file(fn, std::ios::binary); if (!file) return; file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(reinterpret_cast(data.data()), size); size_t offset = 0; while (offset < size) { if (offset + 4 > size) break; uint16_t opcode, length; memcpy(&opcode, data.data() + offset, 2); memcpy(&length, data.data() + offset + 2, 2); offset += 4; std::vector rec_data(data.begin() + offset, data.begin() + offset + length); records.push_back({opcode, length, rec_data}); offset += length; if (opcode == 0x0000) { // BOF uint16_t ver; memcpy(&ver, rec_data.data(), 2); version = std::to_string(ver); } else if (opcode == 0x0006) { // RANGE memcpy(dimensions, rec_data.data(), sizeof(dimensions)); } if (opcode == 0x0001) break; // EOF } } void printProperties() const { std::cout << "Properties of the .WKS file:" << std::endl; std::cout << "File Signature: 00 00 02 00 04 06" << std::endl; std::cout << "Version: " << version << " (Lotus 1-2-3 Release 1A)" << std::endl; std::cout << "Byte Order: Little-endian" << std::endl; std::cout << "Record Structure: 2-byte opcode, 2-byte length, data" << std::endl; if (dimensions[0] || dimensions[1] || dimensions[2] || dimensions[3]) { std::cout << "Dimensions: Columns " << dimensions[0] << "-" << dimensions[2] << ", Rows " << dimensions[1] << "-" << dimensions[3] << std::endl; } std::cout << "Records:" << std::endl; for (const auto& r : records) { std::cout << "Opcode: 0x" << std::setfill('0') << std::setw(4) << std::hex << std::uppercase << r.opcode << ", Length: " << std::dec << r.length << std::endl; // Decode more as needed } std::cout << "Embedded Graphics Compression: LZW (adaptive 9-12 bits, max table 4096, Clear code 4094)" << std::endl; } void write(const std::string& fn) { std::ofstream file(fn, std::ios::binary); if (!file) return; // BOF uint16_t bof[] = {0x0000, 0x0002, 0x0406}; file.write(reinterpret_cast(bof), sizeof(bof)); // RANGE uint16_t range_hdr[] = {0x0006, 0x0008}; file.write(reinterpret_cast(range_hdr), sizeof(range_hdr)); uint16_t range_data[] = {0, 0, 255, 8191}; file.write(reinterpret_cast(range_data), sizeof(range_data)); // Sample label uint16_t label_hdr[] = {0x000F, 10}; file.write(reinterpret_cast(label_hdr), sizeof(label_hdr)); uint8_t label_data[] = {0, 0, 0, 39, 'T', 'e', 's', 't', 0}; // Col, row low, row high, format, string file.write(reinterpret_cast(label_data), sizeof(label_data)); // EOF uint16_t eof[] = {0x0001, 0x0000}; file.write(reinterpret_cast(eof), sizeof(eof)); } }; int main(int argc, char** argv) { if (argc > 1) { WKSFile wks(argv[1]); wks.printProperties(); } return 0; } // ===== end task-810 .WKS ===== // ===== task-811 .WL [C++] ===== #include #include #include #include #include #include struct Property { Uint32 tag; std::string name; std::string type; }; class WLFile { private: DcmFileFormat fileformat; std::vector properties; public: WLFile(const std::string& filename) { OFCondition status = fileformat.loadFile(filename.c_str()); if (!status.good()) { std::cerr << "Error loading file" << std::endl; } // Populate properties properties.push_back({DCM_ScheduledProcedureStepSequence, "Scheduled Procedure Step Sequence", "1"}); properties.push_back({DCM_ScheduledStationAETitle, "Scheduled Station AE Title", "1"}); properties.push_back({DCM_ScheduledProcedureStepStartDate, "Scheduled Procedure Step Start Date", "1"}); properties.push_back({DCM_ScheduledProcedureStepStartTime, "Scheduled Procedure Step Start Time", "1"}); properties.push_back({DCM_Modality, "Modality", "1"}); properties.push_back({DCM_ScheduledPerformingPhysiciansName, "Scheduled Performing Physician's Name", "2"}); properties.push_back({DCM_ScheduledProcedureStepDescription, "Scheduled Procedure Step Description", "1C"}); properties.push_back({DCM_ScheduledStationName, "Scheduled Station Name", "2"}); properties.push_back({DCM_ScheduledProcedureStepLocation, "Scheduled Procedure Step Location", "2"}); properties.push_back({DCM_ReferencedDefinedProtocolSequence, "Referenced Defined Protocol Sequence", "3"}); properties.push_back({DCM_ReferencedSOPClassUID, "Referenced SOP Class UID", "1"}); properties.push_back({DCM_ReferencedSOPInstanceUID, "Referenced SOP Instance UID", "1"}); properties.push_back({DCM_ReferencedPerformedProtocolSequence, "Referenced Performed Protocol Sequence", "3"}); properties.push_back({DCM_ReferencedSOPClassUID, "Referenced SOP Class UID", "1"}); properties.push_back({DCM_ReferencedSOPInstanceUID, "Referenced SOP Instance UID", "1"}); properties.push_back({DCM_ScheduledProtocolCodeSequence, "Scheduled Protocol Code Sequence", "1C"}); properties.push_back({DCM_ProtocolContextSequence, "Protocol Context Sequence", "3"}); properties.push_back({DCM_ValueType, "Value Type", "1"}); properties.push_back({DCM_ConceptNameCodeSequence, "Concept Name Code Sequence", "1"}); properties.push_back({DCM_DateTime, "DateTime", "1C"}); properties.push_back({DCM_PersonName, "Person Name", "1C"}); properties.push_back({DCM_TextValue, "Text Value", "1C"}); properties.push_back({DCM_ConceptCodeSequence, "Concept Code Sequence", "1C"}); properties.push_back({DCM_NumericValue, "Numeric Value", "1C"}); properties.push_back({DCM_MeasurementUnitsCodeSequence, "Measurement Units Code Sequence", "1C"}); properties.push_back({DCM_PreMedication, "Pre-Medication", "2C"}); properties.push_back({DCM_ScheduledProcedureStepID, "Scheduled Procedure Step ID", "1"}); properties.push_back({DCM_RequestedContrastAgent, "Requested Contrast Agent", "2C"}); properties.push_back({DCM_ScheduledProcedureStepStatus, "Scheduled Procedure Step Status", "3"}); properties.push_back({DCM_ScheduledSpecimenSequence, "Scheduled Specimen Sequence", "3"}); properties.push_back({DCM_ContainerIdentifier, "Container Identifier", "1"}); properties.push_back({DCM_ContainerTypeCodeSequence, "Container Type Code Sequence", "2"}); properties.push_back({DCM_SpecimenDescriptionSequence, "Specimen Description Sequence", "1"}); properties.push_back({DCM_SpecimenIdentifier, "Specimen Identifier", "1"}); properties.push_back({DCM_SpecimenUID, "Specimen UID", "1"}); properties.push_back({DCM_BarcodeValue, "Barcode Value", "3"}); properties.push_back({DCM_RequestedProcedureID, "Requested Procedure ID", "1"}); properties.push_back({DCM_RequestedProcedureDescription, "Requested Procedure Description", "1C"}); properties.push_back({DCM_RequestedProcedureCodeSequence, "Requested Procedure Code Sequence", "1C"}); properties.push_back({DCM_RequestedLateralityCodeSequence, "Requested Laterality Code Sequence", "3"}); properties.push_back({DCM_StudyInstanceUID, "Study Instance UID", "1"}); properties.push_back({DCM_StudyDate, "Study Date", "3"}); properties.push_back({DCM_StudyTime, "Study Time", "3"}); properties.push_back({DCM_ReferencedStudySequence, "Referenced Study Sequence", "2"}); properties.push_back({DCM_ReferencedSOPClassUID, "Referenced SOP Class UID", "1"}); properties.push_back({DCM_ReferencedSOPInstanceUID, "Referenced SOP Instance UID", "1"}); properties.push_back({DCM_RequestedProcedurePriority, "Requested Procedure Priority", "2"}); properties.push_back({DCM_PatientTransportArrangements, "Patient Transport Arrangements", "2"}); properties.push_back({DCM_AccessionNumber, "Accession Number", "2"}); properties.push_back({DCM_IssuerOfAccessionNumberSequence, "Issuer of Accession Number Sequence", "3"}); properties.push_back({DCM_RequestingPhysician, "Requesting Physician", "2"}); properties.push_back({DCM_ReferringPhysiciansName, "Referring Physician's Name", "2"}); properties.push_back({DCM_AdmissionID, "Admission ID", "2"}); properties.push_back({DCM_IssuerOfAdmissionIDSequence, "Issuer of Admission ID Sequence", "3"}); properties.push_back({DCM_CurrentPatientLocation, "Current Patient Location", "2"}); properties.push_back({DCM_ReferencedPatientSequence, "Referenced Patient Sequence", "2"}); properties.push_back({DCM_ReferencedSOPClassUID, "Referenced SOP Class UID", "1"}); properties.push_back({DCM_ReferencedSOPInstanceUID, "Referenced SOP Instance UID", "1"}); properties.push_back({DCM_PatientName, "Patient's Name", "1"}); properties.push_back({DCM_PatientID, "Patient ID", "1"}); properties.push_back({DCM_IssuerOfPatientID, "Issuer of Patient ID", "3"}); properties.push_back({DCM_IssuerOfPatientIDQualifiersSequence, "Issuer of Patient ID Qualifiers Sequence", "3"}); properties.push_back({DCM_OtherPatientIDsSequence, "Other Patient IDs Sequence", "3"}); properties.push_back({DCM_PatientBirthDate, "Patient's Birth Date", "2"}); properties.push_back({DCM_PatientSex, "Patient's Sex", "2"}); properties.push_back({DCM_GenderIdentitySequence, "Gender Identity Sequence", "3"}); properties.push_back({DCM_GenderIdentityCodeSequence, "Gender Identity Code Sequence", "1"}); properties.push_back({DCM_EffectiveStartDateTime, "Effective Start DateTime", "3"}); properties.push_back({DCM_EffectiveStopDateTime, "Effective Stop DateTime", "3"}); properties.push_back({DCM_GenderIdentityComment, "Gender Identity Comment", "3"}); properties.push_back({DCM_SexParametersForClinicalUseCategorySequence, "Sex Parameters for Clinical Use Category Sequence", "3"}); properties.push_back({DCM_SexParametersForClinicalUseCategoryCodeSequence, "Sex Parameters for Clinical Use Category Code Sequence", "1"}); properties.push_back({DCM_SexParametersForClinicalUseCategoryComment, "Sex Parameters for Clinical Use Category Comment", "3"}); properties.push_back({DCM_SexParametersForClinicalUseCategoryReference, "Sex Parameters for Clinical Use Category Reference", "3"}); properties.push_back({DCM_PersonNamesToUseSequence, "Person Names to Use Sequence", "3"}); properties.push_back({DCM_NameToUse, "Name to Use", "1"}); properties.push_back({DCM_NameToUseComment, "Name to Use Comment", "3"}); properties.push_back({DCM_ThirdPersonPronounsSequence, "Third Person Pronouns Sequence", "3"}); properties.push_back({DCM_PronounCodeSequence, "Pronoun Code Sequence", "1"}); properties.push_back({DCM_PronounComment, "Pronoun Comment", "3"}); properties.push_back({DCM_PatientsPrimaryLanguageCodeSequence, "Patient's Primary Language Code Sequence", "3"}); properties.push_back({DCM_PatientsPrimaryLanguageModifierCodeSequence, "Patient's Primary Language Modifier Code Sequence", "3"}); properties.push_back({DCM_PatientWeight, "Patient's Weight", "2"}); properties.push_back({DCM_PatientSize, "Patient's Size", "3"}); properties.push_back({DCM_ConfidentialityConstraintOnPatientDataDescription, "Confidentiality Constraint on Patient Data Description", "2"}); properties.push_back({DCM_PatientState, "Patient State", "2"}); properties.push_back({DCM_PregnancyStatus, "Pregnancy Status", "2"}); properties.push_back({DCM_MedicalAlerts, "Medical Alerts", "2"}); properties.push_back({DCM_Allergies, "Allergies", "2"}); properties.push_back({DCM_SpecialNeeds, "Special Needs", "2"}); properties.push_back({DCM_PertinentDocumentsSequence, "Pertinent Documents Sequence", "3"}); properties.push_back({DCM_ReferencedSOPClassUID, "Referenced SOP Class UID", "1"}); properties.push_back({DCM_ReferencedSOPInstanceUID, "Referenced SOP Instance UID", "1"}); properties.push_back({DCM_PurposeOfReferenceCodeSequence, "Purpose of Reference Code Sequence", "2"}); properties.push_back({DCM_DocumentTitle, "Document Title", "2"}); } void printProperties() { DcmDataset *ds = fileformat.getDataset(); for (const auto& prop : properties) { OFString value; if (ds->findAndGetOFStringArray(prop.tag, value).good()) { std::cout << prop.name << " (" << std::hex << prop.tag << "): " << value << std::endl; } } } OFString readProperty(Uint32 tag) { OFString value; fileformat.getDataset()->findAndGetOFStringArray(tag, value); return value; } void writeProperty(Uint32 tag, const std::string& value) { fileformat.getDataset()->putAndInsertString(tag, value.c_str()); } void save(const std::string& filename) { fileformat.saveFile(filename.c_str(), EXS_LittleEndianExplicit); } }; // ===== end task-811 .WL ===== // ===== task-812 .WLMP [C++] ===== #include #include #include #include "tinyxml2.h" // Assume TinyXML2 library is available using namespace tinyxml2; class WLMPHandler { private: std::string filepath; XMLDocument doc; public: WLMPHandler(const std::string& fp) : filepath(fp) {} bool read() { if (doc.LoadFile(filepath.c_str()) != XML_SUCCESS) { std::cerr << "Error loading file: " << doc.ErrorStr() << std::endl; return false; } return true; } void printProperties() { XMLElement* root = doc.FirstChildElement("Project"); if (!root) { std::cout << "No Project root found." << std::endl; return; } std::cout << "Project name: " << (root->Attribute("name") ? root->Attribute("name") : "N/A") << std::endl; std::cout << "Theme ID: " << (root->Attribute("themeId") ? root->Attribute("themeId") : "N/A") << std::endl; std::cout << "Version: " << (root->Attribute("version") ? root->Attribute("version") : "N/A") << std::endl; std::cout << "Template ID: " << (root->Attribute("templateID") ? root->Attribute("templateID") : "N/A") << std::endl; XMLElement* audioDucking = root->FirstChildElement("AudioDuckingProperties"); if (audioDucking) { std::cout << "Emphasis placeholder ID: " << (audioDucking->Attribute("emphasisPlaceholderID") ? audioDucking->Attribute("emphasisPlaceholderID") : "N/A") << std::endl; } XMLElement* mediaItem = root->FirstChildElement("MediaItems")->FirstChildElement("MediaItem"); while (mediaItem) { std::cout << "Media item ID: " << (mediaItem->Attribute("id") ? mediaItem->Attribute("id") : "N/A") << std::endl; std::cout << "File path: " << (mediaItem->Attribute("filePath") ? mediaItem->Attribute("filePath") : "N/A") << std::endl; std::cout << "Media item type: " << (mediaItem->Attribute("mediaItemType") ? mediaItem->Attribute("mediaItemType") : "N/A") << std::endl; std::cout << "Aspect ratio width: " << (mediaItem->Attribute("arWidth") ? mediaItem->Attribute("arWidth") : "N/A") << std::endl; std::cout << "Aspect ratio height: " << (mediaItem->Attribute("arHeight") ? mediaItem->Attribute("arHeight") : "N/A") << std::endl; std::cout << "Duration: " << (mediaItem->Attribute("duration") ? mediaItem->Attribute("duration") : "N/A") << std::endl; std::cout << "Song title: " << (mediaItem->Attribute("songTitle") ? mediaItem->Attribute("songTitle") : "N/A") << std::endl; std::cout << "Song artist: " << (mediaItem->Attribute("songArtist") ? mediaItem->Attribute("songArtist") : "N/A") << std::endl; std::cout << "Song album: " << (mediaItem->Attribute("songAlbum") ? mediaItem->Attribute("songAlbum") : "N/A") << std::endl; std::cout << "Song copyright URL: " << (mediaItem->Attribute("songCopyrightUrl") ? mediaItem->Attribute("songCopyrightUrl") : "N/A") << std::endl; std::cout << "Song artist URL: " << (mediaItem->Attribute("songArtistUrl") ? mediaItem->Attribute("songArtistUrl") : "N/A") << std::endl; std::cout << "Song audio file URL: " << (mediaItem->Attribute("songAudioFileUrl") ? mediaItem->Attribute("songAudioFileUrl") : "N/A") << std::endl; std::cout << "Stabilization mode: " << (mediaItem->Attribute("stabilizationMode") ? mediaItem->Attribute("stabilizationMode") : "N/A") << std::endl; mediaItem = mediaItem->NextSiblingElement("MediaItem"); } XMLElement* extentSelector = doc.FirstChildElement("ExtentSelector"); while (extentSelector) { std::cout << "Extent ID: " << (extentSelector->Attribute("extentID") ? extentSelector->Attribute("extentID") : "N/A") << std::endl; std::cout << "Gap before: " << (extentSelector->Attribute("gapBefore") ? extentSelector->Attribute("gapBefore") : "N/A") << std::endl; std::cout << "Primary track: " << (extentSelector->Attribute("primaryTrack") ? extentSelector->Attribute("primaryTrack") : "N/A") << std::endl; extentSelector = extentSelector->NextSiblingElement("ExtentSelector"); } XMLElement* extentRef = doc.FirstChildElement("ExtentRef"); while (extentRef) { std::cout << "Extent reference ID: " << (extentRef->Attribute("id") ? extentRef->Attribute("id") : "N/A") << std::endl; extentRef = extentRef->NextSiblingElement("ExtentRef"); } } bool write(const std::string& newFilepath = "") { const std::string target = newFilepath.empty() ? filepath : newFilepath; if (doc.SaveFile(target.c_str()) != XML_SUCCESS) { std::cerr << "Error saving file: " << doc.ErrorStr() << std::endl; return false; } return true; } }; // Example usage: // int main() { // WLMPHandler handler("example.wlmp"); // if (handler.read()) { // handler.printProperties(); // handler.write("modified.wlmp"); // } // return 0; // } // ===== end task-812 .WLMP ===== // ===== task-813 .WLS [C++] ===== #include #include #include #include #include #include class WLSHandler { private: std::string filepath; std::map> properties; public: WLSHandler(const std::string& fp) : filepath(fp) {} void readAndDecode() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Failed to open file." << std::endl; return; } std::vector lines; std::string line; while (std::getline(file, line)) { lines.push_back(line); } file.close(); std::string currentProp; std::string shebang = (!lines.empty() && lines[0].rfind("#!", 0) == 0) ? lines[0] : ""; if (!shebang.empty()) { properties["Shebang line"] = {shebang}; } std::regex markerRegex(R"(\(\* ::(\w+):: \*\))"); std::smatch match; for (const auto& ln : lines) { std::string trimmed = ln; trimmed.erase(0, trimmed.find_first_not_of(" \t")); trimmed.erase(trimmed.find_last_not_of(" \t") + 1); if (std::regex_match(trimmed, match, markerRegex)) { currentProp = match[1].str(); if (properties.find(currentProp) == properties.end()) { properties[currentProp] = {}; } } else if (!currentProp.empty()) { properties[currentProp].push_back(trimmed); } } } void printProperties() const { for (const auto& [key, value] : properties) { std::cout << key << ":" << std::endl; for (const auto& v : value) { std::cout << v << std::endl; } std::cout << std::endl; } } void write(const std::string& newFilepath = "") const { std::string writePath = newFilepath.empty() ? filepath : newFilepath; std::ofstream file(writePath); if (!file.is_open()) { std::cerr << "Failed to write file." << std::endl; return; } auto it = properties.find("Shebang line"); if (it != properties.end()) { file << it->second[0] << "\n"; } for (const auto& [key, value] : properties) { if (key != "Shebang line") { file << "(* ::" << key << ":: *)" << "\n"; for (const auto& v : value) { file << v << "\n"; } } } file.close(); } }; // Example usage: // int main() { // WLSHandler handler("example.wls"); // handler.readAndDecode(); // handler.printProperties(); // handler.write("output.wls"); // return 0; // } // ===== end task-813 .WLS ===== // ===== task-814 .WMA [C++] ===== #include #include #include #include #include #include #include class WMAParser { private: std::string filename; std::map properties; std::string readGUID(std::ifstream& file) { uint32_t data1; uint16_t data2, data3; uint8_t data4[8]; file.read(reinterpret_cast(&data1), 4); file.read(reinterpret_cast(&data2), 2); file.read(reinterpret_cast(&data3), 2); file.read(reinterpret_cast(data4), 8); std::stringstream ss; ss << std::hex << std::setfill('0') << std::setw(8) << data1 << "-" << std::setw(4) << data2 << "-" << std::setw(4) << data3 << "-" << std::setw(2) << static_cast(data4[0]) << std::setw(2) << static_cast(data4[1]) << "-"; for (int i = 2; i < 8; i++) ss << std::setw(2) << static_cast(data4[i]); return ss.str(); } uint64_t readQWord(std::ifstream& file) { uint64_t value; file.read(reinterpret_cast(&value), 8); return value; } std::string readString(std::ifstream& file, uint16_t length) { std::vector buffer(length); file.read(buffer.data(), length); std::wstring wstr(reinterpret_cast(buffer.data()), length / 2); return std::string(wstr.begin(), wstr.end()); } public: WMAParser(const std::string& fn) : filename(fn) {} void readAndDecode() { std::ifstream file(filename, std::ios::binary); if (!file) throw std::runtime_error("Cannot open file"); std::string headerGuid = readGUID(file); if (headerGuid != "75b22630-668e-11cf-a6d9-00aa0062ce6c") { // Note: byte order adjusted throw std::runtime_error("Not a valid WMA/ASF file"); } uint64_t headerSize = readQWord(file); uint32_t numObjects; file.read(reinterpret_cast(&numObjects), 4); file.seekg(2, std::ios::cur); // Skip reserved for (uint32_t i = 0; i < numObjects; ++i) { std::string objGuid = readGUID(file); uint64_t objSize = readQWord(file); auto pos = file.tellg(); if (objGuid == "a1dcab8c-47a9-11cf-8ee4-00c00c205365") { // File Properties, note byte order properties["file_id"] = readGUID(file); properties["file_size"] = std::to_string(readQWord(file)); uint64_t creationTime = readQWord(file); properties["creation_date"] = std::to_string(creationTime); // Raw for simplicity properties["data_packets_count"] = std::to_string(readQWord(file)); properties["play_duration"] = std::to_string(readQWord(file) / 10000); properties["send_duration"] = std::to_string(readQWord(file) / 10000); properties["preroll"] = std::to_string(readQWord(file)); uint32_t flags, minPkt, maxPkt, maxBit; file.read(reinterpret_cast(&flags), 4); file.read(reinterpret_cast(&minPkt), 4); file.read(reinterpret_cast(&maxPkt), 4); file.read(reinterpret_cast(&maxBit), 4); properties["flags"] = std::to_string(flags); properties["min_packet_size"] = std::to_string(minPkt); properties["max_packet_size"] = std::to_string(maxPkt); properties["max_bitrate"] = std::to_string(maxBit); } else if (objGuid == "9107dcb7-b7a9-11cf-8ee6-00c00c205365") { // Stream Properties properties["stream_type_guid"] = readGUID(file); properties["error_correction_guid"] = readGUID(file); properties["time_offset"] = std::to_string(readQWord(file)); uint32_t typeLen, errLen; file.read(reinterpret_cast(&typeLen), 4); file.read(reinterpret_cast(&errLen), 4); uint16_t streamNum, flags; file.read(reinterpret_cast(&streamNum), 2); file.read(reinterpret_cast(&flags), 2); properties["stream_number"] = std::to_string(streamNum & 0x7F); properties["stream_flags"] = std::to_string(flags); uint16_t formatTag, channels, blockAlign, bitsSample; uint32_t samplesSec, avgBytes; file.read(reinterpret_cast(&formatTag), 2); file.read(reinterpret_cast(&channels), 2); file.read(reinterpret_cast(&samplesSec), 4); file.read(reinterpret_cast(&avgBytes), 4); file.read(reinterpret_cast(&blockAlign), 2); file.read(reinterpret_cast(&bitsSample), 2); properties["audio_format_tag"] = std::to_string(formatTag); properties["channels"] = std::to_string(channels); properties["samples_per_second"] = std::to_string(samplesSec); properties["avg_bytes_per_second"] = std::to_string(avgBytes); properties["block_alignment"] = std::to_string(blockAlign); properties["bits_per_sample"] = std::to_string(bitsSample); } else if (objGuid == "3326b275-8e66-11cf-a6d9-00aa0062ce6c") { // Content Description uint16_t lengths[5]; for (int j = 0; j < 5; j++) file.read(reinterpret_cast(&lengths[j]), 2); properties["title"] = readString(file, lengths[0]); properties["author"] = readString(file, lengths[1]); properties["copyright"] = readString(file, lengths[2]); properties["description"] = readString(file, lengths[3]); properties["rating"] = readString(file, lengths[4]); } file.seekg(pos + (std::streampos)(objSize - 24)); } file.close(); } void printProperties() { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& outputFilename) { std::ofstream out(outputFilename, std::ios::binary); if (!out) return; // Placeholder for header writing out.close(); } }; // Usage example: // int main() { // WMAParser parser("sample.wma"); // parser.readAndDecode(); // parser.printProperties(); // parser.write("output.wma"); // return 0; // } // ===== end task-814 .WMA ===== // ===== task-815 .WMBD [C++] ===== #include #include #include #include #include class WMDBHandler { private: std::string filepath; CComPtr dbInit; CComPtr dbCreateSession; CComPtr dbCreateCommand; CComPtr command; public: WMDBHandler(const std::string& fp) : filepath(fp) {} HRESULT open() { HRESULT hr = CoCreateInstance(CLSID_MSDASQL, NULL, CLSCTX_INPROC_SERVER, IID_IDBInitialize, (void**)&dbInit); if (SUCCEEDED(hr)) { std::wstring connStr = L"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + std::wstring(filepath.begin(), filepath.end()) + L";"; CComPtr dbProps; dbInit->QueryInterface(IID_IDBProperties, (void**)&dbProps); DBPROP rgProps[1] = {0}; DBPROPSET rgPropSets[1]; rgProps[0].dwPropertyID = DBPROP_INIT_PROVIDERSTRING; rgProps[0].vValue.vt = VT_BSTR; rgProps[0].vValue.bstrVal = SysAllocString(connStr.c_str()); rgPropSets[0].rgProperties = rgProps; rgPropSets[0].cProperties = 1; rgPropSets[0].guidPropertySet = DBPROPSET_DBINIT; dbProps->SetProperties(1, rgPropSets); hr = dbInit->Initialize(); if (SUCCEEDED(hr)) { dbInit->QueryInterface(IID_IDBCreateSession, (void**)&dbCreateSession); dbCreateSession->CreateSession(NULL, IID_IDBCreateCommand, (IUnknown**)&dbCreateCommand); dbCreateCommand->CreateCommand(NULL, IID_ICommandText, (IUnknown**)&command); } } return hr; } void readProperties() { command->SetCommandText(DBGUID_DBSQL, L"SELECT FileName, FileLocation, FileSize, DateAdded, DateLastViewed, TimesViewed, YearCreated, WidthPixels, AdditionalInfo FROM Content"); CComPtr rowset; if (SUCCEEDED(command->Execute(NULL, NULL, NULL, NULL, (IUnknown**)&rowset))) { // Iterate rowset and print (simplified; use Accessor for columns) std::cout << "Properties dumped to console." << std::endl; } } void writeProperty(/* parameters */) { // Similar to execute insert query } void close() { // Release COM objects } }; // ===== end task-815 .WMBD ===== // ===== task-816 .WMF [C++] ===== #include #include #include #include class WMFHandler { private: std::string filepath; uint32_t key, reserved; uint16_t handle, inch, checksum; int16_t left, top, right, bottom; uint16_t fileType, headerSize, version, numObjects, numParams; uint32_t fileSize, maxRecord; bool hasPlaceable = false; public: WMFHandler(const std::string& filepath) : filepath(filepath) {} void readAndDecode() { std::ifstream file(filepath, std::ios::binary); if (!file) { std::cerr << "Error opening file." << std::endl; return; } std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); size_t offset = 0; // Check and parse optional placeable header if (data.size() >= 22) { key = *reinterpret_cast(&data[offset]); if (key == 0x9AC6CDD7) { hasPlaceable = true; handle = *reinterpret_cast(&data[offset + 4]); left = *reinterpret_cast(&data[offset + 6]); top = *reinterpret_cast(&data[offset + 8]); right = *reinterpret_cast(&data[offset + 10]); bottom = *reinterpret_cast(&data[offset + 12]); inch = *reinterpret_cast(&data[offset + 14]); reserved = *reinterpret_cast(&data[offset + 16]); checksum = *reinterpret_cast(&data[offset + 20]); offset += 22; } } // Standard header fileType = *reinterpret_cast(&data[offset]); headerSize = *reinterpret_cast(&data[offset + 2]); version = *reinterpret_cast(&data[offset + 4]); fileSize = *reinterpret_cast(&data[offset + 6]); numObjects = *reinterpret_cast(&data[offset + 10]); maxRecord = *reinterpret_cast(&data[offset + 12]); numParams = *reinterpret_cast(&data[offset + 16]); } void printProperties() { if (hasPlaceable) { std::cout << "Key: " << key << std::endl; std::cout << "Handle: " << handle << std::endl; std::cout << "Left: " << left << std::endl; std::cout << "Top: " << top << std::endl; std::cout << "Right: " << right << std::endl; std::cout << "Bottom: " << bottom << std::endl; std::cout << "Inch: " << inch << std::endl; std::cout << "Reserved: " << reserved << std::endl; std::cout << "Checksum: " << checksum << std::endl; } std::cout << "File Type: " << fileType << std::endl; std::cout << "Header Size: " << headerSize << std::endl; std::cout << "Version: " << version << std::endl; std::cout << "File Size: " << fileSize << std::endl; std::cout << "Number of Objects: " << numObjects << std::endl; std::cout << "Maximum Record Size: " << maxRecord << std::endl; std::cout << "Number of Parameters: " << numParams << std::endl; } void writeHeader(const std::string& outputPath, bool includePlaceable = false) { std::ofstream file(outputPath, std::ios::binary); if (!file) { std::cerr << "Error creating file." << std::endl; return; } if (includePlaceable) { uint32_t temp32 = 0x9AC6CDD7; file.write(reinterpret_cast(&temp32), 4); // Key uint16_t temp16 = 0; file.write(reinterpret_cast(&temp16), 2); // Handle int16_t tempS16 = 0; file.write(reinterpret_cast(&tempS16), 2); // Left tempS16 = 0; file.write(reinterpret_cast(&tempS16), 2); // Top tempS16 = 100; file.write(reinterpret_cast(&tempS16), 2); // Right tempS16 = 100; file.write(reinterpret_cast(&tempS16), 2); // Bottom temp16 = 1440; file.write(reinterpret_cast(&temp16), 2); // Inch temp32 = 0; file.write(reinterpret_cast(&temp32), 4); // Reserved temp16 = 0; file.write(reinterpret_cast(&temp16), 2); // Checksum } uint16_t temp16; uint32_t temp32; temp16 = 1; file.write(reinterpret_cast(&temp16), 2); // File Type temp16 = 9; file.write(reinterpret_cast(&temp16), 2); // Header Size temp16 = 0x0300; file.write(reinterpret_cast(&temp16), 2); // Version temp32 = 9; file.write(reinterpret_cast(&temp32), 4); // File Size temp16 = 0; file.write(reinterpret_cast(&temp16), 2); // Num Objects temp32 = 0; file.write(reinterpret_cast(&temp32), 4); // Max Record temp16 = 0; file.write(reinterpret_cast(&temp16), 2); // Num Params } }; // Example usage: // int main() { // WMFHandler handler("example.wmf"); // handler.readAndDecode(); // handler.printProperties(); // handler.writeHeader("new.wmf", true); // return 0; // } // ===== end task-816 .WMF ===== // ===== task-817 .WMV [C++] ===== #include #include #include #include #include #include // Assume uuid library or implement GUID parsing class WMVParser { private: std::string filename; std::vector data; std::map properties; // Use std::any for mixed types public: WMVParser(const std::string& fn) : filename(fn) { std::ifstream file(filename, std::ios::binary | std::ios::ate); std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(data.data(), size); parse(); } void parse() { const char* buf = data.data(); size_t offset = 0; // Helper functions auto readGUID = [&]() -> std::string { std::stringstream ss; for (int i = 0; i < 4; ++i) ss << std::hex << std::setw(2) << std::setfill('0') << (static_cast(buf[offset + 3 - i]) & 0xFF); ss << "-"; for (int i = 0; i < 2; ++i) ss << std::hex << std::setw(2) << std::setfill('0') << (static_cast(buf[offset + 5 - i + 4]) & 0xFF); ss << "-"; for (int i = 0; i < 2; ++i) ss << std::hex << std::setw(2) << std::setfill('0') << (static_cast(buf[offset + 7 - i + 4]) & 0xFF); ss << "-"; for (int i = 0; i < 2; ++i) ss << std::hex << std::setw(2) << std::setfill('0') << (static_cast(buf[offset + 8 + i]) & 0xFF); ss << "-"; for (int i = 0; i < 6; ++i) ss << std::hex << std::setw(2) << std::setfill('0') << (static_cast(buf[offset + 10 + i]) & 0xFF); offset += 16; return ss.str(); }; auto readQWORD = [&]() -> uint64_t { uint64_t val = *reinterpret_cast(buf + offset); offset += 8; return val; }; auto readDWORD = [&]() -> uint32_t { uint32_t val = *reinterpret_cast(buf + offset); offset += 4; return val; }; auto readWORD = [&]() -> uint16_t { uint16_t val = *reinterpret_cast(buf + offset); offset += 2; return val; }; auto readBYTE = [&]() -> uint8_t { uint8_t val = static_cast(buf[offset]); offset += 1; return val; }; auto readWSTRING = [&](size_t len) -> std::wstring { std::wstring str(reinterpret_cast(buf + offset), len / 2); offset += len; return str; }; std::string guid = readGUID(); if (guid != "3026b275-8e66-cf11-a6d9-00aa0062ce6c") { throw std::runtime_error("Not a valid WMV/ASF file"); } uint64_t headerSize = readQWORD(); std::map header; header["NumberOfHeaderObjects"] = readDWORD(); header["Reserved1"] = readBYTE(); header["Reserved2"] = readBYTE(); properties["Header"] = header; // Parse sub-objects (similar to Python, omitted for brevity; implement as needed) // ... Use similar logic as in Python class ... } void printProperties() { // Implement printing logic, e.g., recursive map print std::cout << "Properties:" << std::endl; // ... Custom print for map ... } void write(const std::string& outputFilename) { std::ofstream out(outputFilename, std::ios::binary); out.write(data.data(), data.size()); } }; // Example usage: // int main() { // WMVParser parser("example.wmv"); // parser.printProperties(); // parser.write("modified.wmv"); // return 0; // } // ===== end task-817 .WMV ===== // ===== task-818 .WOS [C++] ===== #include #include #include #include #include #include #include class WOSFile { private: std::vector>> records; public: WOSFile(const std::string& filepath = "") { if (!filepath.empty()) { read(filepath); } } void read(const std::string& filepath) { std::wifstream file(filepath, std::ios::binary); file.imbue(std::locale(file.getloc(), new std::codecvt_utf8)); if (!file) { std::cerr << "Error opening file" << std::endl; return; } std::map> currentRecord; std::string currentTag; std::wstring lineW; while (std::getline(file, lineW)) { std::string line(lineW.begin(), lineW.end()); line.erase(line.find_last_not_of(" \r\n") + 1); if (line == "ER") { if (!currentRecord.empty()) { records.push_back(currentRecord); } currentRecord.clear(); currentTag.clear(); } else if (line.length() >= 3 && line[2] == ' ' && isupper(line[0]) && isupper(line[1])) { currentTag = line.substr(0, 2); std::string value = line.substr(3); value.erase(0, value.find_first_not_of(' ')); value.erase(value.find_last_not_of(' ') + 1); if (currentRecord.find(currentTag) == currentRecord.end()) { currentRecord[currentTag] = std::vector(); } if (!value.empty()) { currentRecord[currentTag].push_back(value); } } else if (!currentTag.empty() && !line.empty()) { currentRecord[currentTag].push_back(line); } } if (!currentRecord.empty()) { records.push_back(currentRecord); } } void write(const std::string& filepath) { std::wofstream file(filepath, std::ios::binary); file.imbue(std::locale(file.getloc(), new std::codecvt_utf8)); file << L"\uFEFF"; // UTF-8 BOM file << L"FN ISI Export Format\nVR 1.0\n"; for (const auto& record : records) { for (const auto& entry : record) { const std::string& tag = entry.first; const auto& values = entry.second; file << std::wstring(tag.begin(), tag.end()) << L" " << std::wstring(values[0].begin(), values[0].end()) << L"\n"; for (size_t i = 1; i < values.size(); ++i) { file << L" " << std::wstring(values[i].begin(), values[i].end()) << L"\n"; } } file << L"ER\n"; } file << L"EF\n"; } void printProperties() { for (size_t i = 0; i < records.size(); ++i) { std::cout << "Record " << (i + 1) << ":" << std::endl; for (const auto& entry : records[i]) { std::cout << entry.first << ": "; for (const auto& val : entry.second) { std::cout << val << " "; } std::cout << std::endl; } std::cout << std::endl; } } }; // Example usage: // int main() { // WOSFile wos("sample.wos"); // wos.printProperties(); // wos.write("output.wos"); // return 0; // } // ===== end task-818 .WOS ===== // ===== task-819 .WPS [C] ===== #include #include #include // Updated structs with all properties (strings use fixed buffers, integers/filetimes use appropriate types) typedef struct { char title[256]; char subject[256]; char author[256]; char keywords[256]; char comments[256]; char template[256]; char lastAuthor[256]; char revNumber[256]; char editTime[20]; // Sample string representation for FILETIME char lastPrinted[20]; char create_DTM[20]; char lastSave_DTM[20]; int pageCount; int wordCount; int charCount; char appName[256]; int docSecurity; } SummaryProps; typedef struct { char category[256]; char presentationTarget[256]; int bytes; int lines; int paragraphs; int slides; int notes; int hiddenSlides; int mmClips; int scaleCrop; // Boolean as int char headingPairs[512]; // Sample for vector char titlesofParts[512]; // Sample for vector char manager[256]; char company[256]; int linksUpToDate; // Boolean as int int charCountWithSpaces; int sharedDoc; // Boolean as int int hyperlinksChanged; // Boolean as int int appVersion; } DocSummaryProps; typedef struct { char* filename; FILE* file; SummaryProps summary; DocSummaryProps docSummary; } WPSFileHandler; WPSFileHandler* createWPSHandler(const char* filename) { WPSFileHandler* handler = malloc(sizeof(WPSFileHandler)); handler->filename = strdup(filename); handler->file = NULL; return handler; } int openAndDecode(WPSFileHandler* handler) { handler->file = fopen(handler->filename, "rb"); if (!handler->file) return -1; // Read magic bytes for OLE validation unsigned char magic[8]; fread(magic, 1, 8, handler->file); if (memcmp(magic, "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1", 8) != 0) { fclose(handler->file); return -1; } // Updated: Populate all fields with sample values (real impl parses streams and VT types) strcpy(handler->summary.title, "Sample Title"); strcpy(handler->summary.subject, "Sample Subject"); strcpy(handler->summary.author, "Sample Author"); strcpy(handler->summary.keywords, "Sample Keywords"); strcpy(handler->summary.comments, "Sample Comments"); strcpy(handler->summary.template, "Sample Template"); strcpy(handler->summary.lastAuthor, "Sample LastAuthor"); strcpy(handler->summary.revNumber, "Sample RevNumber"); strcpy(handler->summary.editTime, "Sample EditTime"); strcpy(handler->summary.lastPrinted, "Sample LastPrinted"); strcpy(handler->summary.create_DTM, "Sample Create_DTM"); strcpy(handler->summary.lastSave_DTM, "Sample LastSave_DTM"); handler->summary.pageCount = 10; handler->summary.wordCount = 100; handler->summary.charCount = 500; strcpy(handler->summary.appName, "Sample AppName"); handler->summary.docSecurity = 0; strcpy(handler->docSummary.category, "Sample Category"); strcpy(handler->docSummary.presentationTarget, "Sample PresentationTarget"); handler->docSummary.bytes = 1024; handler->docSummary.lines = 50; handler->docSummary.paragraphs = 10; handler->docSummary.slides = 5; handler->docSummary.notes = 2; handler->docSummary.hiddenSlides = 1; handler->docSummary.mmClips = 3; handler->docSummary.scaleCrop = 0; strcpy(handler->docSummary.headingPairs, "Sample HeadingPairs"); strcpy(handler->docSummary.titlesofParts, "Sample TitlesofParts"); strcpy(handler->docSummary.manager, "Sample Manager"); strcpy(handler->docSummary.company, "Sample Company"); handler->docSummary.linksUpToDate = 1; handler->docSummary.charCountWithSpaces = 600; handler->docSummary.sharedDoc = 0; handler->docSummary.hyperlinksChanged = 0; handler->docSummary.appVersion = 1; return 0; } void printProperties(WPSFileHandler* handler) { printf("Summary Properties:\n"); printf("Title: %s\n", handler->summary.title); printf("Subject: %s\n", handler->summary.subject); printf("Author: %s\n", handler->summary.author); printf("Keywords: %s\n", handler->summary.keywords); printf("Comments: %s\n", handler->summary.comments); printf("Template: %s\n", handler->summary.template); printf("LastAuthor: %s\n", handler->summary.lastAuthor); printf("RevNumber: %s\n", handler->summary.revNumber); printf("EditTime: %s\n", handler->summary.editTime); printf("LastPrinted: %s\n", handler->summary.lastPrinted); printf("Create_DTM: %s\n", handler->summary.create_DTM); printf("LastSave_DTM: %s\n", handler->summary.lastSave_DTM); printf("PageCount: %d\n", handler->summary.pageCount); printf("WordCount: %d\n", handler->summary.wordCount); printf("CharCount: %d\n", handler->summary.charCount); printf("AppName: %s\n", handler->summary.appName); printf("DocSecurity: %d\n", handler->summary.docSecurity); printf("\nDocument Summary Properties:\n"); printf("Category: %s\n", handler->docSummary.category); printf("PresentationTarget: %s\n", handler->docSummary.presentationTarget); printf("Bytes: %d\n", handler->docSummary.bytes); printf("Lines: %d\n", handler->docSummary.lines); printf("Paragraphs: %d\n", handler->docSummary.paragraphs); printf("Slides: %d\n", handler->docSummary.slides); printf("Notes: %d\n", handler->docSummary.notes); printf("HiddenSlides: %d\n", handler->docSummary.hiddenSlides); printf("MMClips: %d\n", handler->docSummary.mmClips); printf("ScaleCrop: %d\n", handler->docSummary.scaleCrop); printf("HeadingPairs: %s\n", handler->docSummary.headingPairs); printf("TitlesofParts: %s\n", handler->docSummary.titlesofParts); printf("Manager: %s\n", handler->docSummary.manager); printf("Company: %s\n", handler->docSummary.company); printf("LinksUpToDate: %d\n", handler->docSummary.linksUpToDate); printf("CharCountWithSpaces: %d\n", handler->docSummary.charCountWithSpaces); printf("SharedDoc: %d\n", handler->docSummary.sharedDoc); printf("HyperlinksChanged: %d\n", handler->docSummary.hyperlinksChanged); printf("AppVersion: %d\n", handler->docSummary.appVersion); } void writeProperties(WPSFileHandler* handler) { // Reopen in wb+, rewrite streams (stub for demo) printf("Properties updated (simulate write).\n"); } void closeWPSHandler(WPSFileHandler* handler) { if (handler->file) fclose(handler->file); free(handler->filename); free(handler); } // Usage example: // int main() { // WPSFileHandler* handler = createWPSHandler("example.wps"); // if (openAndDecode(handler) == 0) { // printProperties(handler); // writeProperties(handler); // } // closeWPSHandler(handler); // return 0; // } // ===== end task-819 .WPS ===== // ===== task-820 .WS [C++] ===== #include #include #include #include #include #include #include class WSFile { private: std::string filepath; std::vector bytes; std::map properties; public: WSFile(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary); if (file) { file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0, std::ios::beg); bytes.resize(size); file.read(reinterpret_cast(bytes.data()), size); decodeProperties(); } else { throw std::runtime_error("Failed to open file."); } } void decodeProperties() { if (bytes.empty()) throw std::runtime_error("No data loaded."); // Magic Number std::stringstream magicSs; for (size_t i = 0; i < 5 && i < bytes.size(); ++i) { magicSs << std::hex << std::setw(2) << std::setfill('0') << static_cast(bytes[i]) << " "; } properties["Magic Number"] = magicSs.str(); // High Bit Usage bool highBit = false; for (auto b : bytes) { if (b > 127) highBit = true; } properties["High Bit Usage"] = highBit ? "Detected" : "Not detected"; // Line Endings int hard = 0, soft = 0; for (size_t i = 0; i < bytes.size() - 1; ++i) { if (bytes[i] == 0x0D && bytes[i+1] == 0x0A) ++hard; if (bytes[i] == 0x8D && bytes[i+1] == 0x0A) ++soft; } std::stringstream leSs; leSs << "Hard Returns: " << hard << ", Soft Returns: " << soft; properties["Line Endings"] = leSs.str(); // Soft Spaces Count int softSpaces = 0; for (auto b : bytes) if (b == 0xA0) ++softSpaces; properties["Soft Spaces Count"] = std::to_string(softSpaces); // Extended Sequences std::stringstream seqSs; for (size_t i = 0; i < bytes.size() - 2; ++i) { if (bytes[i] == 0x1B && bytes[i+2] == 0x1C) { seqSs << std::hex << std::setw(2) << std::setfill('0') << static_cast(bytes[i+1]) << " "; } } properties["Extended Sequences"] = seqSs.str(); // Dot Commands std::string text(bytes.begin(), bytes.end()); std::stringstream textSs(text); std::string line, dotCmds; while (std::getline(textSs, line)) { if (line.rfind('.', 0) == 0 && line.size() >= 3) { dotCmds += line.substr(0, 3) + " "; } } properties["Dot Commands"] = dotCmds; // Formatting Controls int bold = 0, underline = 0; for (auto b : bytes) { if (b == 0x02) ++bold; if (b == 0x13) ++underline; } std::stringstream fcSs; fcSs << "Bold: " << bold << ", Underline: " << underline; properties["Formatting Controls"] = fcSs.str(); // Padding EOF Count int eofCount = 0; for (auto it = bytes.rbegin(); it != bytes.rend(); ++it) { if (*it == 0x1A) ++eofCount; else break; } properties["Padding EOF Count"] = std::to_string(eofCount); // Non-Document Mode bool nonDoc = true; for (auto b : bytes) { if (b < 32 || b > 127) nonDoc = false; } properties["Non-Document Mode"] = nonDoc ? "Likely" : "Unlikely"; } void printProperties() const { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void write(const std::string& newFilepath, const std::string& content) { std::vector header = {0x1D, 0x7D, 0x00, 0x00, 0x70}; // Example v7 magic std::vector contentBytes(content.begin(), content.end()); std::vector combined; combined.reserve(header.size() + contentBytes.size()); combined.insert(combined.end(), header.begin(), header.end()); combined.insert(combined.end(), contentBytes.begin(), contentBytes.end()); size_t paddingLen = (128 - (combined.size() % 128)) % 128; std::vector padding(paddingLen, 0x1A); combined.insert(combined.end(), padding.begin(), padding.end()); std::ofstream file(newFilepath, std::ios::binary); if (file) { file.write(reinterpret_cast(combined.data()), combined.size()); } else { throw std::runtime_error("Failed to write file."); } } }; // Example usage: // int main() { // try { // WSFile ws("sample1.ws"); // ws.read(); // ws.printProperties(); // ws.write("new.ws", "Test content\r\n"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-820 .WS ===== // ===== task-821 .WSC [C++] ===== #include #include #include #include #include #include "tinyxml2.h" // Assume TinyXML2 is linked using namespace tinyxml2; class WSCFileHandler { private: std::string filepath; XMLDocument doc; std::map registration; std::vector> properties_list; std::vector> methods; std::vector> events; std::vector> implements_handlers; std::vector> objects; std::vector> resources; std::vector> references; std::vector comments; std::vector> scripts; std::string component_id; bool package_present; public: WSCFileHandler(const std::string& filepath) : filepath(filepath), package_present(false) {} void read() { if (doc.LoadFile(filepath.c_str()) != XML_SUCCESS) { throw std::runtime_error("Failed to load file"); } extractProperties(); } void extractProperties() { XMLElement* root = doc.RootElement(); component_id = root->Attribute("id") ? root->Attribute("id") : "Default"; package_present = root->FirstChildElement("package") != nullptr; XMLElement* reg = root->FirstChildElement("registration"); if (reg) { registration["progid"] = reg->Attribute("progid") ? reg->Attribute("progid") : ""; registration["classid"] = reg->Attribute("classid") ? reg->Attribute("classid") : ""; registration["description"] = reg->Attribute("description") ? reg->Attribute("description") : ""; registration["version"] = reg->Attribute("version") ? reg->Attribute("version") : ""; registration["remotable"] = reg->Attribute("remotable") ? reg->Attribute("remotable") : ""; } XMLElement* public_elem = root->FirstChildElement("public"); if (public_elem) { for (XMLElement* prop = public_elem->FirstChildElement("property"); prop; prop = prop->NextSiblingElement("property")) { std::map prop_map; prop_map["name"] = prop->Attribute("name") ? prop->Attribute("name") : ""; prop_map["internalname"] = prop->Attribute("internalname") ? prop->Attribute("internalname") : ""; prop_map["get"] = prop->Attribute("get") ? prop->Attribute("get") : (prop->FirstChildElement("get") ? prop->FirstChildElement("get")->Attribute("internalname") : ""); prop_map["put"] = prop->Attribute("put") ? prop->Attribute("put") : (prop->FirstChildElement("put") ? prop->FirstChildElement("put")->Attribute("internalname") : ""); properties_list.push_back(prop_map); } for (XMLElement* method = public_elem->FirstChildElement("method"); method; method = method->NextSiblingElement("method")) { std::map method_map; method_map["name"] = method->Attribute("name") ? method->Attribute("name") : ""; method_map["internalname"] = method->Attribute("internalname") ? method->Attribute("internalname") : ""; method_map["dispid"] = method->Attribute("dispid") ? method->Attribute("dispid") : ""; // Parameters would require nested vectors; simplified here methods.push_back(method_map); } for (XMLElement* event = public_elem->FirstChildElement("event"); event; event = event->NextSiblingElement("event")) { std::map event_map; event_map["name"] = event->Attribute("name") ? event->Attribute("name") : ""; event_map["dispid"] = event->Attribute("dispid") ? event->Attribute("dispid") : ""; events.push_back(event_map); } } for (XMLElement* impl = root->FirstChildElement("implements"); impl; impl = impl->NextSiblingElement("implements")) { std::map impl_map; impl_map["type"] = impl->Attribute("type") ? impl->Attribute("type") : ""; impl_map["id"] = impl->Attribute("id") ? impl->Attribute("id") : ""; impl_map["default"] = impl->Attribute("default") ? impl->Attribute("default") : ""; implements_handlers.push_back(impl_map); } for (XMLElement* obj = root->FirstChildElement("object"); obj; obj = obj->NextSiblingElement("object")) { std::map obj_map; obj_map["id"] = obj->Attribute("id") ? obj->Attribute("id") : ""; obj_map["classid"] = obj->Attribute("classid") ? obj->Attribute("classid") : ""; obj_map["progid"] = obj->Attribute("progid") ? obj->Attribute("progid") : ""; objects.push_back(obj_map); } for (XMLElement* res = root->FirstChildElement("resource"); res; res = res->NextSiblingElement("resource")) { std::map res_map; res_map["id"] = res->Attribute("id") ? res->Attribute("id") : ""; res_map["content"] = res->GetText() ? res->GetText() : ""; resources.push_back(res_map); } for (XMLElement* ref = root->FirstChildElement("reference"); ref; ref = ref->NextSiblingElement("reference")) { std::map ref_map; ref_map["object"] = ref->Attribute("object") ? ref->Attribute("object") : ""; ref_map["guid"] = ref->Attribute("guid") ? ref->Attribute("guid") : ""; ref_map["version"] = ref->Attribute("version") ? ref->Attribute("version") : ""; references.push_back(ref_map); } for (XMLElement* com = root->FirstChildElement("comment"); com; com = com->NextSiblingElement("comment")) { comments.push_back(com->GetText() ? com->GetText() : ""); } for (XMLElement* scr = root->FirstChildElement("script"); scr; scr = scr->NextSiblingElement("script")) { std::map scr_map; scr_map["language"] = scr->Attribute("language") ? scr->Attribute("language") : ""; scr_map["code"] = scr->GetText() ? scr->GetText() : ""; scripts.push_back(scr_map); } } void printProperties() { std::cout << "Component ID: " << component_id << std::endl; std::cout << "Package Present: " << (package_present ? "true" : "false") << std::endl; std::cout << "Registration:" << std::endl; for (const auto& kv : registration) { std::cout << " " << kv.first << ": " << kv.second << std::endl; } std::cout << "Public Properties:" << std::endl; for (const auto& prop : properties_list) { for (const auto& kv : prop) { std::cout << " " << kv.first << ": " << kv.second << std::endl; } } // Similarly print other sections (methods, events, etc.); abbreviated for brevity } void write(const std::string& new_filepath = "") { doc.SaveFile((new_filepath.empty() ? filepath : new_filepath).c_str()); } }; // Example usage: // int main() { // try { // WSCFileHandler handler("example.wsc"); // handler.read(); // handler.printProperties(); // handler.write("modified.wsc"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-821 .WSC ===== // ===== task-822 .WTX [C++] ===== #include #include #include #include #include class WTXHandler { private: std::string filepath; std::map properties; public: WTXHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath); if (!file.is_open()) { std::cout << "File " << filepath << " does not exist." << std::endl; return; } std::string line; while (std::getline(file, line)) { line.erase(std::remove_if(line.begin(), line.end(), ::isspace), line.end()); // Trim spaces (simple) size_t pos = line.find("="); if (pos != std::string::npos) { std::string key = line.substr(0, pos); std::string value = line.substr(pos + 1); properties[key] = value; } } file.close(); } void decode() { // Plain text, decode is read read(); } void printProperties() { if (properties.empty()) { std::cout << "No properties loaded." << std::endl; return; } for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::map& newProperties) { std::ofstream file(filepath); if (!file.is_open()) { std::cout << "Could not open file for writing." << std::endl; return; } for (const auto& pair : newProperties) { file << pair.first << " = " << pair.second << std::endl; } file.close(); std::cout << "Properties written to " << filepath << std::endl; } }; // Example usage: // int main() { // WTXHandler handler("example.wtx"); // handler.decode(); // handler.printProperties(); // std::map newProps = {{"CPU Type", "Intel Pentium"}, {"CPU Speed", "100 MHz"}}; // handler.write(newProps); // return 0; // } // ===== end task-822 .WTX ===== // ===== task-823 .WUHB [C] ===== #include #include #include #include #include // For byte order if needed typedef struct { char* filename; uint8_t* data; size_t size; } WUHBHandler; WUHBHandler* wuhb_create(const char* filename) { WUHBHandler* handler = malloc(sizeof(WUHBHandler)); handler->filename = strdup(filename); handler->data = NULL; handler->size = 0; return handler; } void wuhb_read(WUHBHandler* handler) { FILE* f = fopen(handler->filename, "rb"); if (!f) { printf("Error opening file.\n"); return; } fseek(f, 0, SEEK_END); handler->size = ftell(f); fseek(f, 0, SEEK_SET); handler->data = malloc(handler->size); fread(handler->data, 1, handler->size, f); fclose(f); wuhb_decode_and_print(handler); } void wuhb_decode_and_print(WUHBHandler* handler) { if (!handler->data) { printf("No data loaded.\n"); return; } // IVFC Header (assuming little-endian) char ivfc_magic[5] = {0}; strncpy(ivfc_magic, (char*)handler->data, 4); uint32_t magic_num = *(uint32_t*)(handler->data + 4); uint32_t master_hash_size = *(uint32_t*)(handler->data + 8); uint64_t level1_offset = *(uint64_t*)(handler->data + 12); uint64_t level1_size = *(uint64_t*)(handler->data + 20); uint32_t level1_block_log = *(uint32_t*)(handler->data + 28); uint64_t level2_offset = *(uint64_t*)(handler->data + 36); uint64_t level2_size = *(uint64_t*)(handler->data + 44); uint32_t level2_block_log = *(uint32_t*)(handler->data + 52); uint64_t level3_offset = *(uint64_t*)(handler->data + 60); uint64_t level3_size = *(uint64_t*)(handler->data + 68); uint32_t level3_block_log = *(uint32_t*)(handler->data + 76); uint32_t optional_size = *(uint32_t*)(handler->data + 84); printf("IVFC Magic: %s\n", ivfc_magic); printf("Magic Number: 0x%08X\n", magic_num); printf("Master Hash Size: %u\n", master_hash_size); printf("Level 1 Logical Offset: %lu\n", level1_offset); printf("Level 1 Hashdata Size: %lu\n", level1_size); printf("Level 1 Block Size (log2): %u\n", level1_block_log); printf("Level 2 Logical Offset: %lu\n", level2_offset); printf("Level 2 Hashdata Size: %lu\n", level2_size); printf("Level 2 Block Size (log2): %u\n", level2_block_log); printf("Level 3 Logical Offset: %lu\n", level3_offset); printf("Level 3 Hashdata Size: %lu\n", level3_size); printf("Level 3 Block Size (log2): %u\n", level3_block_log); printf("Optional Info Size: %u\n", optional_size); // Level 3 Header size_t level3_start = (size_t)level3_offset; uint32_t header_len = *(uint32_t*)(handler->data + level3_start); uint32_t dir_hash_offset = *(uint32_t*)(handler->data + level3_start + 4); uint32_t dir_hash_len = *(uint32_t*)(handler->data + level3_start + 8); uint32_t dir_meta_offset = *(uint32_t*)(handler->data + level3_start + 12); uint32_t dir_meta_len = *(uint32_t*)(handler->data + level3_start + 16); uint32_t file_hash_offset = *(uint32_t*)(handler->data + level3_start + 20); uint32_t file_hash_len = *(uint32_t*)(handler->data + level3_start + 24); uint32_t file_meta_offset = *(uint32_t*)(handler->data + level3_start + 28); uint32_t file_meta_len = *(uint32_t*)(handler->data + level3_start + 32); uint32_t file_data_offset = *(uint32_t*)(handler->data + level3_start + 36); printf("\nLevel 3 Header Length: %u\n", header_len); printf("Directory Hash Table Offset: %u\n", dir_hash_offset); printf("Directory Hash Table Length: %u\n", dir_hash_len); printf("Directory Metadata Table Offset: %u\n", dir_meta_offset); printf("Directory Metadata Table Length: %u\n", dir_meta_len); printf("File Hash Table Offset: %u\n", file_hash_offset); printf("File Hash Table Length: %u\n", file_hash_len); printf("File Metadata Table Offset: %u\n", file_meta_offset); printf("File Metadata Table Length: %u\n", file_meta_len); printf("File Data Offset: %u\n", file_data_offset); } void wuhb_write(WUHBHandler* handler, const char* output_filename) { FILE* f = fopen(output_filename, "wb"); if (!f) { printf("Error opening output file.\n"); return; } // Minimal header fwrite("IVFC", 1, 4, f); uint32_t magic_num = 0x10000; fwrite(&magic_num, sizeof(uint32_t), 1, f); // Add remaining with examples... fclose(f); printf("Minimal .WUHB written to %s\n", output_filename); } void wuhb_destroy(WUHBHandler* handler) { free(handler->data); free(handler->filename); free(handler); } // Example usage: WUHBHandler* h = wuhb_create("example.wuhb"); wuhb_read(h); wuhb_write(h, "new.wuhb"); wuhb_destroy(h); // ===== end task-823 .WUHB ===== // ===== task-824 .X [C] ===== #include #include #include typedef struct { char magic[5]; char major[3]; char minor[3]; char format_type[5]; char float_size[5]; } XFileHeader; void read_xfile(const char* filename, XFileHeader* header) { FILE* file = fopen(filename, "rb"); if (file) { char buffer[16]; fread(buffer, 1, 16, file); strncpy(header->magic, buffer, 4); header->magic[4] = '\0'; strncpy(header->major, buffer + 4, 2); header->major[2] = '\0'; strncpy(header->minor, buffer + 6, 2); header->minor[2] = '\0'; strncpy(header->format_type, buffer + 8, 4); header->format_type[4] = '\0'; strncpy(header->float_size, buffer + 12, 4); header->float_size[4] = '\0'; fclose(file); print_properties(header); } else { printf("Failed to open file.\n"); } } void print_properties(const XFileHeader* header) { printf("Magic number: %s\n", header->magic); printf("Major version: %s\n", header->major); printf("Minor version: %s\n", header->minor); printf("Format type: %s\n", header->format_type); printf("Float size: %s\n", header->float_size); } void write_xfile(const char* filename, const char* magic, const char* major, const char* minor, const char* format_type, const char* float_size) { FILE* file = fopen(filename, "wb"); if (file) { fwrite(magic, 1, 4, file); fwrite(major, 1, 2, file); fwrite(minor, 1, 2, file); fwrite(format_type, 1, 4, file); fwrite(float_size, 1, 4, file); // Minimal content (e.g., empty template for a valid but empty file) const char* content = "template Empty {}"; fwrite(content, 1, strlen(content), file); fclose(file); } else { printf("Failed to open file for writing.\n"); } } // Example usage: // int main() { // XFileHeader header; // read_xfile("sample.x", &header); // write_xfile("output.x", "xof ", "03", "02", "txt ", "0032"); // return 0; // } // ===== end task-824 .X ===== // ===== task-825 .X3D [C++] ===== #include #include #include #include #include #include #include class X3DParser { public: std::string xmlVer; std::string encoding; std::string pubId; std::string sysId; std::string profile; std::string x3dVer; std::string xmlnsXsd; std::string schemaLoc; std::map> metadata; void load(const std::string& filename) { std::ifstream file(filename); std::stringstream buffer; buffer << file.rdbuf(); std::string text = buffer.str(); std::regex xmlRegex(R"(<\?xml version="([^"]+)" encoding="([^"]+)"\?>)"); std::smatch match; if (std::regex_search(text, match, xmlRegex)) { xmlVer = match[1]; encoding = match[2]; } std::regex docRegex(R"()"); if (std::regex_search(text, match, docRegex)) { pubId = match[1]; sysId = match[2]; } // Extract root attributes size_t x3dPos = text.find("", x3dPos); std::string rootStr = text.substr(x3dPos, endPos - x3dPos + 1); std::regex attrRegex(R"(\s(profile|version|xmlns:xsd|xsd:noNamespaceSchemaLocation)="([^"]*)")"); auto iter = std::sregex_iterator(rootStr.begin(), rootStr.end(), attrRegex); for (std::sregex_iterator i = iter; i != std::sregex_iterator(); ++i) { std::smatch m = *i; std::string attr = m[1]; std::string val = m[2]; if (attr == "profile") profile = val; else if (attr == "version") x3dVer = val; else if (attr == "xmlns:xsd") xmlnsXsd = val; else if (attr == "xsd:noNamespaceSchemaLocation") schemaLoc = val; } } // Extract metadata size_t headPos = text.find(""); if (headPos != std::string::npos) { size_t endHead = text.find("", headPos); std::string headStr = text.substr(headPos, endHead - headPos + 7); std::regex metaRegex(R"()"); auto metaIter = std::sregex_iterator(headStr.begin(), headStr.end(), metaRegex); for (std::sregex_iterator i = metaIter; i != std::sregex_iterator(); ++i) { std::smatch m = *i; std::string name = m[1]; std::string content = m[2]; metadata[name].push_back(content); } } } void printProperties() { std::cout << "XML Version: " << (xmlVer.empty() ? "N/A" : xmlVer) << std::endl; std::cout << "Encoding: " << (encoding.empty() ? "N/A" : encoding) << std::endl; std::cout << "DOCTYPE Public Identifier: " << (pubId.empty() ? "N/A" : pubId) << std::endl; std::cout << "DOCTYPE System Identifier: " << (sysId.empty() ? "N/A" : sysId) << std::endl; std::cout << "X3D Profile: " << (profile.empty() ? "N/A" : profile) << std::endl; std::cout << "X3D Version: " << (x3dVer.empty() ? "N/A" : x3dVer) << std::endl; std::cout << "xmlns:xsd: " << (xmlnsXsd.empty() ? "N/A" : xmlnsXsd) << std::endl; std::cout << "xsd:noNamespaceSchemaLocation: " << (schemaLoc.empty() ? "N/A" : schemaLoc) << std::endl; for (const auto& pair : metadata) { std::cout << pair.first << ": "; for (size_t i = 0; i < pair.second.size(); ++i) { if (i > 0) std::cout << ", "; std::cout << pair.second[i]; } std::cout << std::endl; } } void write(const std::string& filename) { std::ofstream out(filename); out << "\n"; out << "\n"; out << "\n"; out << "\n"; for (const auto& pair : metadata) { for (const auto& val : pair.second) { out << "\n"; } } out << "\n\n"; out.close(); } }; // Example usage: // int main() { // X3DParser parser; // parser.load("example.x3d"); // parser.printProperties(); // parser.write("output.x3d"); // return 0; // } // ===== end task-825 .X3D ===== // ===== task-826 .XAR [C++] ===== #include #include #include #include #include // Assume included or linked class XarHandler { private: struct Header { uint32_t magic; uint16_t size; uint16_t version; uint64_t toc_comp_len; uint64_t toc_uncomp_len; uint32_t cksum_alg; }; Header header; tinyxml2::XMLDocument tocDoc; std::vector heap; public: void open(const std::string& filepath) { std::ifstream file(filepath, std::ios::binary); std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); // Parse header (big-endian) memcpy(&header.magic, data.data(), 4); header.magic = __builtin_bswap32(header.magic); if (header.magic != 0x78617221) throw std::runtime_error("Invalid magic"); // Similarly for other fields using __builtin_bswap16/32/64 // Decompress TOC uLongf uncomp_len = header.toc_uncomp_len; std::vector toc_uncomp(uncomp_len); int ret = uncompress((Bytef*)toc_uncomp.data(), &uncomp_len, (Bytef*)(data.data() + header.size), header.toc_comp_len); if (ret != Z_OK) throw std::runtime_error("Decompression failed"); // Parse XML tocDoc.Parse(toc_uncomp.data()); // Heap heap.assign(data.begin() + header.size + header.toc_comp_len, data.end()); } void printProperties() { std::cout << "Header Properties:" << std::endl; std::cout << "- Magic: xar!" << std::endl; // Print others auto toc = tocDoc.FirstChildElement("xar")->FirstChildElement("toc"); std::cout << "\nArchive Properties:" << std::endl; std::cout << "- Creation Time: " << (toc->FirstChildElement("creation-time") ? toc->FirstChildElement("creation-time")->GetText() : "N/A") << std::endl; // Similarly for checksum, files, etc. } void write(const std::string& filepath, /* files */) { // Build XML with tinyxml2, compress with compress(), build header, write file + compressed TOC + heap } }; // ===== end task-826 .XAR ===== // ===== task-826 .XAR [C] ===== struct xar_header { uint32_t magic; // 'xar!' (0x78617221) uint16_t size; // Header size (usually 28, or >28 if extended with algorithm name) uint16_t version; // Always 1 uint64_t toc_length_compressed; // Size of compressed TOC uint64_t toc_length_uncompressed; // Size of uncompressed TOC uint32_t cksum_alg; // TOC checksum algorithm (0: none, 1: SHA1, 3: MD5, 4: SHA256, 5: SHA512) // If size > 28, additional bytes for checksum algorithm name (e.g., null-terminated string) }; // ===== end task-826 .XAR ===== // ===== task-827 .XRBL [C++] ===== #include #include #include #include "tinyxml2.h" // Assume tinyxml2 library is available using namespace tinyxml2; class XBRLParser { private: std::string filename; XMLDocument doc; public: XBRLParser(const std::string& fn) : filename(fn) {} void read() { if (doc.LoadFile(filename.c_str()) != XML_SUCCESS) { throw std::runtime_error("Failed to load file."); } XMLElement* root = doc.RootElement(); if (std::string(root->Name()) != "xbrl") { throw std::runtime_error("Not a valid XBRL file (missing root)."); } } void printProperties() { XMLElement* root = doc.RootElement(); if (!root) { throw std::runtime_error("File not read yet. Call read() first."); } std::cout << "XBRL Properties:" << std::endl; std::cout << "- XML Version: " << (doc.Version() ? doc.Version() : "1.0") << std::endl; // Encoding not directly available in tinyxml2; assume UTF-8 std::cout << "- Encoding: UTF-8" << std::endl; std::cout << "- Root Element: " << root->Name() << std::endl; std::cout << "- Namespaces:" << std::endl; // Namespaces in attributes for (const XMLAttribute* attr = root->FirstAttribute(); attr; attr = attr->Next()) { if (std::string(attr->Name()).find("xmlns") == 0) { std::cout << " " << attr->Name() << ": " << attr->Value() << std::endl; } } XMLElement* schemaRef = root->FirstChildElement("schemaRef"); int schemaCount = 0; std::cout << "- Schema References: "; while (schemaRef) { schemaCount++; std::cout << schemaCount << " href: " << (schemaRef->Attribute("xlink:href") ? schemaRef->Attribute("xlink:href") : "") << std::endl; schemaRef = schemaRef->NextSiblingElement("schemaRef"); } if (schemaCount == 0) std::cout << "0" << std::endl; XMLElement* linkbaseRef = root->FirstChildElement("linkbaseRef"); int linkbaseCount = 0; std::cout << "- Linkbase References: "; while (linkbaseRef) { linkbaseCount++; std::cout << linkbaseCount << " href: " << (linkbaseRef->Attribute("xlink:href") ? linkbaseRef->Attribute("xlink:href") : "") << ", role: " << (linkbaseRef->Attribute("xlink:role") ? linkbaseRef->Attribute("xlink:role") : "none") << std::endl; linkbaseRef = linkbaseRef->NextSiblingElement("linkbaseRef"); } if (linkbaseCount == 0) std::cout << "0" << std::endl; XMLElement* context = root->FirstChildElement("context"); int contextCount = 0; while (context) { contextCount++; context = context->NextSiblingElement("context"); } std::cout << "- Contexts: " << contextCount << std::endl; XMLElement* unit = root->FirstChildElement("unit"); int unitCount = 0; while (unit) { unitCount++; unit = unit->NextSiblingElement("unit"); } std::cout << "- Units: " << unitCount << std::endl; // Facts: count elements with contextRef int factCount = 0; XMLElement* elem = root->FirstChildElement(); while (elem) { if (elem->Attribute("contextRef")) factCount++; elem = elem->NextSiblingElement(); } std::cout << "- Facts: " << factCount << std::endl; } void write(const std::string& newFilename) { if (doc.SaveFile(newFilename.c_str()) != XML_SUCCESS) { throw std::runtime_error("Failed to write file."); } } }; // Example usage: // int main() { // try { // XBRLParser parser("example.xbrl"); // parser.read(); // parser.printProperties(); // parser.write("output.xbrl"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-827 .XRBL ===== // ===== task-828 .XCF [C++] ===== #include #include #include #include #include #include #include // Link -lz class XCFHandlerCpp { private: std::ifstream file; int compression = 0; int pointer_size = 4; int version = 0; uint32_t read_uint32() { uint32_t val; file.read(reinterpret_cast(&val), 4); val = __builtin_bswap32(val); return val; } int32_t read_int32() { int32_t val; file.read(reinterpret_cast(&val), 4); val = __builtin_bswap32(val); return val; } uint64_t read_uint64() { uint32_t high = read_uint32(); uint32_t low = read_uint32(); return (static_cast(high) << 32) | low; } float read_float() { uint32_t val = read_uint32(); float f; std::memcpy(&f, &val, sizeof(float)); return f; } uint64_t read_pointer() { return pointer_size == 4 ? read_uint32() : read_uint64(); } std::string read_string() { uint32_t len = read_uint32(); std::vector buf(len); file.read(buf.data(), len); return std::string(buf.data(), len - 1); } std::string parse_parasites(std::streampos end_pos) { std::string res; while (file.tellg() < end_pos) { std::string name = read_string(); uint32_t flags = read_uint32(); uint32_t size = read_uint32(); std::vector data(size); file.read(data.data(), size); res += "Name: " + name + ", Flags: " + std::to_string(flags) + ", Size: " + std::to_string(size) + ", Data: (binary)\n"; } return res; } struct Prop { uint32_t type; std::string value; }; Prop parse_property() { uint32_t type = read_uint32(); uint32_t len = read_uint32(); std::streampos start = file.tellg(); std::streampos end = start + static_cast(len); std::string value = "Type: " + std::to_string(type) + ", Length: " + std::to_string(len); if (type == 0) { } else if (type == 1) { uint32_t n = read_uint32(); std::string colors; for (uint32_t i = 0; i < n; i++) { uint8_t r, g, b; file.read(reinterpret_cast(&r), 1); file.read(reinterpret_cast(&g), 1); file.read(reinterpret_cast(&b), 1); colors += "(" + std::to_string(r) + "," + std::to_string(g) + "," + std::to_string(b) + ")"; } value += ", Num Colors: " + std::to_string(n) + ", Colors: " + colors; } // ... (add cases for all types similar to above) else { value += ", Unknown Payload: (skipped)"; file.seekg(end); } if (file.tellg() > end) file.seekg(end); return {type, value}; } void parse_property_list(const std::string& context) { std::cout << "Properties for " << context << ":" << std::endl; while (true) { Prop prop = parse_property(); std::cout << prop.value << std::endl; if (prop.type == 0) break; } } void decompress_rle(const std::vector& data, int expected, std::vector& decomp) { size_t i = 0; while (decomp.size() < static_cast(expected) && i < data.size()) { uint8_t opcode = data[i++]; if (opcode <= 126) { int count = opcode + 1; uint8_t val = data[i++]; for (int j = 0; j < count; j++) decomp.push_back(val); } else if (opcode == 127) { uint8_t p = data[i++]; uint8_t q = data[i++]; int count = p * 256 + q; uint8_t val = data[i++]; for (int j = 0; j < count; j++) decomp.push_back(val); } else if (opcode == 128) { uint8_t p = data[i++]; uint8_t q = data[i++]; int count = p * 256 + q; for (int j = 0; j < count; j++) decomp.push_back(data[i++]); } else if (opcode >= 129) { int count = 256 - opcode; for (int j = 0; j < count; j++) decomp.push_back(data[i++]); } } } void parse_hierarchy(uint64_t hptr) { file.seekg(hptr); uint32_t width = read_uint32(); uint32_t height = read_uint32(); uint32_t bpp = read_uint32(); std::cout << "Hierarchy: Width=" << width << ", Height=" << height << ", BPP=" << bpp << std::endl; std::vector levels; while (true) { uint64_t lptr = read_pointer(); if (lptr == 0) break; levels.push_back(lptr); } for (size_t idx = 0; idx < levels.size(); ++idx) { file.seekg(levels[idx]); uint32_t lwidth = read_uint32(); uint32_t lheight = read_uint32(); std::cout << " Level " << idx << ": Width=" << lwidth << ", Height=" << lheight << std::endl; std::vector tptrs; while (true) { uint64_t tptr = read_pointer(); if (tptr == 0) break; tptrs.push_back(tptr); } std::cout << " Tiles: " << tptrs.size() << std::endl; for (size_t i = 0; i < tptrs.size() - 1; ++i) { uint64_t size = tptrs[i + 1] - tptrs[i]; std::cout << " Tile " << i << ": Offset=" << tptrs[i] << ", Size=" << size << std::endl; file.seekg(tptrs[i]); std::vector data(size); file.read(reinterpret_cast(data.data()), size); std::string summary; if (compression == 0) { summary = "Uncompressed data: first 5 bytes "; for (int j = 0; j < 5 && j < data.size(); ++j) summary += std::to_string(data[j]) + " "; } else if (compression == 1) { int tile_size = 64 * 64; int expected = tile_size * bpp; std::vector decomp; size_t start = 0; for (int comp = 0; comp < bpp; ++comp) { std::vector comp_data(data.begin() + start, data.end()); std::vector decomp_comp; decompress_rle(comp_data, tile_size, decomp_comp); decomp.insert(decomp.end(), decomp_comp.begin(), decomp_comp.end()); start += decomp_comp.size(); // Approx } summary = "RLE decompressed: first 5 " ; for (int j = 0; j < 5 && j < decomp.size(); ++j) summary += std::to_string(decomp[j]) + " "; } else if (compression == 2) { std::vector decomp(64*64*bpp); uLongf dest_len = decomp.size(); if (uncompress(decomp.data(), &dest_len, data.data(), size) == Z_OK) { summary = "Zlib decompressed: length " + std::to_string(dest_len) + ", first 5 "; for (int j = 0; j < 5 && j < dest_len; ++j) summary += std::to_string(decomp[j]) + " "; } else { summary = "Zlib decompress failed"; } } else { summary = "Unknown compression"; } std::cout << summary << std::endl; } } } public: void open_and_read(const std::string& filename) { file.open(filename, std::ios::binary); if (!file) { std::cerr << "Cannot open file" << std::endl; return; } std::string magic = read_string(); if (magic != "gimp xcf") { std::cerr << "Not an XCF file" << std::endl; return; } std::string version_str = read_string(); version = std::stoi(version_str.substr(1)); pointer_size = (version >= 11) ? 8 : 4; uint32_t width = read_uint32(); uint32_t height = read_uint32(); uint32_t base_type = read_uint32(); std::string precision = "N/A"; if (version >= 4) { precision = std::to_string(read_uint32()); } std::cout << "Header: Magic=" << magic << ", Version=" << version << ", Width=" << width << ", Height=" << height << ", BaseType=" << base_type << ", Precision=" << precision << std::endl; parse_property_list("Image"); std::vector layer_offsets; while (true) { uint64_t lo = read_pointer(); if (lo == 0) break; layer_offsets.push_back(lo); } for (auto lo : layer_offsets) { file.seekg(lo); uint32_t l_width = read_uint32(); uint32_t l_height = read_uint32(); uint32_t l_type = read_uint32(); std::string l_name = read_string(); std::cout << "Layer: Name=" << l_name << ", Width=" << l_width << ", Height=" << l_height << ", Type=" << l_type << std::endl; parse_property_list("Layer " + l_name); uint64_t hptr = read_pointer(); uint64_t mptr = read_pointer(); if (hptr != 0) parse_hierarchy(hptr); if (mptr != 0) { std::cout << "Mask at " << mptr << std::endl; file.seekg(mptr); uint32_t m_width = read_uint32(); uint32_t m_height = read_uint32(); std::string m_name = read_string(); std::cout << " Mask: Name=" << m_name << ", Width=" << m_width << ", Height=" << m_height << std::endl; parse_property_list("Mask"); uint64_t mhptr = read_pointer(); if (mhptr != 0) parse_hierarchy(mhptr); } } std::vector channel_offsets; while (true) { uint64_t co = read_pointer(); if (co == 0) break; channel_offsets.push_back(co); } for (auto co : channel_offsets) { file.seekg(co); uint32_t c_width = read_uint32(); uint32_t c_height = read_uint32(); std::string c_name = read_string(); std::cout << "Channel: Name=" << c_name << ", Width=" << c_width << ", Height=" << c_height << std::endl; parse_property_list("Channel " + c_name); uint64_t hptr = read_pointer(); if (hptr != 0) parse_hierarchy(hptr); } file.close(); } void write_simple(const std::string& filename) { std::ofstream out(filename, std::ios::binary); if (!out) { std::cerr << "Cannot write file" << std::endl; return; } out.write("gimp xcf ", 9); out.write("v003\0", 5); uint32_t header_vals[3] = {__builtin_bswap32(800), __builtin_bswap32(600), __builtin_bswap32(0)}; out.write(reinterpret_cast(header_vals), 12); uint32_t comp_prop[2] = {__builtin_bswap32(17), __builtin_bswap32(1)}; out.write(reinterpret_cast(comp_prop), 8); out.put(0); // compression none uint32_t end_prop[2] = {__builtin_bswap32(0), __builtin_bswap32(0)}; out.write(reinterpret_cast(end_prop), 8); uint32_t offset_layer = __builtin_bswap32(100); out.write(reinterpret_cast(&offset_layer), 4); uint32_t zero = __builtin_bswap32(0); out.write(reinterpret_cast(&zero), 4); // end layers out.write(reinterpret_cast(&zero), 4); // end channels out.seekp(100); uint32_t layer_header[3] = {__builtin_bswap32(800), __builtin_bswap32(600), __builtin_bswap32(1)}; out.write(reinterpret_cast(layer_header), 12); uint32_t name_len = __builtin_bswap32(6); out.write(reinterpret_cast(&name_len), 4); out.write("Layer\0", 6); out.write(reinterpret_cast(end_prop), 8); // PROP_END std::streampos curr = out.tellp(); uint32_t offset_hier = __builtin_bswap32(static_cast(curr) + 8); out.write(reinterpret_cast(&offset_hier), 4); out.write(reinterpret_cast(&zero), 4); // mask uint32_t hier_header[3] = {__builtin_bswap32(800), __builtin_bswap32(600), __builtin_bswap32(4)}; out.write(reinterpret_cast(hier_header), 12); curr = out.tellp(); uint32_t offset_level = __builtin_bswap32(static_cast(curr) + 4); out.write(reinterpret_cast(&offset_level), 4); out.write(reinterpret_cast(&zero), 4); // end levels uint32_t level_header[2] = {__builtin_bswap32(800), __builtin_bswap32(600)}; out.write(reinterpret_cast(level_header), 8); curr = out.tellp(); uint32_t offset_tile = __builtin_bswap32(static_cast(curr) + 4); out.write(reinterpret_cast(&offset_tile), 4); out.write(reinterpret_cast(&zero), 4); // end tiles std::vector tile_data(64 * 64 * 4, 0); out.write(tile_data.data(), tile_data.size()); std::cout << "Wrote simple XCF file with layer and tile data" << std::endl; } }; int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "Usage: ./script filename.xcf" << std::endl; return 1; } XCFHandlerCpp handler; handler.open_and_read(argv[1]); handler.write_simple("output.xcf"); return 0; } // ===== end task-828 .XCF ===== // ===== task-829 .XDM [C] ===== #include #include #include #include typedef struct { char *filepath; xmlDocPtr doc; // Properties would be stored in a struct or map, but for simplicity, we'll print directly } XDMFile; XDMFile* xdm_new(const char *filepath) { XDMFile *xdm = malloc(sizeof(XDMFile)); xdm->filepath = strdup(filepath); xdm->doc = NULL; return xdm; } int xdm_read(XDMFile *xdm) { xdm->doc = xmlReadFile(xdm->filepath, NULL, 0); if (xdm->doc == NULL) { fprintf(stderr, "Failed to parse %s\n", xdm->filepath); return -1; } return 0; } void xdm_print_properties(XDMFile *xdm) { if (xdm->doc == NULL) return; xmlNode *root = xmlDocGetRootElement(xdm->doc); if (root == NULL) return; printf("Version: %s\n", xmlGetProp(root, (xmlChar*)"version")); printf("Default Data Source Ref: %s\n", xmlGetProp(root, (xmlChar*)"defaultDataSourceRef")); xmlNode *cur = root->children; while (cur != NULL) { if (xmlStrcmp(cur->name, (xmlChar*)"dataProperties") == 0) { printf("Data Properties:\n"); xmlNode *prop = cur->children; while (prop != NULL) { if (xmlStrcmp(prop->name, (xmlChar*)"property") == 0) { printf(" Name: %s, Value: %s\n", xmlGetProp(prop, (xmlChar*)"name"), xmlGetProp(prop, (xmlChar*)"value")); } prop = prop->next; } } else if (xmlStrcmp(cur->name, (xmlChar*)"dataSets") == 0) { printf("Data Sets:\n"); xmlNode *ds = cur->children; while (ds != NULL) { if (xmlStrcmp(ds->name, (xmlChar*)"dataSet") == 0) { printf(" Name: %s, Type: %s\n", xmlGetProp(ds, (xmlChar*)"name"), xmlGetProp(ds, (xmlChar*)"type")); xmlNode *sql = ds->children; while (sql != NULL) { if (xmlStrcmp(sql->name, (xmlChar*)"sql") == 0) { printf(" SQL: %s\n", xmlNodeGetContent(sql)); printf(" Data Source Ref: %s\n", xmlGetProp(sql, (xmlChar*)"dataSourceRef")); } sql = sql->next; } } ds = ds->next; } } else if (xmlStrcmp(cur->name, (xmlChar*)"output") == 0) { printf("Output:\n"); printf(" Root Name: %s, Unique Row Name: %s\n", xmlGetProp(cur, (xmlChar*)"rootName"), xmlGetProp(cur, (xmlChar*)"uniqueRowName")); xmlNode *nodeList = cur->children; while (nodeList != NULL) { if (xmlStrcmp(nodeList->name, (xmlChar*)"nodeList") == 0) { xmlNode *dataStructure = nodeList->children; while (dataStructure != NULL) { if (xmlStrcmp(dataStructure->name, (xmlChar*)"dataStructure") == 0) { printf(" Tag Name: %s\n", xmlGetProp(dataStructure, (xmlChar*)"tagName")); xmlNode *group = dataStructure->children; while (group != NULL) { if (xmlStrcmp(group->name, (xmlChar*)"group") == 0) { printf(" Group Name: %s, Label: %s, Source: %s\n", xmlGetProp(group, (xmlChar*)"name"), xmlGetProp(group, (xmlChar*)"label"), xmlGetProp(group, (xmlChar*)"source")); xmlNode *element = group->children; while (element != NULL) { if (xmlStrcmp(element->name, (xmlChar*)"element") == 0) { printf(" Element Name: %s, Value: %s, Label: %s, DataType: %s, BreakOrder: %s, FieldOrder: %s\n", xmlGetProp(element, (xmlChar*)"name"), xmlGetProp(element, (xmlChar*)"value"), xmlGetProp(element, (xmlChar*)"label"), xmlGetProp(element, (xmlChar*)"dataType"), xmlGetProp(element, (xmlChar*)"breakOrder"), xmlGetProp(element, (xmlChar*)"fieldOrder")); } element = element->next; } } group = group->next; } } dataStructure = dataStructure->next; } } nodeList = nodeList->next; } } else if (xmlStrcmp(cur->name, (xmlChar*)"eventTriggers") == 0) { printf("Event Triggers: Present\n"); } else if (xmlStrcmp(cur->name, (xmlChar*)"lexicals") == 0) { printf("Lexicals: Present\n"); } else if (xmlStrcmp(cur->name, (xmlChar*)"valueSets") == 0) { printf("Value Sets: Present\n"); } else if (xmlStrcmp(cur->name, (xmlChar*)"parameters") == 0) { printf("Parameters: Present\n"); } else if (xmlStrcmp(cur->name, (xmlChar*)"bursting") == 0) { printf("Bursting: Present\n"); } else if (xmlStrcmp(cur->name, (xmlChar*)"display") == 0) { printf("Display:\n"); xmlNode *layouts = cur->children; while (layouts != NULL) { if (xmlStrcmp(layouts->name, (xmlChar*)"layouts") == 0) { xmlNode *layout = layouts->children; while (layout != NULL) { if (xmlStrcmp(layout->name, (xmlChar*)"layout") == 0) { printf(" Layout Name: %s, Left: %s, Top: %s\n", xmlGetProp(layout, (xmlChar*)"name"), xmlGetProp(layout, (xmlChar*)"left"), xmlGetProp(layout, (xmlChar*)"top")); } layout = layout->next; } } else if (xmlStrcmp(layouts->name, (xmlChar*)"groupLinks") == 0) { printf(" Group Links: Present\n"); } layouts = layouts->next; } } cur = cur->next; } } void xdm_write(XDMFile *xdm, const char *new_filepath) { if (xdm->doc == NULL) return; xmlSaveFormatFileEnc(new_filepath, xdm->doc, "UTF-8", 1); } void xdm_free(XDMFile *xdm) { xmlFreeDoc(xdm->doc); free(xdm->filepath); free(xdm); } // Example usage: // int main() { // XDMFile *xdm = xdm_new("example.xdm"); // if (xdm_read(xdm) == 0) { // xdm_print_properties(xdm); // xdm_write(xdm, "new.xdm"); // } // xdm_free(xdm); // return 0; // } // ===== end task-829 .XDM ===== // ===== task-830 .XE [C] ===== #include #include #include #include typedef struct { char *filename; char **properties; int prop_count; int prop_capacity; } XEFile; XEFile* xe_create(const char *filename) { XEFile *xe = malloc(sizeof(XEFile)); xe->filename = strdup(filename); xe->properties = malloc(50 * sizeof(char*)); // Arbitrary xe->prop_count = 0; xe->prop_capacity = 50; return xe; } void xe_read_decode(XEFile *xe) { FILE *f = fopen(xe->filename, "rb"); if (!f) return; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); int offset = 0; // Magic and Version char magic[5] = {0}; memcpy(magic, data + offset, 4); offset += 4; xe->properties[xe->prop_count++] = strdup("Magic: " + *magic); // Simplified uint8_t major = data[offset++]; uint8_t minor = data[offset++]; char ver_str[20]; sprintf(ver_str, "Version: %d.%d", major, minor); xe->properties[xe->prop_count++] = strdup(ver_str); offset += 2; // Reserved // Sectors while (offset < size) { uint16_t sector_type = *(uint16_t*)(data + offset); offset += 4; // Type + reserved uint64_t content_size = *(uint64_t*)(data + offset); offset += 8; char sect_str[50]; sprintf(sect_str, "Sector Type: 0x%x | Content Size: %llu", sector_type, content_size); xe->properties[xe->prop_count++] = strdup(sect_str); if (sector_type == 0x5555) break; if (content_size > 0) { uint8_t padding_size = data[offset]; offset += 4; offset += (content_size - 4 - padding_size); uint32_t crc = *(uint32_t*)(data + offset); char crc_str[20]; sprintf(crc_str, "CRC: 0x%x", crc); xe->properties[xe->prop_count++] = strdup(crc_str); offset += 4 + padding_size; } } // Static properties xe->properties[xe->prop_count++] = strdup("Endianness: Little-Endian"); xe->properties[xe->prop_count++] = strdup("Structure: Sector-based"); xe->properties[xe->prop_count++] = strdup("CRC: Per sector (IEEE 802.3)"); xe->properties[xe->prop_count++] = strdup("Padding: To 32-bit words"); xe->properties[xe->prop_count++] = strdup("Multi-Tile: Yes"); xe->properties[xe->prop_count++] = strdup("System Description: SysConfig/XN sectors"); xe->properties[xe->prop_count++] = strdup("Execution Control: Goto/Call sectors"); xe->properties[xe->prop_count++] = strdup("Skip Sector: Supported (0xFFFF)"); xe->properties[xe->prop_count++] = strdup("Loader: Sequential or parallel"); xe->properties[xe->prop_count++] = strdup("Debug/Sim: ELF-compatible"); free(data); } void xe_print_properties(XEFile *xe) { for (int i = 0; i < xe->prop_count; i++) { printf("%s\n", xe->properties[i]); } } void xe_write(XEFile *xe, const char *new_filename) { FILE *f_in = fopen(xe->filename, "rb"); FILE *f_out = fopen(new_filename, "wb"); char buffer[1024]; size_t bytes; while ((bytes = fread(buffer, 1, sizeof(buffer), f_in)) > 0) { fwrite(buffer, 1, bytes, f_out); } fclose(f_in); fclose(f_out); printf("Written to %s\n", new_filename); } void xe_destroy(XEFile *xe) { for (int i = 0; i < xe->prop_count; i++) free(xe->properties[i]); free(xe->properties); free(xe->filename); free(xe); } // Example usage int main() { XEFile *xe = xe_create("example.xe"); xe_read_decode(xe); xe_print_properties(xe); xe_write(xe, "output.xe"); xe_destroy(xe); return 0; } // ===== end task-830 .XE ===== // ===== task-831 .XEX [C++] ===== #include #include #include #include #include struct Segment { uint16_t start; uint16_t end; std::vector data; }; class XEXFile { private: std::string filepath; uint8_t magic[2]; std::vector segments; uint16_t init_addr; uint16_t run_addr; bool has_init; bool has_run; public: XEXFile(const std::string& fp) : filepath(fp), has_init(false), has_run(false) { std::memset(magic, 0, sizeof(magic)); init_addr = 0; run_addr = 0; } void decode() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { throw std::runtime_error("Cannot open file"); } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); std::vector data(size); if (!file.read(reinterpret_cast(data.data()), size)) { throw std::runtime_error("Error reading file"); } size_t offset = 0; if (data[offset] != 0xFF || data[offset + 1] != 0xFF) { throw std::runtime_error("Invalid magic header"); } magic[0] = 0xFF; magic[1] = 0xFF; offset += 2; while (offset < data.size()) { if (offset + 4 > data.size()) break; uint16_t start = *reinterpret_cast(&data[offset]); uint16_t end = *reinterpret_cast(&data[offset + 2]); size_t length = static_cast(end) - start + 1; offset += 4; if (offset + length > data.size()) { throw std::runtime_error("Invalid segment length"); } std::vector seg_data(data.begin() + offset, data.begin() + offset + length); segments.push_back({start, end, seg_data}); if (start == 0x02E2 && end == 0x02E3 && length == 2) { init_addr = *reinterpret_cast(seg_data.data()); has_init = true; } else if (start == 0x02E0 && end == 0x02E1 && length == 2) { run_addr = *reinterpret_cast(seg_data.data()); has_run = true; } offset += length; } } void printProperties() const { if (magic[0] == 0xFF && magic[1] == 0xFF) { std::cout << "Magic header: 0xFF 0xFF" << std::endl; } for (size_t i = 0; i < segments.size(); ++i) { const auto& seg = segments[i]; std::cout << "Segment " << (i + 1) << ":" << std::endl; std::printf(" Start address: 0x%04X\n", seg.start); std::printf(" End address: 0x%04X\n", seg.end); std::cout << " Data length: " << seg.data.size() << " bytes" << std::endl; } if (has_init) { std::printf("INIT address: 0x%04X\n", init_addr); } if (has_run) { std::printf("RUN address: 0x%04X\n", run_addr); } } void write(const std::string& outputPath) const { std::ofstream file(outputPath, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open output file"); } file.write(reinterpret_cast(magic), 2); for (const auto& seg : segments) { uint16_t start = seg.start; uint16_t end = seg.end; file.write(reinterpret_cast(&start), 2); file.write(reinterpret_cast(&end), 2); file.write(reinterpret_cast(seg.data.data()), seg.data.size()); } } }; // Example usage: // int main() { // try { // XEXFile xex("example.xex"); // xex.decode(); // xex.printProperties(); // xex.write("output.xex"); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-831 .XEX ===== // ===== task-832 .XLR [C++] ===== #include #include #include #include #include #include #include class XLRParser { private: std::string filename; std::vector data; std::map>> listProperties; std::map> dictProperties; public: XLRParser(const std::string& fn = "") { if (!fn.empty()) read(fn); } void read(const std::string& fn) { filename = fn; std::ifstream file(fn, std::ios::binary | std::ios::ate); std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); data.resize(size); file.read(reinterpret_cast(data.data()), size); parse(); } void parse() { int offset = data.size() - 22; int eocdOffset = -1; while (offset > 0) { uint32_t sig; memcpy(&sig, &data[offset], 4); if (sig == 0x06054b50) { eocdOffset = offset; break; } offset--; } if (eocdOffset == -1) return; // Zip64 locator bool isZip64 = false; uint64_t zip64EocdOffset = 0; if (eocdOffset - 20 >= 0) { uint32_t locatorSig; memcpy(&locatorSig, &data[eocdOffset - 20], 4); if (locatorSig == 0x07064b50) { isZip64 = true; std::map locator; memcpy(&locatorSig, &data[eocdOffset - 20], 4); locator["Signature"] = std::to_string(locatorSig); uint32_t numDisk; memcpy(&numDisk, &data[eocdOffset - 16], 4); locator["Number of disk with Zip64 EOCD"] = std::to_string(numDisk); memcpy(&zip64EocdOffset, &data[eocdOffset - 12], 8); locator["Relative offset of Zip64 EOCD"] = std::to_string(zip64EocdOffset); uint32_t totalDisks; memcpy(&totalDisks, &data[eocdOffset - 4], 4); locator["Total number of disks"] = std::to_string(totalDisks); dictProperties["Zip64 End of Central Directory Locator"] = locator; } } // Zip64 EOCD uint64_t cdOffset = 0, cdSize = 0, totalEntries = 0; if (isZip64) { offset = zip64EocdOffset; uint32_t sig; memcpy(&sig, &data[offset], 4); if (sig == 0x06064b50) { std::map zip64Eocd; zip64Eocd["Signature"] = std::to_string(sig); uint64_t recSize; memcpy(&recSize, &data[offset + 4], 8); zip64Eocd["Size of Zip64 EOCD record"] = std::to_string(recSize); uint16_t versionMade; memcpy(&versionMade, &data[offset + 12], 2); zip64Eocd["Version made by"] = std::to_string(versionMade); uint16_t versionNeeded; memcpy(&versionNeeded, &data[offset + 14], 2); zip64Eocd["Version needed"] = std::to_string(versionNeeded); uint32_t thisDisk; memcpy(&thisDisk, &data[offset + 16], 4); zip64Eocd["Number of this disk"] = std::to_string(thisDisk); uint32_t cdDisk; memcpy(&cdDisk, &data[offset + 20], 4); zip64Eocd["Disk with central directory"] = std::to_string(cdDisk); uint64_t entriesDisk; memcpy(&entriesDisk, &data[offset + 24], 8); zip64Eocd["Total entries on this disk"] = std::to_string(entriesDisk); memcpy(&totalEntries, &data[offset + 32], 8); zip64Eocd["Total entries"] = std::to_string(totalEntries); memcpy(&cdSize, &data[offset + 40], 8); zip64Eocd["Size of central directory"] = std::to_string(cdSize); memcpy(&cdOffset, &data[offset + 48], 8); zip64Eocd["Offset of central directory"] = std::to_string(cdOffset); uint64_t extLen = recSize - 44; std::stringstream extSs; for (uint64_t i = 0; i < extLen; i++) { extSs << std::hex << std::setfill('0') << std::setw(2) << (int)data[offset + 56 + i] << " "; } zip64Eocd["Zip64 extensible data sector"] = extSs.str(); dictProperties["Zip64 End of Central Directory Record"] = zip64Eocd; } } // EOCD offset = eocdOffset; std::map eocd; uint32_t sig; memcpy(&sig, &data[offset], 4); eocd["Signature"] = std::to_string(sig); uint16_t shortVal; memcpy(&shortVal, &data[offset + 4], 2); eocd["Number of this disk"] = std::to_string(shortVal); memcpy(&shortVal, &data[offset + 6], 2); eocd["Disk with central directory"] = std::to_string(shortVal); memcpy(&shortVal, &data[offset + 8], 2); eocd["Entries on this disk"] = std::to_string(shortVal); uint16_t eocdTotalEntries; memcpy(&eocdTotalEntries, &data[offset + 10], 2); eocd["Total entries"] = std::to_string(eocdTotalEntries); uint32_t intVal; memcpy(&intVal, &data[offset + 12], 4); eocd["Central directory size"] = std::to_string(intVal); uint32_t eocdCdOffset; memcpy(&eocdCdOffset, &data[offset + 16], 4); eocd["Central directory offset"] = std::to_string(eocdCdOffset); memcpy(&shortVal, &data[offset + 20], 2); eocd["Comment length"] = std::to_string(shortVal); std::string comment((char*)&data[offset + 22], shortVal); eocd["Comment"] = comment; dictProperties["End of Central Directory"] = eocd; if (!isZip64) { totalEntries = eocdTotalEntries; cdOffset = eocdCdOffset; } // Central Directory listProperties["Central Directory Headers"] = {}; offset = cdOffset; std::vector localOffsets; for (uint64_t i = 0; i < totalEntries; i++) { std::map header; // Similar parsing as Python/Java, omitted for brevity due to length // Implement full field copying and extra parsing similar to above listProperties["Central Directory Headers"].push_back(header); } // Add digital signature, local headers, etc., similarly } void printProperties() { // Implement printing similar to Python for (const auto& pair : dictProperties) { std::cout << pair.first << ":" << std::endl; for (const auto& kv : pair.second) { std::cout << " " << kv.first << ": " << kv.second << std::endl; } } for (const auto& pair : listProperties) { std::cout << pair.first << ":" << std::endl; for (const auto& item : pair.second) { for (const auto& kv : item) { std::cout << " " << kv.first << ": " << kv.second << std::endl; } } } } void write(const std::string& fn, const std::map& files) { // Basic write similar to Python read(fn); } }; // Example int main() { XLRParser parser("example.xlr"); parser.printProperties(); return 0; } // ===== end task-832 .XLR ===== // ===== task-833 .XLS [C++] ===== #include #include #include #include #include #include #include class XLSHeaderParser { private: std::string filename; std::map properties; public: XLSHeaderParser(const std::string& fn) : filename(fn) { readHeader(); } void readHeader() { std::ifstream file(filename, std::ios::binary); if (!file) { throw std::runtime_error("Cannot open file"); } std::vector header(512); file.read(reinterpret_cast(header.data()), 512); if (file.gcount() < 512) { throw std::runtime_error("File too small to be a valid .XLS"); } // Signature std::ostringstream sig; for (int i = 0; i < 8; ++i) { sig << "0x" << std::hex << std::setw(2) << std::setfill('0') << (header[i] & 0xFF) << " "; } properties["Signature"] = sig.str().substr(0, sig.str().size() - 1); // CLSID std::ostringstream clsid; for (int i = 8; i < 24; ++i) { clsid << "0x" << std::hex << std::setw(2) << std::setfill('0') << (header[i] & 0xFF) << " "; } properties["CLSID"] = clsid.str().substr(0, clsid.str().size() - 1); // Helper to get little-endian values auto getUint16 = [&header](int offset) { return *reinterpret_cast(&header[offset]); }; auto getUint32 = [&header](int offset) { return *reinterpret_cast(&header[offset]); }; // Minor Version properties["Minor Version"] = "0x" + std::to_string(getUint16(24)); std::ostringstream oss; oss << "0x" << std::hex << std::setw(4) << std::setfill('0') << getUint16(24); properties["Minor Version"] = oss.str(); // Major Version oss.str(""); oss << "0x" << std::hex << std::setw(4) << std::setfill('0') << getUint16(26); properties["Major Version"] = oss.str(); // Byte Order oss.str(""); oss << "0x" << std::hex << std::setw(4) << std::setfill('0') << getUint16(28); properties["Byte Order"] = oss.str(); // Sector Shift properties["Sector Shift"] = std::to_string(getUint16(30)); // Mini Sector Shift properties["Mini Sector Shift"] = std::to_string(getUint16(32)); // Reserved oss.str(""); oss << "0x" << std::hex << std::setw(4) << std::setfill('0') << getUint16(34); properties["Reserved"] = oss.str(); // Reserved1 oss.str(""); oss << "0x" << std::hex << std::setw(8) << std::setfill('0') << getUint32(36); properties["Reserved1"] = oss.str(); // Number of Directory Sectors properties["Number of Directory Sectors"] = std::to_string(getUint32(40)); // Number of FAT Sectors properties["Number of FAT Sectors"] = std::to_string(getUint32(44)); // First Directory Sector Location oss.str(""); oss << "0x" << std::hex << std::setw(8) << std::setfill('0') << getUint32(48); properties["First Directory Sector Location"] = oss.str(); // Transaction Signature Number properties["Transaction Signature Number"] = std::to_string(getUint32(52)); // Mini Stream Cutoff Size properties["Mini Stream Cutoff Size"] = std::to_string(getUint32(56)); // First Mini FAT Sector Location oss.str(""); oss << "0x" << std::hex << std::setw(8) << std::setfill('0') << getUint32(60); properties["First Mini FAT Sector Location"] = oss.str(); // Number of Mini FAT Sectors properties["Number of Mini FAT Sectors"] = std::to_string(getUint32(64)); // First DIFAT Sector Location oss.str(""); oss << "0x" << std::hex << std::setw(8) << std::setfill('0') << getUint32(68); properties["First DIFAT Sector Location"] = oss.str(); // Number of DIFAT Sectors properties["Number of DIFAT Sectors"] = std::to_string(getUint32(72)); // DIFAT std::ostringstream difat; for (int i = 0; i < 109; ++i) { uint32_t val = getUint32(76 + i * 4); difat << "0x" << std::hex << std::setw(8) << std::setfill('0') << val << " "; } properties["DIFAT"] = difat.str().substr(0, difat.str().size() - 1); } void printProperties() const { for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } } void writeHeader(const std::string& newFilename = "") const { std::string outFn = newFilename.empty() ? filename + ".modified" : newFilename; std::ifstream inFile(filename, std::ios::binary); std::ofstream outFile(outFn, std::ios::binary); if (!inFile || !outFile) { throw std::runtime_error("File I/O error"); } std::vector header(512, 0); // Signature auto parseHexBytes = [](const std::string& s, uint8_t* dest) { std::istringstream iss(s); std::string token; int idx = 0; while (iss >> token) { dest[idx++] = static_cast(std::stoul(token.substr(2), nullptr, 16)); } }; parseHexBytes(properties.at("Signature"), header.data()); // CLSID parseHexBytes(properties.at("CLSID"), header.data() + 8); // Minor Version *reinterpret_cast(&header[24]) = static_cast(std::stoul(properties.at("Minor Version").substr(2), nullptr, 16)); // Major Version *reinterpret_cast(&header[26]) = static_cast(std::stoul(properties.at("Major Version").substr(2), nullptr, 16)); // Byte Order *reinterpret_cast(&header[28]) = static_cast(std::stoul(properties.at("Byte Order").substr(2), nullptr, 16)); // Sector Shift *reinterpret_cast(&header[30]) = static_cast(std::stoi(properties.at("Sector Shift"))); // Mini Sector Shift *reinterpret_cast(&header[32]) = static_cast(std::stoi(properties.at("Mini Sector Shift"))); // Reserved *reinterpret_cast(&header[34]) = static_cast(std::stoul(properties.at("Reserved").substr(2), nullptr, 16)); // Reserved1 *reinterpret_cast(&header[36]) = std::stoul(properties.at("Reserved1").substr(2), nullptr, 16); // Number of Directory Sectors *reinterpret_cast(&header[40]) = std::stoul(properties.at("Number of Directory Sectors")); // Number of FAT Sectors *reinterpret_cast(&header[44]) = std::stoul(properties.at("Number of FAT Sectors")); // First Directory Sector Location *reinterpret_cast(&header[48]) = std::stoul(properties.at("First Directory Sector Location").substr(2), nullptr, 16); // Transaction Signature Number *reinterpret_cast(&header[52]) = std::stoul(properties.at("Transaction Signature Number")); // Mini Stream Cutoff Size *reinterpret_cast(&header[56]) = std::stoul(properties.at("Mini Stream Cutoff Size")); // First Mini FAT Sector Location *reinterpret_cast(&header[60]) = std::stoul(properties.at("First Mini FAT Sector Location").substr(2), nullptr, 16); // Number of Mini FAT Sectors *reinterpret_cast(&header[64]) = std::stoul(properties.at("Number of Mini FAT Sectors")); // First DIFAT Sector Location *reinterpret_cast(&header[68]) = std::stoul(properties.at("First DIFAT Sector Location").substr(2), nullptr, 16); // Number of DIFAT Sectors *reinterpret_cast(&header[72]) = std::stoul(properties.at("Number of DIFAT Sectors")); // DIFAT std::istringstream difatIss(properties.at("DIFAT")); std::string token; int idx = 76; while (difatIss >> token) { *reinterpret_cast(&header[idx]) = std::stoul(token.substr(2), nullptr, 16); idx += 4; } outFile.write(reinterpret_cast(header.data()), 512); inFile.seekg(512); char buf[4096]; while (inFile.read(buf, sizeof(buf))) { outFile.write(buf, inFile.gcount()); } outFile.write(buf, inFile.gcount()); // Last chunk std::cout << "Modified file written to " << outFn << std::endl; } }; // Example usage: // int main() { // try { // XLSHeaderParser parser("example.xls"); // parser.printProperties(); // parser.writeHeader(); // } catch (const std::exception& e) { // std::cerr << e.what() << std::endl; // } // return 0; // } // ===== end task-833 .XLS ===== // ===== task-834 .XLSB [C] ===== #include #include #include #define ZIP_LOCAL_HEADER 0x04034b50 typedef struct { char* name; } Property; typedef struct { char* filename; Property* properties; int prop_count; unsigned char* zip_data; size_t zip_size; } XLSBHandler; XLSBHandler* create_xlsb_handler(const char* filename) { XLSBHandler* h = malloc(sizeof(XLSBHandler)); h->filename = strdup(filename); h->properties = NULL; h->prop_count = 0; h->zip_data = NULL; h->zip_size = 0; return h; } void read_and_decode(XLSBHandler* h) { FILE* f = fopen(h->filename, "rb"); if (!f) return; fseek(f, 0, SEEK_END); h->zip_size = ftell(f); fseek(f, 0, SEEK_SET); h->zip_data = malloc(h->zip_size); fread(h->zip_data, 1, h->zip_size, f); fclose(f); // Simple parse for file names size_t offset = 0; while (offset < h->zip_size) { if (*(unsigned int*)(h->zip_data + offset) == ZIP_LOCAL_HEADER) { unsigned short name_len = *(unsigned short*)(h->zip_data + offset + 26); offset += 30; char* name = malloc(name_len + 1); strncpy(name, (char*)(h->zip_data + offset), name_len); name[name_len] = '\0'; h->properties = realloc(h->properties, sizeof(Property) * (h->prop_count + 1)); h->properties[h->prop_count].name = name; h->prop_count++; offset += name_len; unsigned short extra_len = *(unsigned short*)(h->zip_data + offset - 2); offset += extra_len; unsigned int compressed = *(unsigned int*)(h->zip_data + offset - 12); offset += compressed; } else { break; } } print_properties(h); } void print_properties(XLSBHandler* h) { printf("XLSB Properties (internal files):\n"); for (int i = 0; i < h->prop_count; i++) { printf("%s\n", h->properties[i].name); } } void write(XLSBHandler* h, const char* new_filename) { if (!h->zip_data) return; FILE* f = fopen(new_filename, "wb"); if (!f) return; fwrite(h->zip_data, 1, h->zip_size, f); fclose(f); } void destroy_xlsb_handler(XLSBHandler* h) { for (int i = 0; i < h->prop_count; i++) { free(h->properties[i].name); } free(h->properties); free(h->filename); free(h->zip_data); free(h); } // Example usage: // int main() { // XLSBHandler* handler = create_xlsb_handler("sample.xlsb"); // read_and_decode(handler); // write(handler, "copy.xlsb"); // destroy_xlsb_handler(handler); // return 0; // } // ===== end task-834 .XLSB ===== // ===== task-835 .XLSM [C++] ===== #include #include #include // Assume tinyxml2.h for XML parsing class XLSMProperties { private: std::string filename; zip_t* zip; tinyxml2::XMLDocument coreDoc; tinyxml2::XMLDocument appDoc; public: XLSMProperties(const std::string& fn) : filename(fn) { int err = 0; zip = zip_open(filename.c_str(), ZIP_RDONLY, &err); if (!zip) { std::cerr << "Error opening ZIP" << std::endl; } } ~XLSMProperties() { if (zip) zip_close(zip); } void readProperties() { // Read core.xml zip_file_t* coreFile = zip_fopen(zip, "docProps/core.xml", 0); if (coreFile) { // Read buffer, load into tinyxml2 // Assume read into char* buffer, then coreDoc.Parse(buffer); zip_fclose(coreFile); } // Similar for app.xml } void printProperties() { std::cout << "Core Properties:" << std::endl; // Use coreDoc.FirstChildElement("cp:coreProperties")->FirstChildElement("dc:title")->GetText() // With namespaces handled via queries like coreDoc.FirstChildElement("cp:category", "http://...") but tinyxml2 needs manual NS handling // For simplicity: std::cout << "title: " << coreDoc.RootElement()->FirstChildElement("dc:title")->GetText() << std::endl; // Repeat for all std::cout << "Extended Properties:" << std::endl; // Similar } void writeProperties(/* const std::map& newProps */) { // Open new zip, copy files, modify XML buffers, add to new zip std::cout << "New file written." << std::endl; } }; // Example: XLSMProperties props("example.xlsm"); props.readProperties(); props.printProperties(); // ===== end task-835 .XLSM ===== // ===== task-836 .XLSX [C] ===== #include #include #include #include #include #include typedef struct { char *filePath; xmlChar *coreProps[16]; // Array for core props values xmlChar *extProps[17]; // Array for ext props values const char *coreKeys[16]; const char *extKeys[17]; zip_t *zip; } XLSXProperties; void initProps(XLSXProperties *props) { const char *ck[] = {"category", "contentStatus", "contentType", "created", "creator", "description", "identifier", "keywords", "language", "lastModifiedBy", "lastPrinted", "modified", "revision", "subject", "title", "version"}; const char *ek[] = {"Application", "AppVersion", "Company", "DocSecurity", "HyperlinkBase", "HyperlinksChanged", "LinksUpToDate", "Manager", "ScaleCrop", "SharedDoc", "Template", "TotalTime", "Pages", "Words", "Characters", "Lines", "Paragraphs"}; memcpy(props->coreKeys, ck, sizeof(ck)); memcpy(props->extKeys, ek, sizeof(ek)); for (int i = 0; i < 16; i++) props->coreProps[i] = NULL; for (int i = 0; i < 17; i++) props->extProps[i] = NULL; } XLSXProperties *XLSXProperties_new(const char *filePath) { XLSXProperties *props = malloc(sizeof(XLSXProperties)); props->filePath = strdup(filePath); int err = 0; props->zip = zip_open(filePath, 0, &err); if (!props->zip) { fprintf(stderr, "Failed to open ZIP\n"); free(props); return NULL; } initProps(props); // Read core.xml zip_file_t *coreFile = zip_fopen(props->zip, "docProps/core.xml", 0); if (coreFile) { zip_stat_t stat; zip_stat(props->zip, "docProps/core.xml", 0, &stat); char *buf = malloc(stat.size + 1); zip_fread(coreFile, buf, stat.size); buf[stat.size] = '\0'; xmlDocPtr doc = xmlReadMemory(buf, stat.size, NULL, NULL, 0); if (doc) { xmlNode *root = xmlDocGetRootElement(doc); for (int i = 0; i < 16; i++) { xmlNode *node = root->children; while (node) { if (!xmlStrcmp(node->name, (const xmlChar *)props->coreKeys[i])) { props->coreProps[i] = xmlNodeGetContent(node); break; } node = node->next; } } xmlFreeDoc(doc); } free(buf); zip_fclose(coreFile); } // Read app.xml (similar, simplified namespace ignoring for brevity) zip_file_t *appFile = zip_fopen(props->zip, "docProps/app.xml", 0); if (appFile) { zip_stat_t stat; zip_stat(props->zip, "docProps/app.xml", 0, &stat); char *buf = malloc(stat.size + 1); zip_fread(appFile, buf, stat.size); buf[stat.size] = '\0'; xmlDocPtr doc = xmlReadMemory(buf, stat.size, NULL, NULL, 0); if (doc) { xmlNode *root = xmlDocGetRootElement(doc); for (int i = 0; i < 17; i++) { xmlNode *node = root->children; while (node) { if (!xmlStrcmp(node->name, (const xmlChar *)props->extKeys[i])) { props->extProps[i] = xmlNodeGetContent(node); break; } node = node->next; } } // HeadingPairs and TitlesOfParts (dump as content) xmlNode *heading = xmlGetProp(root, (xmlChar *)"HeadingPairs"); // Simplified if (heading) props->extProps[17] = xmlNodeGetContent(heading); // Extra slot if needed xmlFreeDoc(doc); } free(buf); zip_fclose(appFile); } return props; } void XLSXProperties_print(XLSXProperties *props) { printf("Core Properties:\n"); for (int i = 0; i < 16; i++) { if (props->coreProps[i]) printf("%s: %s\n", props->coreKeys[i], props->coreProps[i]); } printf("\nExtended Properties:\n"); for (int i = 0; i < 17; i++) { if (props->extProps[i]) printf("%s: %s\n", props->extKeys[i], props->extProps[i]); } } void XLSXProperties_update(XLSXProperties *props, const char *propType, const char *key, const char *value) { int index = -1; if (strcmp(propType, "core") == 0) { for (int i = 0; i < 16; i++) { if (strcmp(props->coreKeys[i], key) == 0) { index = i; break; } } if (index != -1) { if (props->coreProps[index]) xmlFree(props->coreProps[index]); props->coreProps[index] = xmlStrdup((xmlChar *)value); } } else if (strcmp(propType, "extended") == 0) { for (int i = 0; i < 17; i++) { if (strcmp(props->extKeys[i], key) == 0) { index = i; break; } } if (index != -1) { if (props->extProps[index]) xmlFree(props->extProps[index]); props->extProps[index] = xmlStrdup((xmlChar *)value); } } } void XLSXProperties_write(XLSXProperties *props, const char *outputPath) { zip_t *newZip = zip_open(outputPath, ZIP_CREATE | ZIP_TRUNCATE, NULL); int num = zip_get_num_entries(props->zip, 0); for (int i = 0; i < num; i++) { const char *name = zip_get_name(props->zip, i, 0); if (strcmp(name, "docProps/core.xml") == 0) { // Generate new core.xml xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0"); xmlNodePtr root = xmlNewNode(NULL, BAD_CAST "cp:coreProperties"); xmlDocSetRootElement(doc, root); for (int j = 0; j < 16; j++) { if (props->coreProps[j]) { xmlNewChild(root, NULL, BAD_CAST props->coreKeys[j], props->coreProps[j]); } } xmlChar *xmlbuff; int buffersize; xmlDocDumpFormatMemory(doc, &xmlbuff, &buffersize, 1); zip_source_t *src = zip_source_buffer(newZip, xmlbuff, buffersize, 0); zip_file_add(newZip, name, src, ZIP_FL_OVERWRITE); xmlFreeDoc(doc); } else if (strcmp(name, "docProps/app.xml") == 0) { // Similar for app.xml xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0"); xmlNodePtr root = xmlNewNode(NULL, BAD_CAST "Properties"); xmlDocSetRootElement(doc, root); for (int j = 0; j < 17; j++) { if (props->extProps[j]) { xmlNewChild(root, NULL, BAD_CAST props->extKeys[j], props->extProps[j]); } } xmlChar *xmlbuff; int buffersize; xmlDocDumpFormatMemory(doc, &xmlbuff, &buffersize, 1); zip_source_t *src = zip_source_buffer(newZip, xmlbuff, buffersize, 0); zip_file_add(newZip, name, src, ZIP_FL_OVERWRITE); xmlFreeDoc(doc); } else { zip_source_t *src = zip_source_zip(newZip, props->zip, i, 0, 0, -1); zip_file_add(newZip, name, src, ZIP_FL_OVERWRITE); } } zip_close(newZip); } void XLSXProperties_free(XLSXProperties *props) { for (int i = 0; i < 16; i++) if (props->coreProps[i]) xmlFree(props->coreProps[i]); for (int i = 0; i < 17; i++) if (props->extProps[i]) xmlFree(props->extProps[i]); zip_close(props->zip); free(props->filePath); free(props); } // Example usage: // int main() { // XLSXProperties *props = XLSXProperties_new("example.xlsx"); // XLSXProperties_print(props); // XLSXProperties_update(props, "core", "title", "New Title"); // XLSXProperties_write(props, "modified.xlsx"); // XLSXProperties_free(props); // return 0; // } // ===== end task-836 .XLSX ===== // ===== task-837 .XM [C] ===== #include #include #include #include typedef struct { char id_text[18]; char module_name[21]; uint8_t separator; char tracker_name[21]; uint16_t version_number; uint32_t header_size; uint16_t song_length; uint16_t restart_position; uint16_t num_channels; uint16_t num_patterns; uint16_t num_instruments; uint16_t flags; uint16_t default_tempo; uint16_t default_bpm; uint8_t pattern_order[256]; // Dynamic arrays for patterns and instruments struct Pattern *patterns; struct Instrument *instruments; // Data buffers uint8_t **pattern_data; uint8_t ***sample_data; } XMFile; typedef struct { uint32_t header_length; uint8_t packing_type; uint16_t num_rows; uint16_t data_size; } Pattern; typedef struct { uint32_t size; char name[23]; uint8_t type; uint16_t num_samples; // If num_samples > 0 uint32_t sample_header_size; uint8_t sample_keymap[96]; uint16_t volume_points[24]; // 12 x/y pairs uint16_t panning_points[24]; uint8_t num_volume_points; uint8_t num_panning_points; uint8_t volume_sustain; uint8_t volume_loop_start; uint8_t volume_loop_end; uint8_t panning_sustain; uint8_t panning_loop_start; uint8_t panning_loop_end; uint8_t volume_type; uint8_t panning_type; uint8_t vibrato_type; uint8_t vibrato_sweep; uint8_t vibrato_depth; uint8_t vibrato_rate; uint16_t volume_fadeout; uint16_t reserved; struct Sample *samples; } Instrument; typedef struct { uint32_t length; uint32_t loop_start; uint32_t loop_length; uint8_t volume; int8_t finetune; uint8_t type; uint8_t panning; int8_t relative_note; uint8_t reserved; char name[23]; } Sample; // Helper to read string void read_string(FILE *f, char *dest, size_t len) { fread(dest, 1, len, f); dest[len] = '\0'; // Trim nulls/spaces for (int i = len - 1; i >= 0; i--) { if (dest[i] == 0 || dest[i] == ' ') dest[i] = 0; else break; } } void read(XMFile *xm, const char *filename) { FILE *f = fopen(filename, "rb"); if (!f) return; fseek(f, 0, SEEK_END); long file_size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *buffer = malloc(file_size); fread(buffer, 1, file_size, f); fclose(f); int offset = 0; memcpy(xm->id_text, buffer + offset, 17); xm->id_text[17] = 0; offset += 17; memcpy(xm->module_name, buffer + offset, 20); xm->module_name[20] = 0; offset += 20; xm->separator = buffer[offset++]; memcpy(xm->tracker_name, buffer + offset, 20); xm->tracker_name[20] = 0; offset += 20; xm->version_number = *(uint16_t*)(buffer + offset); offset += 2; xm->header_size = *(uint32_t*)(buffer + offset); uint32_t header_size = xm->header_size; offset += 4; xm->song_length = *(uint16_t*)(buffer + offset); offset += 2; xm->restart_position = *(uint16_t*)(buffer + offset); offset += 2; xm->num_channels = *(uint16_t*)(buffer + offset); offset += 2; xm->num_patterns = *(uint16_t*)(buffer + offset); uint16_t num_patterns = xm->num_patterns; offset += 2; xm->num_instruments = *(uint16_t*)(buffer + offset); uint16_t num_instruments = xm->num_instruments; offset += 2; xm->flags = *(uint16_t*)(buffer + offset); offset += 2; xm->default_tempo = *(uint16_t*)(buffer + offset); offset += 2; xm->default_bpm = *(uint16_t*)(buffer + offset); offset += 2; memcpy(xm->pattern_order, buffer + offset, 256); offset += 256; offset = 60 + header_size - 4; xm->patterns = malloc(num_patterns * sizeof(Pattern)); xm->pattern_data = malloc(num_patterns * sizeof(uint8_t*)); for (int p = 0; p < num_patterns; p++) { xm->patterns[p].header_length = *(uint32_t*)(buffer + offset); uint32_t pat_header_len = xm->patterns[p].header_length; offset += 4; xm->patterns[p].packing_type = buffer[offset++]; xm->patterns[p].num_rows = *(uint16_t*)(buffer + offset); offset += 2; xm->patterns[p].data_size = *(uint16_t*)(buffer + offset); uint16_t pat_data_size = xm->patterns[p].data_size; offset += pat_header_len - 9; xm->pattern_data[p] = malloc(pat_data_size); memcpy(xm->pattern_data[p], buffer + offset, pat_data_size); offset += pat_data_size; } xm->instruments = malloc(num_instruments * sizeof(Instrument)); xm->sample_data = malloc(num_instruments * sizeof(uint8_t**)); for (int i = 0; i < num_instruments; i++) { xm->instruments[i].size = *(uint32_t*)(buffer + offset); uint32_t inst_size = xm->instruments[i].size; offset += 4; memcpy(xm->instruments[i].name, buffer + offset, 22); xm->instruments[i].name[22] = 0; offset += 22; xm->instruments[i].type = buffer[offset++]; xm->instruments[i].num_samples = *(uint16_t*)(buffer + offset); uint16_t num_samples = xm->instruments[i].num_samples; offset += 2; xm->sample_data[i] = malloc(num_samples * sizeof(uint8_t*)); if (num_samples > 0) { xm->instruments[i].sample_header_size = *(uint32_t*)(buffer + offset); offset += 4; memcpy(xm->instruments[i].sample_keymap, buffer + offset, 96); offset += 96; memcpy(xm->instruments[i].volume_points, buffer + offset, 48); offset += 48; memcpy(xm->instruments[i].panning_points, buffer + offset, 48); offset += 48; xm->instruments[i].num_volume_points = buffer[offset++]; xm->instruments[i].num_panning_points = buffer[offset++]; xm->instruments[i].volume_sustain = buffer[offset++]; xm->instruments[i].volume_loop_start = buffer[offset++]; xm->instruments[i].volume_loop_end = buffer[offset++]; xm->instruments[i].panning_sustain = buffer[offset++]; xm->instruments[i].panning_loop_start = buffer[offset++]; xm->instruments[i].panning_loop_end = buffer[offset++]; xm->instruments[i].volume_type = buffer[offset++]; xm->instruments[i].panning_type = buffer[offset++]; xm->instruments[i].vibrato_type = buffer[offset++]; xm->instruments[i].vibrato_sweep = buffer[offset++]; xm->instruments[i].vibrato_depth = buffer[offset++]; xm->instruments[i].vibrato_rate = buffer[offset++]; xm->instruments[i].volume_fadeout = *(uint16_t*)(buffer + offset); offset += 2; xm->instruments[i].reserved = *(uint16_t*)(buffer + offset); offset += 2; offset += inst_size - 263; xm->instruments[i].samples = malloc(num_samples * sizeof(Sample)); for (int s = 0; s < num_samples; s++) { xm->instruments[i].samples[s].length = *(uint32_t*)(buffer + offset); uint32_t sample_len = xm->instruments[i].samples[s].length; offset += 4; xm->instruments[i].samples[s].loop_start = *(uint32_t*)(buffer + offset); offset += 4; xm->instruments[i].samples[s].loop_length = *(uint32_t*)(buffer + offset); offset += 4; xm->instruments[i].samples[s].volume = buffer[offset++]; xm->instruments[i].samples[s].finetune = (int8_t)buffer[offset++]; xm->instruments[i].samples[s].type = buffer[offset++]; uint8_t sample_type = xm->instruments[i].samples[s].type; xm->instruments[i].samples[s].panning = buffer[offset++]; xm->instruments[i].samples[s].relative_note = (int8_t)buffer[offset++]; xm->instruments[i].samples[s].reserved = buffer[offset++]; memcpy(xm->instruments[i].samples[s].name, buffer + offset, 22); xm->instruments[i].samples[s].name[22] = 0; offset += 22; uint32_t byte_len = sample_len * ((sample_type & 0x10) ? 2 : 1); xm->sample_data[i][s] = malloc(byte_len); memcpy(xm->sample_data[i][s], buffer + offset, byte_len); offset += byte_len; } } else { xm->instruments[i].samples = NULL; } } free(buffer); } void print_properties(const XMFile *xm) { printf("ID text: %s\n", xm->id_text); printf("Module name: %s\n", xm->module_name); printf("Separator: %u\n", xm->separator); printf("Tracker name: %s\n", xm->tracker_name); printf("Version number: %u\n", xm->version_number); printf("Header size: %u\n", xm->header_size); printf("Song length: %u\n", xm->song_length); printf("Restart position: %u\n", xm->restart_position); printf("Number of channels: %u\n", xm->num_channels); printf("Number of patterns: %u\n", xm->num_patterns); printf("Number of instruments: %u\n", xm->num_instruments); printf("Flags: %u\n", xm->flags); printf("Default tempo: %u\n", xm->default_tempo); printf("Default BPM: %u\n", xm->default_bpm); printf("Pattern order table: "); for (int i = 0; i < 256; i++) printf("%u ", xm->pattern_order[i]); printf("\n"); for (int p = 0; p < xm->num_patterns; p++) { printf("Pattern %d:\n", p); printf(" Pattern header length: %u\n", xm->patterns[p].header_length); printf(" Packing type: %u\n", xm->patterns[p].packing_type); printf(" Number of rows: %u\n", xm->patterns[p].num_rows); printf(" Packed pattern data size: %u\n", xm->patterns[p].data_size); } for (int i = 0; i < xm->num_instruments; i++) { printf("Instrument %d:\n", i); printf(" Instrument size: %u\n", xm->instruments[i].size); printf(" Instrument name: %s\n", xm->instruments[i].name); printf(" Instrument type: %u\n", xm->instruments[i].type); printf(" Number of samples: %u\n", xm->instruments[i].num_samples); if (xm->instruments[i].num_samples > 0) { printf(" Sample header size: %u\n", xm->instruments[i].sample_header_size); printf(" Sample number for all notes: "); for (int k = 0; k < 96; k++) printf("%u ", xm->instruments[i].sample_keymap[k]); printf("\n"); printf(" Volume envelope points: "); for (int ep = 0; ep < 24; ep++) printf("%u ", xm->instruments[i].volume_points[ep]); printf("\n"); printf(" Panning envelope points: "); for (int ep = 0; ep < 24; ep++) printf("%u ", xm->instruments[i].panning_points[ep]); printf("\n"); printf(" Number of volume points: %u\n", xm->instruments[i].num_volume_points); printf(" Number of panning points: %u\n", xm->instruments[i].num_panning_points); printf(" Volume sustain point: %u\n", xm->instruments[i].volume_sustain); printf(" Volume loop start point: %u\n", xm->instruments[i].volume_loop_start); printf(" Volume loop end point: %u\n", xm->instruments[i].volume_loop_end); printf(" Panning sustain point: %u\n", xm->instruments[i].panning_sustain); printf(" Panning loop start point: %u\n", xm->instruments[i].panning_loop_start); printf(" Panning loop end point: %u\n", xm->instruments[i].panning_loop_end); printf(" Volume type: %u\n", xm->instruments[i].volume_type); printf(" Panning type: %u\n", xm->instruments[i].panning_type); printf(" Vibrato type: %u\n", xm->instruments[i].vibrato_type); printf(" Vibrato sweep: %u\n", xm->instruments[i].vibrato_sweep); printf(" Vibrato depth: %u\n", xm->instruments[i].vibrato_depth); printf(" Vibrato rate: %u\n", xm->instruments[i].vibrato_rate); printf(" Volume fadeout: %u\n", xm->instruments[i].volume_fadeout); printf(" Reserved: %u\n", xm->instruments[i].reserved); for (int s = 0; s < xm->instruments[i].num_samples; s++) { printf(" Sample %d:\n", s); printf(" Sample length: %u\n", xm->instruments[i].samples[s].length); printf(" Sample loop start: %u\n", xm->instruments[i].samples[s].loop_start); printf(" Sample loop length: %u\n", xm->instruments[i].samples[s].loop_length); printf(" Volume: %u\n", xm->instruments[i].samples[s].volume); printf(" Finetune: %d\n", xm->instruments[i].samples[s].finetune); printf(" Sample type: %u\n", xm->instruments[i].samples[s].type); printf(" Panning: %u\n", xm->instruments[i].samples[s].panning); printf(" Relative note number: %d\n", xm->instruments[i].samples[s].relative_note); printf(" Reserved: %u\n", xm->instruments[i].samples[s].reserved); printf(" Sample name: %s\n", xm->instruments[i].samples[s].name); } } } } void write(const XMFile *xm, const char *filename) { FILE *f = fopen(filename, "wb"); if (!f) return; fwrite(xm->id_text, 1, 17, f); fwrite(xm->module_name, 1, 20, f); fwrite(&xm->separator, 1, 1, f); fwrite(xm->tracker_name, 1, 20, f); fwrite(&xm->version_number, 2, 1, f); fwrite(&xm->header_size, 4, 1, f); fwrite(&xm->song_length, 2, 1, f); fwrite(&xm->restart_position, 2, 1, f); fwrite(&xm->num_channels, 2, 1, f); fwrite(&xm->num_patterns, 2, 1, f); fwrite(&xm->num_instruments, 2, 1, f); fwrite(&xm->flags, 2, 1, f); fwrite(&xm->default_tempo, 2, 1, f); fwrite(&xm->default_bpm, 2, 1, f); fwrite(xm->pattern_order, 1, 256, f); for (int p = 0; p < xm->num_patterns; p++) { fwrite(&xm->patterns[p].header_length, 4, 1, f); fwrite(&xm->patterns[p].packing_type, 1, 1, f); fwrite(&xm->patterns[p].num_rows, 2, 1, f); fwrite(&xm->patterns[p].data_size, 2, 1, f); fwrite(xm->pattern_data[p], 1, xm->patterns[p].data_size, f); } for (int i = 0; i < xm->num_instruments; i++) { fwrite(&xm->instruments[i].size, 4, 1, f); fwrite(xm->instruments[i].name, 1, 22, f); fwrite(&xm->instruments[i].type, 1, 1, f); fwrite(&xm->instruments[i].num_samples, 2, 1, f); if (xm->instruments[i].num_samples > 0) { fwrite(&xm->instruments[i].sample_header_size, 4, 1, f); fwrite(xm->instruments[i].sample_keymap, 1, 96, f); fwrite(xm->instruments[i].volume_points, 2, 24, f); fwrite(xm->instruments[i].panning_points, 2, 24, f); fwrite(&xm->instruments[i].num_volume_points, 1, 1, f); fwrite(&xm->instruments[i].num_panning_points, 1, 1, f); fwrite(&xm->instruments[i].volume_sustain, 1, 1, f); fwrite(&xm->instruments[i].volume_loop_start, 1, 1, f); fwrite(&xm->instruments[i].volume_loop_end, 1, 1, f); fwrite(&xm->instruments[i].panning_sustain, 1, 1, f); fwrite(&xm->instruments[i].panning_loop_start, 1, 1, f); fwrite(&xm->instruments[i].panning_loop_end, 1, 1, f); fwrite(&xm->instruments[i].volume_type, 1, 1, f); fwrite(&xm->instruments[i].panning_type, 1, 1, f); fwrite(&xm->instruments[i].vibrato_type, 1, 1, f); fwrite(&xm->instruments[i].vibrato_sweep, 1, 1, f); fwrite(&xm->instruments[i].vibrato_depth, 1, 1, f); fwrite(&xm->instruments[i].vibrato_rate, 1, 1, f); fwrite(&xm->instruments[i].volume_fadeout, 2, 1, f); fwrite(&xm->instruments[i].reserved, 2, 1, f); for (int s = 0; s < xm->instruments[i].num_samples; s++) { fwrite(&xm->instruments[i].samples[s].length, 4, 1, f); fwrite(&xm->instruments[i].samples[s].loop_start, 4, 1, f); fwrite(&xm->instruments[i].samples[s].loop_length, 4, 1, f); fwrite(&xm->instruments[i].samples[s].volume, 1, 1, f); fwrite(&xm->instruments[i].samples[s].finetune, 1, 1, f); fwrite(&xm->instruments[i].samples[s].type, 1, 1, f); fwrite(&xm->instruments[i].samples[s].panning, 1, 1, f); fwrite(&xm->instruments[i].samples[s].relative_note, 1, 1, f); fwrite(&xm->instruments[i].samples[s].reserved, 1, 1, f); fwrite(xm->instruments[i].samples[s].name, 1, 22, f); uint32_t byte_len = xm->instruments[i].samples[s].length * ((xm->instruments[i].samples[s].type & 0x10) ? 2 : 1); fwrite(xm->sample_data[i][s], 1, byte_len, f); } } } fclose(f); } // Free memory function omitted for brevity // ===== end task-837 .XM ===== // ===== task-838 .XMF [C++] ===== #include #include #include #include #include #include struct XMFNode { uint64_t length; uint64_t item_count; uint64_t header_length; uint64_t metadata_length; std::vector metadata_contents; uint64_t ref_type; std::vector contents; std::vector children; }; class XMFParser { private: std::string magic; std::string version; int32_t file_type_id = 0; int32_t file_type_rev = 0; uint64_t file_size; uint64_t mtt_length; std::vector mtt_contents; uint64_t tree_start_offset; XMFNode root_node; uint64_t vlq_to_int(const std::vector& data, size_t& offset) { uint64_t value = 0; while (true) { uint8_t octet = data[offset]; value = (value << 7) + (octet & 0x7F); offset++; if ((octet & 0x80) == 0) break; } return value; } XMFNode parse_node(const std::vector& data, size_t& offset) { size_t node_start = offset; XMFNode node; node.length = vlq_to_int(data, offset); node.item_count = vlq_to_int(data, offset); node.header_length = vlq_to_int(data, offset); node.metadata_length = vlq_to_int(data, offset); node.metadata_contents.assign(data.begin() + offset, data.begin() + offset + node.metadata_length); offset += node.metadata_length; node.ref_type = vlq_to_int(data, offset); if (node.item_count > 0) { node.contents = std::vector{'F', 'o', 'l', 'd', 'e', 'r', ' ', 'n', 'o', 'd', 'e'}; for (uint64_t i = 0; i < node.item_count; i++) { node.children.push_back(parse_node(data, offset)); } } else { if (node.ref_type == 1) { size_t content_size = node.length - (offset - node_start); node.contents.assign(data.begin() + offset, data.begin() + offset + content_size); offset += content_size; } else if (node.ref_type == 2) { uint64_t content_offset = vlq_to_int(data, offset); std::string off_str = "Offset: " + std::to_string(content_offset); node.contents.assign(off_str.begin(), off_str.end()); } } return node; } void print_node(const XMFNode& node, int depth) { std::string indent(depth * 2, ' '); std::cout << indent << "Node Length: " << node.length << std::endl; std::cout << indent << "Item Count: " << node.item_count << std::endl; std::cout << indent << "Header Length: " << node.header_length << std::endl; std::cout << indent << "Metadata Length: " << node.metadata_length << std::endl; std::cout << indent << "Metadata Contents: [Binary, " << node.metadata_length << " bytes]" << std::endl; std::cout << indent << "Reference Type: " << node.ref_type << std::endl; std::string contents_str(node.contents.begin(), node.contents.end()); std::cout << indent << "Contents: " << (node.contents.size() > 20 ? "[Binary, " + std::to_string(node.contents.size()) + " bytes]" : contents_str) << std::endl; for (const auto& child : node.children) { print_node(child, depth + 1); } } std::vector int_to_vlq(uint64_t value) { std::vector bytes_list; while (true) { bytes_list.push_back(value & 0x7F); value >>= 7; if (value == 0) break; } std::reverse(bytes_list.begin(), bytes_list.end()); for (size_t i = 0; i < bytes_list.size() - 1; i++) { bytes_list[i] |= 0x80; } return bytes_list; } std::vector write_node(const XMFNode& node) { std::vector data; auto append = [&data](const std::vector& v) { data.insert(data.end(), v.begin(), v.end()); }; append(int_to_vlq(node.length)); append(int_to_vlq(node.item_count)); append(int_to_vlq(node.header_length)); append(int_to_vlq(node.metadata_length)); append(node.metadata_contents); append(int_to_vlq(node.ref_type)); data.insert(data.end(), node.contents.begin(), node.contents.end()); for (const auto& child : node.children) { append(write_node(child)); } return data; } public: void read(const std::string& filename) { std::ifstream file(filename, std::ios::binary); std::vector data((std::istreambuf_iterator(file)), std::istreambuf_iterator()); size_t offset = 0; magic = std::string(data.begin() + offset, data.begin() + offset + 4); offset += 4; version = std::string(data.begin() + offset, data.begin() + offset + 4); offset += 4; if (version == "2.00") { std::memcpy(&file_type_id, data.data() + offset, 4); file_type_id = __builtin_bswap32(file_type_id); // Assume big-endian offset += 4; std::memcpy(&file_type_rev, data.data() + offset, 4); file_type_rev = __builtin_bswap32(file_type_rev); offset += 4; } file_size = vlq_to_int(data, offset); mtt_length = vlq_to_int(data, offset); mtt_contents.assign(data.begin() + offset, data.begin() + offset + mtt_length); offset += mtt_length; tree_start_offset = vlq_to_int(data, offset); root_node = parse_node(data, offset = tree_start_offset); } void print_properties() { std::cout << "Magic Number: " << magic << std::endl; std::cout << "Version: " << version << std::endl; std::cout << "File Type ID: " << (version == "2.00" ? std::to_string(file_type_id) : "N/A") << std::endl; std::cout << "File Type Revision ID: " << (version == "2.00" ? std::to_string(file_type_rev) : "N/A") << std::endl; std::cout << "File Size: " << file_size << std::endl; std::cout << "MTT Length: " << mtt_length << std::endl; std::cout << "MTT Contents: [Binary, " << mtt_length << " bytes]" << std::endl; std::cout << "Tree Start Offset: " << tree_start_offset << std::endl; std::cout << "Root Node:" << std::endl; print_node(root_node, 0); } void write(const std::string& filename) { std::vector data(magic.begin(), magic.end()); data.insert(data.end(), version.begin(), version.end()); if (version == "2.00") { int32_t be_id = __builtin_bswap32(file_type_id); data.insert(data.end(), reinterpret_cast(&be_id), reinterpret_cast(&be_id) + 4); int32_t be_rev = __builtin_bswap32(file_type_rev); data.insert(data.end(), reinterpret_cast(&be_rev), reinterpret_cast(&be_rev) + 4); } auto append = [&data](const std::vector& v) { data.insert(data.end(), v.begin(), v.end()); }; append(int_to_vlq(file_size)); append(int_to_vlq(mtt_length)); append(mtt_contents); append(int_to_vlq(tree_start_offset)); append(write_node(root_node)); std::ofstream file(filename, std::ios::binary); file.write(reinterpret_cast(data.data()), data.size()); } }; // Example usage: // int main() { // XMFParser parser; // parser.read("example.xmf"); // parser.print_properties(); // parser.write("output.xmf"); // return 0; // } // ===== end task-838 .XMF ===== // ===== task-839 .XML [C++] ===== #include #include #include #include #include "pugixml.hpp" // Assume pugixml.hpp is included; download from https://pugixml.org/ if needed. class XMLHandler { private: std::string filepath; std::string version; std::string encoding; std::string standalone; std::string content; pugi::xml_document doc; public: XMLHandler(const std::string& filepath) : filepath(filepath), version("1.0"), encoding("UTF-8"), standalone("no") { readAndDecode(); } void readAndDecode() { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Error opening file." << std::endl; return; } std::string line; while (std::getline(file, line)) { content += line + "\n"; } file.close(); // Extract using regex for declaration (pugixml doesn't expose declaration directly) std::regex declaration_regex(R"(<\?xml\s+(.*?)\?>)"); std::smatch match; if (std::regex_search(content, match, declaration_regex)) { std::string attrs = match[1].str(); std::regex version_regex(R"(version\s*=\s*["'](.*?)["'])"); std::smatch vmatch; if (std::regex_search(attrs, vmatch, version_regex)) version = vmatch[1].str(); std::regex encoding_regex(R"(encoding\s*=\s*["'](.*?)["'])"); std::smatch ematch; if (std::regex_search(attrs, ematch, encoding_regex)) encoding = ematch[1].str(); std::regex standalone_regex(R"(standalone\s*=\s*["'](.*?)["'])"); std::smatch smatch; if (std::regex_search(attrs, smatch, standalone_regex)) standalone = smatch[1].str(); } // Full parsing with pugixml pugi::xml_parse_result result = doc.load_string(content.c_str()); if (!result) { std::cerr << "Error parsing XML: " << result.description() << std::endl; } } void printElement(const pugi::xml_node& node, int indent = 0) { std::string prefix(indent * 2, ' '); std::cout << prefix << "Element: " << node.name() << std::endl; for (pugi::xml_attribute attr = node.first_attribute(); attr; attr = attr.next_attribute()) { std::cout << prefix << " Attribute: " << attr.name() << " = " << attr.value() << std::endl; } if (!std::string(node.text().get()).empty()) { std::cout << prefix << " Text: " << node.text().get() << std::endl; } for (pugi::xml_node child = node.first_child(); child; child = child.next_sibling()) { if (child.type() == pugi::node_element) { printElement(child, indent + 1); } } } void printProperties() { std::cout << "XML Properties:" << std::endl; std::cout << "- XML Version: " << version << std::endl; std::cout << "- Character Encoding: " << encoding << std::endl; std::cout << "- Standalone Status: " << standalone << std::endl; std::cout << "\nFull XML Structure:" << std::endl; pugi::xml_node root = doc.root(); if (root) { printElement(root); } else { std::cout << "No root element found." << std::endl; } } void writeFile(const std::string& outputFilepath, const std::string& newVersion = "", const std::string& newEncoding = "", const std::string& newStandalone = "") { if (!newVersion.empty()) version = newVersion; if (!newEncoding.empty()) encoding = newEncoding; if (!newStandalone.empty()) standalone = newStandalone; std::string newDeclaration = "\n"; // Replace old declaration std::regex oldDecl_regex(R"(^<\?xml\s+.*?\?\>\s*)"); std::string newContent = std::regex_replace(content, oldDecl_regex, newDeclaration); // To preserve full structure, save using pugixml doc.save_file(outputFilepath.c_str(), " ", pugi::format_indent, pugi::encoding_utf8); } }; // Example usage: // int main() { // XMLHandler handler("example.xml"); // handler.printProperties(); // handler.writeFile("output.xml", "", "", "yes"); // return 0; // } // ===== end task-839 .XML ===== // ===== task-840 .XP [C++] ===== #include #include #include #include #include // For memcpy struct Cell { int32_t charCode; uint8_t fg[3]; uint8_t bg[3]; }; struct Layer { int32_t width; int32_t height; std::vector cells; }; class XPFile { public: int32_t version; int32_t numLayers; std::vector layers; XPFile(const std::string& filepath = "") { if (!filepath.empty()) { read(filepath); } } void read(const std::string& filepath) { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { throw std::runtime_error("Failed to open file"); } size_t size = file.tellg(); file.seekg(0); std::vector compressed(size); file.read(reinterpret_cast(compressed.data()), size); uLongf decompressedSize = size * 10; // Estimate std::vector data(decompressedSize); while (uncompress(data.data(), &decompressedSize, compressed.data(), size) == Z_BUF_ERROR) { decompressedSize *= 2; data.resize(decompressedSize); } const uint8_t* ptr = data.data(); memcpy(&version, ptr, 4); ptr += 4; memcpy(&numLayers, ptr, 4); ptr += 4; layers.clear(); for (int i = 0; i < numLayers; ++i) { Layer layer; memcpy(&layer.width, ptr, 4); ptr += 4; memcpy(&layer.height, ptr, 4); ptr += 4; layer.cells.resize(layer.width * layer.height); for (auto& cell : layer.cells) { memcpy(&cell.charCode, ptr, 4); ptr += 4; memcpy(cell.fg, ptr, 3); ptr += 3; memcpy(cell.bg, ptr, 3); ptr += 3; } layers.push_back(layer); } } void printProperties() const { std::cout << "Format Version: " << version << std::endl; std::cout << "Number of Layers: " << numLayers << std::endl; for (size_t i = 0; i < layers.size(); ++i) { const auto& layer = layers[i]; std::cout << "\nLayer " << (i + 1) << ":" << std::endl; std::cout << " Width: " << layer.width << std::endl; std::cout << " Height: " << layer.height << std::endl; for (size_t j = 0; j < layer.cells.size(); ++j) { const auto& cell = layer.cells[j]; int x = j / layer.height; int y = j % layer.height; std::cout << " Cell (" << x << ", " << y << "): Char=" << static_cast(cell.charCode) << " (code=" << cell.charCode << "), FG=(" << static_cast(cell.fg[0]) << "," << static_cast(cell.fg[1]) << "," << static_cast(cell.fg[2]) << "), BG=(" << static_cast(cell.bg[0]) << "," << static_cast(cell.bg[1]) << "," << static_cast(cell.bg[2]) << ")" << std::endl; } } } void write(const std::string& filepath) const { size_t size = 8; // version + numLayers for (const auto& layer : layers) { size += 8; // width + height size += layer.cells.size() * (4 + 3 + 3); } std::vector data(size); uint8_t* ptr = data.data(); memcpy(ptr, &version, 4); ptr += 4; memcpy(ptr, &numLayers, 4); ptr += 4; for (const auto& layer : layers) { memcpy(ptr, &layer.width, 4); ptr += 4; memcpy(ptr, &layer.height, 4); ptr += 4; for (const auto& cell : layer.cells) { memcpy(ptr, &cell.charCode, 4); ptr += 4; memcpy(ptr, cell.fg, 3); ptr += 3; memcpy(ptr, cell.bg, 3); ptr += 3; } } uLongf compressedSize = compressBound(size); std::vector compressed(compressedSize); compress(compressed.data(), &compressedSize, data.data(), size); std::ofstream file(filepath, std::ios::binary); file.write(reinterpret_cast(compressed.data()), compressedSize); } }; // ===== end task-840 .XP ===== // ===== task-841 .XPL [C++] ===== #include #include #include #include class XPLHandler { private: tinyxml2::XMLDocument doc; const char* ns = "http://www.w3.org/ns/xproc"; // Not directly used in TinyXML2, but for reference public: XPLHandler(const std::string& filepath) { doc.LoadFile(filepath.c_str()); } void printProperties() { tinyxml2::XMLElement* root = doc.RootElement(); if (!root) { std::cerr << "Error: Invalid XML." << std::endl; return; } std::cout << "namespace: " << (root->Namespace() ? root->Namespace() : "Not found") << std::endl; std::cout << "version: " << (root->Attribute("version") ? root->Attribute("version") : "Not specified") << std::endl; std::cout << "root_element: " << root->Name() << std::endl; std::vector inputs; for (tinyxml2::XMLElement* el = root->FirstChildElement("input"); el; el = el->NextSiblingElement("input")) { inputs.push_back(el->Attribute("port") ? el->Attribute("port") : ""); } std::cout << "inputs: "; for (const auto& val : inputs) std::cout << val << " "; std::cout << std::endl; std::vector outputs; for (tinyxml2::XMLElement* el = root->FirstChildElement("output"); el; el = el->NextSiblingElement("output")) { outputs.push_back(el->Attribute("port") ? el->Attribute("port") : ""); } std::cout << "outputs: "; for (const auto& val : outputs) std::cout << val << " "; std::cout << std::endl; // Similar for options, variables, etc. } void writeExample(const std::string& outputPath) { tinyxml2::XMLDocument newDoc; tinyxml2::XMLElement* root = newDoc.NewElement("p:pipeline"); root->SetAttribute("xmlns:p", ns); root->SetAttribute("version", "1.0"); newDoc.InsertFirstChild(root); tinyxml2::XMLElement* input = newDoc.NewElement("p:input"); input->SetAttribute("port", "source"); root->InsertEndChild(input); tinyxml2::XMLElement* output = newDoc.NewElement("p:output"); output->SetAttribute("port", "result"); root->InsertEndChild(output); newDoc.SaveFile(outputPath.c_str()); } }; // Example usage: // int main() { // XPLHandler handler("example.xpl"); // handler.printProperties(); // handler.writeExample("new_example.xpl"); // return 0; // } // ===== end task-841 .XPL ===== // ===== task-842 .XPS [C++] ===== #include #include #include #include #include class XPSParser { private: std::string filename; std::map properties; void readProperties() { zip_t* zip = zip_open(filename.c_str(), ZIP_RDONLY, nullptr); if (!zip) { throw std::runtime_error("Failed to open XPS file."); } zip_stat_t stat; if (zip_stat(zip, "docProps/core.xml", 0, &stat) != 0) { zip_close(zip); throw std::runtime_error("Core properties file not found."); } char* buffer = new char[stat.size]; zip_file_t* file = zip_fopen(zip, "docProps/core.xml", 0); zip_fread(file, buffer, stat.size); zip_fclose(file); zip_close(zip); tinyxml2::XMLDocument doc; doc.Parse(buffer, stat.size); delete[] buffer; auto getText = [&doc](const char* tag) -> std::string { auto elem = doc.FirstChildElement("cp:coreProperties")->FirstChildElement(tag); return elem ? elem->GetText() : "N/A"; }; properties["Title"] = getText("dc:title"); properties["Creator"] = getText("dc:creator"); properties["Description"] = getText("dc:description"); properties["Subject"] = getText("dc:subject"); properties["Identifier"] = getText("dc:identifier"); properties["Keywords"] = getText("cp:keywords"); properties["Language"] = getText("dc:language"); properties["Created"] = getText("dcterms:created"); properties["Modified"] = getText("dcterms:modified"); properties["Last Modified By"] = getText("cp:lastModifiedBy"); properties["Revision"] = getText("cp:revision"); properties["Version"] = getText("cp:version"); properties["Category"] = getText("cp:category"); properties["Content Status"] = getText("cp:contentStatus"); properties["Content Type"] = getText("cp:contentType"); properties["Last Printed"] = getText("cp:lastPrinted"); } public: XPSParser(const std::string& fn) : filename(fn) { readProperties(); } void printProperties() const { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void setProperty(const std::string& key, const std::string& value) { if (properties.find(key) != properties.end()) { properties[key] = value; } else { throw std::invalid_argument("Invalid property: " + key); } } void write(const std::string& outputFilename) { zip_t* sourceZip = zip_open(filename.c_str(), ZIP_RDONLY, nullptr); if (!sourceZip) { throw std::runtime_error("Failed to open source XPS file."); } zip_t* newZip = zip_open(outputFilename.c_str(), ZIP_CREATE | ZIP_TRUNCATE, nullptr); if (!newZip) { zip_close(sourceZip); throw std::runtime_error("Failed to create new XPS file."); } int numEntries = zip_get_num_entries(sourceZip, 0); for (int i = 0; i < numEntries; ++i) { const char* name = zip_get_name(sourceZip, i, 0); zip_stat_t stat; zip_stat_index(sourceZip, i, 0, &stat); char* buffer = new char[stat.size]; zip_file_t* file = zip_fopen_index(sourceZip, i, 0); zip_fread(file, buffer, stat.size); zip_fclose(file); if (std::string(name) == "docProps/core.xml") { tinyxml2::XMLDocument doc; tinyxml2::XMLElement* root = doc.NewElement("cp:coreProperties"); root->SetAttribute("xmlns:cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); root->SetAttribute("xmlns:dc", "http://purl.org/dc/elements/1.1/"); root->SetAttribute("xmlns:dcterms", "http://purl.org/dc/terms/"); root->SetAttribute("xmlns:dcmitype", "http://purl.org/dc/dcmitype/"); root->SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); doc.InsertFirstChild(root); auto addElem = [&doc, root](const char* tag, const std::string& value) { tinyxml2::XMLElement* elem = doc.NewElement(tag); elem->SetText(value.c_str()); root->InsertEndChild(elem); }; addElem("dc:title", properties["Title"]); addElem("dc:creator", properties["Creator"]); addElem("dc:description", properties["Description"]); addElem("dc:subject", properties["Subject"]); addElem("dc:identifier", properties["Identifier"]); addElem("cp:keywords", properties["Keywords"]); addElem("dc:language", properties["Language"]); tinyxml2::XMLElement* created = doc.NewElement("dcterms:created"); created->SetAttribute("xsi:type", "dcterms:W3CDTF"); created->SetText(properties["Created"].c_str()); root->InsertEndChild(created); tinyxml2::XMLElement* modified = doc.NewElement("dcterms:modified"); modified->SetAttribute("xsi:type", "dcterms:W3CDTF"); modified->SetText(properties["Modified"].c_str()); root->InsertEndChild(modified); addElem("cp:lastModifiedBy", properties["Last Modified By"]); addElem("cp:revision", properties["Revision"]); addElem("cp:version", properties["Version"]); addElem("cp:category", properties["Category"]); addElem("cp:contentStatus", properties["Content Status"]); addElem("cp:contentType", properties["Content Type"]); addElem("cp:lastPrinted", properties["Last Printed"]); tinyxml2::XMLPrinter printer; doc.Accept(&printer); std::string xmlStr = "\n" + printer.CStr(); delete[] buffer; buffer = new char[xmlStr.size()]; memcpy(buffer, xmlStr.c_str(), xmlStr.size()); stat.size = xmlStr.size(); } zip_source_t* source = zip_source_buffer(newZip, buffer, stat.size, 1); zip_file_add(newZip, name, source, ZIP_FL_OVERWRITE | ZIP_FL_ENC_UTF_8); } zip_close(newZip); zip_close(sourceZip); } }; // ===== end task-842 .XPS ===== // ===== task-843 .XSD [C++] ===== #include #include // Assume TinyXML-2 library is available #include #include #include class XSDHandler { private: tinyxml2::XMLDocument doc; std::string filePath; std::string encoding = "UTF-8"; // Default public: void open(const std::string& filePath) { this->filePath = filePath; std::ifstream file(filePath); std::string raw((std::istreambuf_iterator(file)), std::istreambuf_iterator()); std::regex encodingRegex(R"(encoding="([^"]+)")"); std::smatch match; if (std::regex_search(raw, match, encodingRegex) && match.size() > 1) { encoding = match[1].str(); } if (doc.Parse(raw.c_str()) != tinyxml2::XML_SUCCESS) { throw std::runtime_error("Failed to parse XML"); } tinyxml2::XMLElement* root = doc.FirstChildElement("schema"); if (!root || std::string(root->GetDocument()->RootElement()->Namespace()) != "http://www.w3.org/2001/XMLSchema") { throw std::invalid_argument("Invalid .XSD root element"); } } void printProperties() { tinyxml2::XMLElement* root = doc.FirstChildElement("schema"); if (!root) { throw std::runtime_error("No file opened"); } std::cout << "General Properties:" << std::endl; size_t dotPos = filePath.find_last_of('.'); std::cout << "File extension: " << (dotPos != std::string::npos ? filePath.substr(dotPos) : "") << std::endl; std::cout << "MIME type: application/xml" << std::endl; std::cout << "Encoding: " << encoding << std::endl; std::cout << "File type: Text-based, human-readable XML" << std::endl; std::cout << "Root element: with namespace http://www.w3.org/2001/XMLSchema" << std::endl; std::cout << "\nStructural Properties (Root Attributes):" << std::endl; const tinyxml2::XMLAttribute* attr = root->FirstAttribute(); while (attr) { std::cout << attr->Name() << ": " << attr->Value() << std::endl; attr = attr->Next(); } } void write(const std::string& filePath) { std::ofstream outFile(filePath); outFile << "" << std::endl; tinyxml2::XMLPrinter printer; doc.Print(&printer); outFile << printer.CStr(); if (!outFile) { throw std::runtime_error("Failed to write file"); } } }; // Example usage: // int main() { // try { // XSDHandler handler; // handler.open("example.xsd"); // handler.printProperties(); // handler.write("output.xsd"); // } catch (const std::exception& e) { // std::cerr << "Error: " << e.what() << std::endl; // } // return 0; // } // ===== end task-843 .XSD ===== // ===== task-844 .XSF [C++] ===== #include #include #include #include #include class XSFHandler { private: std::map properties; // Use std::any for mixed types (C++17) public: XSFHandler() { properties["structureType"] = std::string("Unknown"); properties["primVec"] = std::vector(); properties["convVec"] = std::vector(); properties["primCoord"] = std::vector(); properties["convCoord"] = std::vector(); properties["atoms"] = std::vector(); properties["animSteps"] = 0; properties["forces"] = std::vector(); properties["datagrids"] = std::vector>(); properties["bandgrids"] = std::vector>(); properties["fermiEnergy"] = 0.0f; // or nullptr for optional } void read(const std::string& filename) { std::ifstream file(filename); std::string line; std::vector lines; while (std::getline(file, line)) { line.erase(0, line.find_first_not_of(" \t")); line.erase(line.find_last_not_of(" \t") + 1); if (!line.empty() && line[0] != '#') { lines.push_back(line); } } // Parsing logic similar to Python, using loop over lines // Implement conditions for keywords } void printProperties() { std::cout << "XSF Properties:" << std::endl; // Use std::any_cast to print each // For example: std::cout << "structureType: " << std::any_cast(properties["structureType"]) << std::endl; // Extend for others } void write(const std::string& filename) { std::ofstream file(filename); std::string type = std::any_cast(properties["structureType"]); if (type != "Unknown") { file << type << std::endl; } // Similar for other properties } }; // Usage: // XSFHandler handler; // handler.read("example.xsf"); // handler.printProperties(); // handler.write("output.xsf"); // ===== end task-844 .XSF ===== // ===== task-845 .XSL [C++] ===== #include #include #include #include #include "tinyxml2.h" // Assume tinyxml2.h is included using namespace tinyxml2; using namespace std; class XSLHandler { private: string filePath; XMLDocument doc; const char* ns = "http://www.w3.org/1999/XSL/Transform"; public: XSLHandler(const string& filePath) : filePath(filePath) { doc.LoadFile(filePath.c_str()); } map>> getProperties() { map>> props; XMLElement* root = doc.RootElement(); props["Document Type"] = "Well-formed XML"s; props["Root Element"] = root->Name(); props["Namespace URI"] = root->GetDocument()->GetErrorID() == 0 ? ns : "Not declared"s; props["Version Attribute"] = root->Attribute("version") ? root->Attribute("version") : "Not specified"s; props["Media Type"] = "application/xslt+xml (inferred)"s; vector imports; for (XMLElement* el = root->FirstChildElement("import"); el; el = el->NextSiblingElement("import")) { imports.push_back(el->Attribute("href") ? el->Attribute("href") : "None"); } props["Imported Stylesheets"] = imports; vector includes; for (XMLElement* el = root->FirstChildElement("include"); el; el = el->NextSiblingElement("include")) { includes.push_back(el->Attribute("href") ? el->Attribute("href") : "None"); } props["Included Stylesheets"] = includes; vector variables; for (XMLElement* el = root->FirstChildElement("variable"); el; el = el->NextSiblingElement("variable")) { variables.push_back(el->Attribute("name") ? el->Attribute("name") : "Unnamed"); } props["Global Variables"] = variables; vector params; for (XMLElement* el = root->FirstChildElement("param"); el; el = el->NextSiblingElement("param")) { params.push_back(el->Attribute("name") ? el->Attribute("name") : "Unnamed"); } props["Global Parameters"] = params; vector templates; for (XMLElement* el = root->FirstChildElement("template"); el; el = el->NextSiblingElement("template")) { const char* match = el->Attribute("match"); const char* name = el->Attribute("name"); templates.push_back(match ? match : (name ? name : "Unnamed")); } props["Templates"] = templates; XMLElement* output = root->FirstChildElement("output"); props["Output Method"] = output && output->Attribute("method") ? output->Attribute("method") : "Not specified"s; return props; } void printProperties() { auto props = getProperties(); for (const auto& [key, val] : props) { if (holds_alternative>(val)) { const auto& list = get>(val); cout << key << ": "; for (size_t i = 0; i < list.size(); ++i) { cout << list[i] << (i < list.size() - 1 ? ", " : ""); } cout << endl; } else { cout << key << ": " << get(val) << endl; } } } void write(const string& outputPath = "", bool modifyExample = false) { string path = outputPath.empty() ? filePath : outputPath; if (modifyExample) { // Example modification: Add a comment XMLComment* comment = doc.NewComment("Modified by XSLHandler"); doc.RootElement()->InsertFirstChild(comment); } doc.SaveFile(path.c_str()); } }; // Example usage: // int main() { // XSLHandler handler("example.xsl"); // handler.printProperties(); // handler.write("modified.xsl", true); // return 0; // } // ===== end task-845 .XSL ===== // ===== task-846 .XSLT [C++] ===== #include #include #include #include #include #include "tinyxml2.h" // Assume tinyxml2.h is included class XsltHandler { private: std::string filepath; tinyxml2::XMLDocument doc; tinyxml2::XMLElement* root; std::map properties; public: XsltHandler(const std::string& filepath) : filepath(filepath), root(nullptr) {} void readAndDecode() { if (doc.LoadFile(filepath.c_str()) != tinyxml2::XML_SUCCESS) { throw std::runtime_error("Failed to load XML file."); } root = doc.FirstChildElement(); if (!root) { throw std::runtime_error("No root element found."); } properties["File Extension"] = ".xslt"; properties["MIME Type"] = "application/xslt+xml"; properties["Encoding"] = doc.Encoding() ? doc.Encoding() : "UTF-8"; properties["XML Version"] = doc.Version() ? doc.Version() : "1.0"; properties["Root Element"] = root->Name() ? root->Name() : "N/A"; properties["Required Namespace"] = root->GetDocument()->RootElement()->Namespace() ? root->GetDocument()->RootElement()->Namespace() : "N/A"; // Simplified; adjust if needed properties["Version Attribute"] = root->Attribute("version") ? root->Attribute("version") : "N/A"; properties["Default Mode"] = root->Attribute("default-mode") ? root->Attribute("default-mode") : "N/A"; properties["Default Collation"] = root->Attribute("default-collation") ? root->Attribute("default-collation") : "N/A"; properties["Default Validation"] = root->Attribute("default-validation") ? root->Attribute("default-validation") : "N/A"; properties["Default Action"] = root->Attribute("default-action") ? root->Attribute("default-action") : "N/A"; properties["Expand Text"] = root->Attribute("expand-text") ? root->Attribute("expand-text") : "N/A"; properties["XPath Default Namespace"] = root->Attribute("xpath-default-namespace") ? root->Attribute("xpath-default-namespace") : "N/A"; properties["Extension Element Prefixes"] = root->Attribute("extension-element-prefixes") ? root->Attribute("extension-element-prefixes") : "N/A"; properties["Exclude Result Prefixes"] = root->Attribute("exclude-result-prefixes") ? root->Attribute("exclude-result-prefixes") : "N/A"; properties["Use When"] = root->Attribute("use-when") ? root->Attribute("use-when") : "N/A"; properties["Input Type Annotations"] = root->Attribute("input-type-annotations") ? root->Attribute("input-type-annotations") : "N/A"; properties["ID Attribute"] = root->Attribute("id") ? root->Attribute("id") : "N/A"; properties["Static Attributes"] = root->Attribute("static") ? root->Attribute("static") : "N/A"; properties["Visibility Attributes"] = root->Attribute("visibility") ? root->Attribute("visibility") : "N/A"; std::stringstream nsStream; for (const tinyxml2::XMLAttribute* attr = root->FirstAttribute(); attr; attr = attr->Next()) { std::string name = attr->Name(); if (name.find("xmlns") == 0) { if (!nsStream.str().empty()) nsStream << ", "; nsStream << name << ": " << attr->Value(); } } properties["Namespaces"] = nsStream.str().empty() ? "N/A" : nsStream.str(); std::stringstream declStream; for (tinyxml2::XMLElement* child = root->FirstChildElement(); child; child = child->NextSiblingElement()) { if (!declStream.str().empty()) declStream << "; "; declStream << child->Name() << " (name: " << (child->Attribute("name") ? child->Attribute("name") : "N/A") << ", match: " << (child->Attribute("match") ? child->Attribute("match") : "N/A") << ")"; } properties["Top-Level Declarations"] = declStream.str().empty() ? "N/A" : declStream.str(); std::stringstream packageStream; packageStream << "Name: " << (root->Attribute("name") ? root->Attribute("name") : "N/A") << ", Version: " << (root->Attribute("package-version") ? root->Attribute("package-version") : "N/A"); properties["Package-Specific Properties"] = packageStream.str(); } void printProperties() const { for (const auto& pair : properties) { std::cout << pair.first << ": " << pair.second << std::endl; } } void write(const std::string& newFilepath = "") const { if (!root) { throw std::runtime_error("File not read yet."); } std::string target = newFilepath.empty() ? filepath : newFilepath; doc.SaveFile(target.c_str()); } }; // Example usage: // int main() { // try { // XsltHandler handler("example.xslt"); // handler.readAndDecode(); // handler.printProperties(); // handler.write("output.xslt"); // } catch (const std::exception& e) { // std::cerr << "Error: " << e.what() << std::endl; // } // return 0; // } // ===== end task-846 .XSLT ===== // ===== task-847 .XSN [C] ===== #include #include #include // Assume mspack.h for CAB (libmspack) #include // Assume simple XML parser header; for brevity, use custom parsing functions. struct XSNHandler { char* filepath; char* manifest_content; // Raw XML string }; struct XSNHandler* createXSNHandler(const char* filepath) { struct XSNHandler* handler = malloc(sizeof(struct XSNHandler)); handler->filepath = strdup(filepath); handler->manifest_content = NULL; load(handler); return handler; } void load(struct XSNHandler* handler) { // Use libmspack to extract manifest.xsf struct mscab_decompressor* cabd = mscab_decompressor_create(); struct mscabd_cabinet* cab = cabd->open(cabd, handler->filepath); struct mscabd_file* file = cab->files; while (file) { if (strcmp(file->filename, "manifest.xsf") == 0) { handler->manifest_content = malloc(file->length + 1); cabd->extract(cabd, file, "temp_manifest.xsf"); // Extract to temp FILE* f = fopen("temp_manifest.xsf", "r"); fread(handler->manifest_content, 1, file->length, f); handler->manifest_content[file->length] = '\0'; fclose(f); remove("temp_manifest.xsf"); break; } file = file->next; } cabd->close(cabd, cab); mscab_decompressor_destroy(cabd); } void printProperties(struct XSNHandler* handler) { if (!handler->manifest_content) return; // Custom XML parsing: Search for attributes (simplified string search for demo) printf("Properties:\n"); char* name = strstr(handler->manifest_content, "name=\""); if (name) printf("- Form Name: %s\n", /* parse value */); // Extend for other properties with string parsing or full XML lib... } void writeProperties(struct XSNHandler* handler, /* updates */) { // Update content, repack CAB using libmspack compress } void destroyXSNHandler(struct XSNHandler* handler) { free(handler->filepath); free(handler->manifest_content); free(handler); } // Usage example: // struct XSNHandler* handler = createXSNHandler("example.xsn"); // printProperties(handler); // destroyXSNHandler(handler); // ===== end task-847 .XSN ===== // ===== task-848 .XSPF [C] ===== #include #include #include #include #include #define NAMESPACE "http://xspf.org/ns/0/" typedef struct { xmlDocPtr doc; } XSPFHandler; void xspf_init(XSPFHandler *handler) { handler->doc = NULL; } int xspf_load(XSPFHandler *handler, const char *file_path) { handler->doc = xmlReadFile(file_path, NULL, 0); if (handler->doc == NULL) { fprintf(stderr, "Failed to parse %s\n", file_path); return -1; } xmlNodePtr root = xmlDocGetRootElement(handler->doc); if (root == NULL || xmlStrcmp(root->name, (const xmlChar *)"playlist") != 0) { fprintf(stderr, "Not a valid XSPF file\n"); xmlFreeDoc(handler->doc); handler->doc = NULL; return -1; } return 0; } void print_node_properties(xmlNodePtr node, int is_track) { const char *simple_elements[] = {"title", "creator", "annotation", "info", "location", "identifier", "image", "date", "license", "album", "trackNum", "duration", NULL}; for (int i = 0; simple_elements[i]; i++) { xmlNodePtr cur = node->children; while (cur) { if (cur->type == XML_ELEMENT_NODE && xmlStrcmp(cur->name, (const xmlChar *)simple_elements[i]) == 0 && xmlStrcmp(cur->ns->href, (const xmlChar *)NAMESPACE) == 0) { xmlChar *content = xmlNodeGetContent(cur); printf(" %s: %s\n", simple_elements[i], content ? (char *)content : "null"); xmlFree(content); } cur = cur->next; } } // Attribution (playlist only) if (!is_track) { xmlNodePtr attribution = xmlFirstElementChild(node); while (attribution) { if (xmlStrcmp(attribution->name, (const xmlChar *)"attribution") == 0) { printf(" attribution:\n"); xmlNodePtr child = attribution->children; while (child) { if (child->type == XML_ELEMENT_NODE) { xmlChar *content = xmlNodeGetContent(child); printf(" %s: %s\n", (char *)child->name, content ? (char *)content : "null"); xmlFree(content); } child = child->next; } break; } attribution = attribution->next; } } // Links, metas, extensions xmlNodePtr cur = node->children; while (cur) { if (cur->type == XML_ELEMENT_NODE && xmlStrcmp(cur->ns->href, (const xmlChar *)NAMESPACE) == 0) { if (xmlStrcmp(cur->name, (const xmlChar *)"link") == 0) { xmlChar *rel = xmlGetProp(cur, (const xmlChar *)"rel"); xmlChar *content = xmlNodeGetContent(cur); printf(" link (rel=%s): %s\n", rel ? (char *)rel : "null", content ? (char *)content : "null"); xmlFree(rel); xmlFree(content); } else if (xmlStrcmp(cur->name, (const xmlChar *)"meta") == 0) { xmlChar *rel = xmlGetProp(cur, (const xmlChar *)"rel"); xmlChar *content = xmlNodeGetContent(cur); printf(" meta (rel=%s): %s\n", rel ? (char *)rel : "null", content ? (char *)content : "null"); xmlFree(rel); xmlFree(content); } else if (xmlStrcmp(cur->name, (const xmlChar *)"extension") == 0) { xmlChar *app = xmlGetProp(cur, (const xmlChar *)"application"); // For simplicity, print first-level content xmlChar *content = xmlNodeGetContent(cur); printf(" extension (application=%s): %s\n", app ? (char *)app : "null", content ? (char *)content : "null"); xmlFree(app); xmlFree(content); } } cur = cur->next; } } void xspf_print_properties(XSPFHandler *handler) { if (handler->doc == NULL) { fprintf(stderr, "No file loaded\n"); return; } printf("XSPF Properties:\n"); xmlNodePtr playlist = xmlDocGetRootElement(handler->doc); printf("\nPlaylist Attributes:\n"); xmlChar *xmlns = xmlGetProp(playlist, (const xmlChar *)"xmlns"); xmlChar *version = xmlGetProp(playlist, (const xmlChar *)"version"); printf(" xmlns: %s\n", xmlns ? (char *)xmlns : "null"); printf(" version: %s\n", version ? (char *)version : "null"); xmlFree(xmlns); xmlFree(version); printf("\nPlaylist Elements:\n"); print_node_properties(playlist, 0); xmlNodePtr track_list = playlist->children; while (track_list) { if (track_list->type == XML_ELEMENT_NODE && xmlStrcmp(track_list->name, (const xmlChar *)"trackList") == 0) { xmlNodePtr track = track_list->children; int track_num = 1; while (track) { if (track->type == XML_ELEMENT_NODE && xmlStrcmp(track->name, (const xmlChar *)"track") == 0) { printf("\nTrack %d Elements:\n", track_num++); print_node_properties(track, 1); } track = track->next; } break; } track_list = track_list->next; } } int xspf_save(XSPFHandler *handler, const char *file_path) { if (handler->doc == NULL) { fprintf(stderr, "No file loaded\n"); return -1; } return xmlSaveFormatFileEnc(file_path, handler->doc, "UTF-8", 1); } void xspf_free(XSPFHandler *handler) { if (handler->doc) { xmlFreeDoc(handler->doc); handler->doc = NULL; } } // Example usage: // int main() { // XSPFHandler handler; // xspf_init(&handler); // if (xspf_load(&handler, "example.xspf") == 0) { // xspf_print_properties(&handler); // xspf_save(&handler, "output.xspf"); // } // xspf_free(&handler); // xmlCleanupParser(); // return 0; // } // ===== end task-848 .XSPF ===== // ===== task-849 .XX [C++] ===== #include #include #include #include #include #include #include #include // Requires OpenSSL for SHA-256 class XXFileHandler { private: std::string filename; std::vector binaryData; std::map properties; struct Token { std::string data; bool isString; }; void initProperties() { properties["text_based"] = "true"; properties["supported_notations"] = "hex, prefixed_hex, binary, quoted_strings"; properties["comment_styles"] = "single-line, multi-line, unicode_box"; properties["no_header"] = "true"; properties["version_features"] = "0.5 (binary support)"; properties["parsing_behavior"] = "concatenated binary extraction"; } public: XXFileHandler(const std::string& fname) : filename(fname) { initProperties(); readAndDecode(); } void readAndDecode() { std::ifstream file(filename); std::vector lines; std::string line; while (std::getline(file, line)) { lines.push_back(line); } file.close(); binaryData = parseXX(lines); } std::vector parseXX(const std::vector& lines) { std::vector out; bool multilineComment = false; std::string joinedLine; std::string asciiComments[] = {"#", ";", "%", "|", "\x1B", "-", "/"}; std::string twoCharComments[] = {"--", "//"}; std::string filterList[] = {",", "$", "\\x", "0x", "h", ":", " "}; std::map escapes = {{'n', '\n'}, {'\\', '\\'}, {'t', '\t'}, {'r', '\r'}}; for (const auto& ln : lines) { auto result = filterMultiLineComments(multilineComment, joinedLine, ln); multilineComment = std::get<0>(result); joinedLine = std::get<1>(result); std::string line = std::get<2>(result); bool mustContinue = std::get<3>(result); if (mustContinue) continue; auto tokens = tokenizeXX(line, escapes); std::string lineHex; for (const auto& token : tokens) { if (isComment(token.data, asciiComments, sizeof(asciiComments)/sizeof(std::string), twoCharComments, sizeof(twoCharComments)/sizeof(std::string))) continue; std::string cleaned = filterIgnored(token.data, filterList, sizeof(filterList)/sizeof(std::string)); if (token.isString) { cleaned = asciiToHex(token.data, escapes); } else if (cleaned.substr(0, 2) == "0y" && cleaned.length() == 10) { unsigned char val = std::stoi(cleaned.substr(2), nullptr, 2); std::stringstream ss; ss << std::hex << std::setw(2) << std::setfill('0') << static_cast(val); cleaned = ss.str(); } auto bytes = hexToBytes(cleaned); out.insert(out.end(), bytes.begin(), bytes.end()); lineHex += cleaned; } } return out; } std::tuple filterMultiLineComments(bool multilineComment, std::string joinedLine, std::string line) { std::string lineResult = joinedLine; joinedLine = ""; bool mustContinue = false; while (!line.empty()) { if (multilineComment) { size_t pos = line.find("*/"); if (pos != std::string::npos) { line = line.substr(pos + 2); multilineComment = false; } else { joinedLine += lineResult; mustContinue = true; break; } } else { size_t pos = line.find("/*"); if (pos != std::string::npos) { lineResult += line.substr(0, pos); line = line.substr(pos + 2); multilineComment = true; } else { lineResult += line; break; } } } return {multilineComment, joinedLine, lineResult, mustContinue}; } std::vector tokenizeXX(std::string line, const std::map& escapes) { std::vector tokens; std::string buf; bool verbatim = false; bool isEscape = false; bool isString = false; line.erase(0, line.find_first_not_of(" \t")); // trim left line.erase(line.find_last_not_of(" \t") + 1); // trim right for (char c : line) { if (c == '\\' && verbatim && !isEscape) { isEscape = true; continue; } if (isEscape) { auto it = escapes.find(c); buf += (it != escapes.end()) ? it->second : ('\\' + c); isEscape = false; continue; } if (c == '"') { verbatim = !verbatim; isString = true; if (!verbatim && !buf.empty()) { tokens.push_back({buf, isString}); isString = false; } buf.clear(); continue; } if (c == ' ' && !verbatim) { if (!buf.empty()) tokens.push_back({buf, isString}); buf.clear(); continue; } buf += c; } if (!buf.empty()) tokens.push_back({buf, isString}); return tokens; } bool isComment(const std::string& data, const std::string* asciiComments, size_t asciiSize, const std::string* twoCharComments, size_t twoSize) { if (data.empty()) return false; char first = data[0]; for (size_t i = 0; i < asciiSize; ++i) { if (asciiComments[i][0] == first) return true; } if (data.length() > 1) { std::string two = data.substr(0, 2); for (size_t i = 0; i < twoSize; ++i) { if (twoCharComments[i] == two) return true; } } unsigned int code = static_cast(first); return code >= 9472 && code < 9632; } std::string filterIgnored(std::string text, const std::string* filterList, size_t filterSize) { for (size_t i = 0; i < filterSize; ++i) { size_t pos; while ((pos = text.find(filterList[i])) != std::string::npos) { text.erase(pos, filterList[i].length()); } } return text; } std::string asciiToHex(const std::string& str, const std::map& escapes) { std::stringstream hex; for (size_t i = 0; i < str.length(); ) { if (str[i] == '\\' && i + 1 < str.length()) { char next = str[i + 1]; auto it = escapes.find(next); char esc = (it != escapes.end()) ? it->second : ('\\' + next); hex << std::hex << std::setw(2) << std::setfill('0') << static_cast(static_cast(esc)); i += 2; } else { hex << std::hex << std::setw(2) << std::setfill('0') << static_cast(static_cast(str[i])); ++i; } } return hex.str(); } std::vector hexToBytes(const std::string& hex) { std::vector bytes; for (size_t i = 0; i < hex.length(); i += 2) { std::string byteStr = hex.substr(i, 2); if (byteStr.empty()) continue; unsigned char byte = static_cast(std::stoi(byteStr, nullptr, 16)); bytes.push_back(byte); } return bytes; } std::string write(const std::string& outputFilename = "") { std::string outFile = outputFilename; if (outFile.empty()) { unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256(&binaryData[0], binaryData.size(), hash); std::stringstream ss; ss << std::hex << std::setw(2) << std::setfill('0'); for (int i = 0; i < 4; ++i) { // First 8 hex chars (4 bytes) ss << static_cast(hash[i]); } std::string shortHash = ss.str(); size_t pos = filename.rfind(".xx"); outFile = (pos != std::string::npos) ? filename.substr(0, pos) : filename; outFile += "." + shortHash + ".bin"; } std::ofstream ofs(outFile, std::ios::binary); ofs.write(reinterpret_cast(binaryData.data()), binaryData.size()); ofs.close(); return outFile; } void printProperties() { std::cout << "Properties of the .XX File Format:" << std::endl; for (const auto& prop : properties) { std::cout << prop.first << ": " << prop.second << std::endl; } std::cout << "\nCompiled Binary (Hex Dump):" << std::endl; hexDump(binaryData); } void hexDump(const std::vector& data) { for (size_t offset = 0; offset < data.size(); offset += 16) { std::stringstream hex; std::stringstream ascii; size_t end = std::min(offset + 16, data.size()); for (size_t i = offset; i < end; ++i) { hex << std::hex << std::setw(2) << std::setfill('0') << static_cast(data[i]) << " "; ascii << ((data[i] >= 32 && data[i] < 127) ? static_cast(data[i]) : '.'); } std::cout << std::hex << std::setw(8) << std::setfill('0') << offset << ": " << std::left << std::setw(47) << hex.str() << " " << ascii.str() << std::endl; } } }; // Example usage: // int main() { // XXFileHandler handler("example.xx"); // handler.printProperties(); // handler.write(); // return 0; // } // ===== end task-849 .XX ===== // ===== task-850 .XXE [C] ===== #include #include #include #define ALPHABET "+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" typedef struct { char *filename; char *mode; unsigned char *binary_data; size_t data_size; } XXEHandler; int decode_map[256]; void init_decode_map() { memset(decode_map, -1, sizeof(decode_map)); for (int i = 0; i < 64; i++) { decode_map[(unsigned char)ALPHABET[i]] = i; } } XXEHandler* create_xxe_handler() { XXEHandler* handler = malloc(sizeof(XXEHandler)); handler->filename = NULL; handler->mode = NULL; handler->binary_data = NULL; handler->data_size = 0; init_decode_map(); return handler; } void destroy_xxe_handler(XXEHandler* handler) { free(handler->filename); free(handler->mode); free(handler->binary_data); free(handler); } int open_and_decode(XXEHandler* handler, const char* filepath) { FILE* file = fopen(filepath, "r"); if (!file) return -1; char line[1024]; while (fgets(line, sizeof(line), file) && !strstr(line, "begin ")) {} if (feof(file)) { fclose(file); return -1; } char* token = strtok(line + 6, " \n"); // Skip "begin " handler->mode = strdup(token); token = strtok(NULL, " \n"); handler->filename = strdup(token); unsigned char* data = NULL; size_t capacity = 0; size_t size = 0; while (fgets(line, sizeof(line), file)) { char* trim = strtok(line, "\n"); if (strcmp(trim, "end") == 0) break; if (strcmp(trim, "+") == 0 || strlen(trim) == 0) continue; char len_char = trim[0]; int length = decode_map[(unsigned char)len_char]; if (length <= 0) continue; char* enc_data = trim + 1; int enc_len = strlen(enc_data); for (int j = 0; j < enc_len; j += 4) { char group[5] = {0}; strncpy(group, enc_data + j, 4); int bits[4] = {0}; for (int k = 0; k < 4; k++) bits[k] = decode_map[(unsigned char)group[k]]; unsigned char byte1 = (bits[0] << 2) | (bits[1] >> 4); unsigned char byte2 = ((bits[1] & 0x0F) << 4) | (bits[2] >> 2); unsigned char byte3 = ((bits[2] & 0x03) << 6) | bits[3]; int remaining = (length - (j / 4 * 3) > 3) ? 3 : length - (j / 4 * 3); if (size + remaining > capacity) { capacity = capacity ? capacity * 2 : 1024; data = realloc(data, capacity); } if (remaining > 0) data[size++] = byte1; if (remaining > 1) data[size++] = byte2; if (remaining > 2) data[size++] = byte3; } } fclose(file); handler->binary_data = data; handler->data_size = size; return 0; } void print_properties(XXEHandler* handler) { printf("Filename: %s\n", handler->filename); printf("Permissions Mode: %s\n", handler->mode); } int write_xxe(XXEHandler* handler, const char* output_filepath, const char* new_filename, const char* new_mode, const unsigned char* new_binary_data, size_t new_data_size) { free(handler->filename); free(handler->mode); free(handler->binary_data); handler->filename = strdup(new_filename); handler->mode = strdup(new_mode); handler->binary_data = malloc(new_data_size); memcpy(handler->binary_data, new_binary_data, new_data_size); handler->data_size = new_data_size; FILE* file = fopen(output_filepath, "w"); if (!file) return -1; fprintf(file, "begin %s %s\n", handler->mode, handler->filename); size_t i = 0; while (i < new_data_size) { size_t chunk_size = (new_data_size - i < 45) ? new_data_size - i : 45; char len_char = ALPHABET[chunk_size]; fputc(len_char, file); size_t j; for (j = 0; j < chunk_size; j += 3) { unsigned char b1 = (i + j < new_data_size) ? new_binary_data[i + j] : 0; unsigned char b2 = (i + j + 1 < new_data_size) ? new_binary_data[i + j + 1] : 0; unsigned char b3 = (i + j + 2 < new_data_size) ? new_binary_data[i + j + 2] : 0; int out1 = (b1 >> 2); int out2 = ((b1 & 0x03) << 4) | (b2 >> 4); int out3 = ((b2 & 0x0F) << 2) | (b3 >> 6); int out4 = b3 & 0x3F; fputc(ALPHABET[out1], file); fputc(ALPHABET[out2], file); fputc(ALPHABET[out3], file); fputc(ALPHABET[out4], file); } fputc('\n', file); i += chunk_size; } fprintf(file, "+\nend\n"); fclose(file); return 0; } // Example usage: // int main() { // XXEHandler* handler = create_xxe_handler(); // if (open_and_decode(handler, "example.xxe") == 0) { // print_properties(handler); // } // unsigned char data[] = {/* binary data */}; // write_xxe(handler, "new.xxe", "newfile.bin", "644", data, sizeof(data)); // destroy_xxe_handler(handler); // return 0; // } // ===== end task-850 .XXE ===== // ===== task-851 .XXX [C] ===== #include #include #include typedef struct { char* filepath; uint32_t stitch_count_minus_1; uint32_t number_of_colors; uint16_t design_width; uint16_t design_height; uint16_t last_stitch_x; uint16_t last_stitch_neg_y; uint16_t neg_left_extent; uint16_t top_extent; uint32_t end_of_stitches_pointer; // Add arrays for stitches and colors } XXXFileHandler; XXXFileHandler* create_xxx_handler(const char* filepath) { XXXFileHandler* handler = malloc(sizeof(XXXFileHandler)); handler->filepath = strdup(filepath); return handler; } void read_xxx(XXXFileHandler* handler) { FILE* f = fopen(handler->filepath, "rb"); if (!f) return; fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t* data = malloc(size); fread(data, 1, size, f); fclose(f); handler->stitch_count_minus_1 = *(uint32_t*)(data + 0x17); handler->number_of_colors = *(uint32_t*)(data + 0x27); // Similar for other LE16/LE32 using casts or unions // Stitch and color parsing loops free(data); } void print_properties(XXXFileHandler* handler) { printf("Stitch Count Minus 1: %u\n", handler->stitch_count_minus_1); // Print others } void write_xxx(XXXFileHandler* handler, const char* new_filepath) { // Open file, write binary data mirroring format } void destroy_xxx_handler(XXXFileHandler* handler) { free(handler->filepath); free(handler); } // Usage example: // int main() { // XXXFileHandler* handler = create_xxx_handler("example.xxx"); // read_xxx(handler); // print_properties(handler); // write_xxx(handler, "new.xxx"); // destroy_xxx_handler(handler); // return 0; // } // ===== end task-851 .XXX ===== // ===== task-852 .XYZ [C] ===== #include #include #include typedef struct { char *element; double x, y, z; } Atom; typedef struct { char *filepath; int atom_count; char *title; Atom *atoms; } XYZFileHandler; XYZFileHandler* xyz_create(const char *filepath) { XYZFileHandler *handler = (XYZFileHandler*)malloc(sizeof(XYZFileHandler)); handler->filepath = strdup(filepath); handler->atom_count = 0; handler->title = NULL; handler->atoms = NULL; return handler; } void xyz_read(XYZFileHandler *handler) { FILE *file = fopen(handler->filepath, "r"); if (!file) { fprintf(stderr, "Error opening file.\n"); return; } char line[256]; if (!fgets(line, sizeof(line), file)) { fprintf(stderr, "Invalid .XYZ file format.\n"); fclose(file); return; } handler->atom_count = atoi(line); if (!fgets(line, sizeof(line), file)) { fprintf(stderr, "Invalid .XYZ file format.\n"); fclose(file); return; } handler->title = strdup(strtok(line, "\n")); handler->atoms = (Atom*)malloc(handler->atom_count * sizeof(Atom)); int index = 0; while (fgets(line, sizeof(line), file)) { char *token = strtok(line, " \t\n"); if (token && index < handler->atom_count) { handler->atoms[index].element = strdup(token); token = strtok(NULL, " \t\n"); handler->atoms[index].x = atof(token); token = strtok(NULL, " \t\n"); handler->atoms[index].y = atof(token); token = strtok(NULL, " \t\n"); handler->atoms[index].z = atof(token); index++; } } if (index != handler->atom_count) { fprintf(stderr, "Atom count mismatch in .XYZ file.\n"); } fclose(file); } void xyz_write(XYZFileHandler *handler, const char *new_filepath) { const char *path = new_filepath ? new_filepath : handler->filepath; FILE *file = fopen(path, "w"); if (!file) { fprintf(stderr, "Error opening file for writing.\n"); return; } fprintf(file, "%d\n", handler->atom_count); fprintf(file, "%s\n", handler->title); for (int i = 0; i < handler->atom_count; i++) { fprintf(file, "%s %.6f %.6f %.6f\n", handler->atoms[i].element, handler->atoms[i].x, handler->atoms[i].y, handler->atoms[i].z); } fclose(file); } void xyz_print_properties(XYZFileHandler *handler) { printf("Atom Count: %d\n", handler->atom_count); printf("Title: %s\n", handler->title); printf("Atoms:\n"); for (int i = 0; i < handler->atom_count; i++) { printf("Atom %d: Element: %s, X: %.6f, Y: %.6f, Z: %.6f\n", i + 1, handler->atoms[i].element, handler->atoms[i].x, handler->atoms[i].y, handler->atoms[i].z); } } void xyz_destroy(XYZFileHandler *handler) { free(handler->filepath); free(handler->title); for (int i = 0; i < handler->atom_count; i++) { free(handler->atoms[i].element); } free(handler->atoms); free(handler); } // Example usage: // int main() { // XYZFileHandler *handler = xyz_create("example.xyz"); // xyz_read(handler); // xyz_print_properties(handler); // xyz_write(handler, "new_example.xyz"); // xyz_destroy(handler); // return 0; // } // ===== end task-852 .XYZ ===== // ===== task-853 .XZ [C] ===== #include #include #include #include #include typedef struct { uint8_t *data; size_t size; size_t offset; // Properties would be stored in a dynamic structure, but for simplicity, we print directly uint8_t *original_data; size_t original_size; } XZParser; XZParser* xzparser_new(const char* filename) { XZParser* parser = malloc(sizeof(XZParser)); FILE* f = fopen(filename, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); parser->size = ftell(f); fseek(f, 0, SEEK_SET); parser->data = malloc(parser->size); fread(parser->data, 1, parser->size, f); fclose(f); parser->offset = 0; parser->original_data = malloc(parser->size); memcpy(parser->original_data, parser->data, parser->size); parser->original_size = parser->size; return parser; } void xzparser_free(XZParser* parser) { free(parser->data); free(parser->original_data); free(parser); } uint64_t read_vli(XZParser* parser) { uint64_t val = 0; int shift = 0; for (int i = 0; i < 9; i++) { uint8_t byte = parser->data[parser->offset++]; val |= ((uint64_t)(byte & 0x7F)) << shift; if ((byte & 0x80) == 0) return val; shift += 7; } fprintf(stderr, "Invalid VLI\n"); exit(1); } void read_bytes(XZParser* parser, uint8_t* buf, size_t n) { memcpy(buf, parser->data + parser->offset, n); parser->offset += n; } uint32_t read_uint32(XZParser* parser) { uint32_t val; memcpy(&val, parser->data + parser->offset, 4); parser->offset += 4; return val; } void parse_block(XZParser* parser, int check_id) { printf("Block:\n"); uint8_t header_size_enc; read_bytes(parser, &header_size_enc, 1); size_t header_size = (header_size_enc + 1) * 4; printf(" Header Size: %zu bytes\n", header_size); uint8_t block_flags; read_bytes(parser, &block_flags, 1); int num_filters = (block_flags & 0x03) + 1; bool has_comp_size = (block_flags & 0x40) != 0; bool has_uncomp_size = (block_flags & 0x80) != 0; printf(" Flags: 0x%02x (Filters: %d, Comp: %d, Uncomp: %d)\n", block_flags, num_filters, has_comp_size, has_uncomp_size); uint64_t comp_size = 0; if (has_comp_size) { comp_size = read_vli(parser); printf(" Compressed Size: %llu\n", (unsigned long long)comp_size); } if (has_uncomp_size) { uint64_t uncomp_size = read_vli(parser); printf(" Uncompressed Size: %llu\n", (unsigned long long)uncomp_size); } printf(" Filters:\n"); for (int i = 0; i < num_filters; i++) { uint64_t filter_id = read_vli(parser); uint64_t prop_size = read_vli(parser); uint8_t* props = malloc(prop_size); read_bytes(parser, props, prop_size); printf(" Filter %d: ID %llu, Prop Size %llu, Props: ", i + 1, (unsigned long long)filter_id, (unsigned long long)prop_size); for (size_t j = 0; j < prop_size; j++) { printf("%02x ", props[j]); } printf("\n"); free(props); } size_t pad_start = parser->offset; int pad_bytes = 0; while (pad_bytes < 3 && parser->data[parser->offset++] == 0) pad_bytes++; parser->offset = pad_start + pad_bytes; printf(" Header Padding: %d bytes\n", pad_bytes); uint32_t block_crc = read_uint32(parser); printf(" Header CRC32: 0x%08x\n", block_crc); size_t comp_start = parser->offset; parser->offset += comp_size; printf(" Compressed Data: %llu bytes (skipped)\n", (unsigned long long)comp_size); int block_pad = 0; while (block_pad < 3 && parser->data[parser->offset++] == 0) block_pad++; parser->offset -= block_pad; printf(" Block Padding: %d bytes\n", block_pad); int check_size = 0; switch (check_id) { case 0x00: check_size = 0; break; case 0x01: check_size = 4; break; case 0x04: check_size = 8; break; case 0x0A: check_size = 32; break; default: check_size = 64; } uint8_t* check_bytes = malloc(check_size); read_bytes(parser, check_bytes, check_size); printf(" Check: "); for (int j = 0; j < check_size; j++) { printf("%02x ", check_bytes[j]); } printf("\n"); free(check_bytes); } void parse_stream(XZParser* parser) { uint8_t magic[6]; read_bytes(parser, magic, 6); printf("Stream Header Magic: "); for (int i = 0; i < 6; i++) printf("%02x ", magic[i]); printf("\n"); uint8_t flags[2]; read_bytes(parser, flags, 2); int check_id = flags[1] & 0x0F; printf("Stream Flags: 0x%02x 0x%02x (Check ID: %d)\n", flags[0], flags[1], check_id); uint32_t header_crc = read_uint32(parser); printf("Header CRC32: 0x%08x\n", header_crc); printf("Blocks:\n"); while (true) { if (parser->data[parser->offset] == 0) break; parse_block(parser, check_id); } printf("Index:\n"); uint8_t index_ind; read_bytes(parser, &index_ind, 1); printf(" Indicator: 0x%02x\n", index_ind); uint64_t num_records = read_vli(parser); printf(" Number of Records: %llu\n", (unsigned long long)num_records); for (uint64_t i = 0; i < num_records; i++) { uint64_t unpadded = read_vli(parser); uint64_t uncomp = read_vli(parser); printf(" Record %llu: Unpadded %llu, Uncompressed %llu\n", (unsigned long long)i + 1, (unsigned long long)unpadded, (unsigned long long)uncomp); } size_t pad_start = parser->offset; int pad_bytes = 0; while (pad_bytes < 3 && parser->data[parser->offset++] == 0) pad_bytes++; parser->offset = pad_start + pad_bytes; printf(" Index Padding: %d bytes\n", pad_bytes); uint32_t index_crc = read_uint32(parser); printf(" Index CRC32: 0x%08x\n", index_crc); uint32_t footer_crc = read_uint32(parser); printf("Footer CRC32: 0x%08x\n", footer_crc); uint32_t backward_size = read_uint32(parser); printf("Backward Size: %u\n", (backward_size + 1) * 4); uint8_t footer_flags[2]; read_bytes(parser, footer_flags, 2); printf("Footer Flags: 0x%02x 0x%02x\n", footer_flags[0], footer_flags[1]); uint8_t footer_magic[2]; read_bytes(parser, footer_magic, 2); printf("Footer Magic: %02x %02x\n", footer_magic[0], footer_magic[1]); int pad_count = 0; while (parser->offset < parser->size && parser->data[parser->offset++] == 0) pad_count++; if (pad_count % 4 != 0) { fprintf(stderr, "Invalid Stream Padding\n"); exit(1); } printf("Stream Padding: %d bytes\n", pad_count); parser->offset -= pad_count; // Reset } void xzparser_parse_and_print(XZParser* parser) { int stream_num = 1; while (parser->offset < parser->size) { printf("Stream %d:\n", stream_num++); parse_stream(parser); } } void xzparser_write(XZParser* parser, const char* output_filename) { FILE* f = fopen(output_filename, "wb"); if (!f) return; fwrite(parser->original_data, 1, parser->original_size, f); fclose(f); } // ===== end task-853 .XZ ===== // ===== task-854 .Y [C++] ===== #include #include #include #include #include // For fixed-width types class SegYHandler { private: std::string filepath; std::string textualHeader; struct BinaryHeader { int32_t jobId; int32_t lineNum; int32_t reelNum; int16_t dataTracesEnsemble; int16_t auxTracesEnsemble; int16_t sampleInterval; int16_t origSampleInterval; int16_t samplesPerTrace; int16_t origSamplesPerTrace; int16_t formatCode; int16_t ensembleFold; int16_t traceSorting; int16_t verticalSum; int16_t sweepFreqStart; int16_t sweepFreqEnd; int16_t sweepLength; int16_t sweepType; int16_t sweepChannel; int16_t sweepTaperStart; int16_t sweepTaperEnd; int16_t taperType; int16_t correlatedTraces; int16_t binaryGain; int16_t ampRecovery; int16_t measurementSystem; int16_t impulsePolarity; int16_t vibratoryPolarity; uint16_t segyRevision; // Unsigned int16_t fixedTraceFlag; int16_t extTextHeaders; } binaryHeader; // Add trace struct public: SegYHandler(const std::string& fp) : filepath(fp) {} void read() { std::ifstream file(filepath, std::ios::binary); if (!file) return; // Textual Header std::vector textBuf(3200); file.read(textBuf.data(), 3200); textualHeader = std::string(textBuf.begin(), textBuf.end()); // EBCDIC conversion needed // Binary Header char binBuf[400]; file.read(binBuf, 400); memcpy(&binaryHeader.jobId, binBuf + 0, 4); memcpy(&binaryHeader.lineNum, binBuf + 4, 4); memcpy(&binaryHeader.reelNum, binBuf + 8, 4); memcpy(&binaryHeader.dataTracesEnsemble, binBuf + 12, 2); memcpy(&binaryHeader.auxTracesEnsemble, binBuf + 14, 2); memcpy(&binaryHeader.sampleInterval, binBuf + 16, 2); memcpy(&binaryHeader.origSampleInterval, binBuf + 18, 2); memcpy(&binaryHeader.samplesPerTrace, binBuf + 20, 2); memcpy(&binaryHeader.origSamplesPerTrace, binBuf + 22, 2); memcpy(&binaryHeader.formatCode, binBuf + 24, 2); memcpy(&binaryHeader.ensembleFold, binBuf + 26, 2); memcpy(&binaryHeader.traceSorting, binBuf + 28, 2); memcpy(&binaryHeader.verticalSum, binBuf + 30, 2); memcpy(&binaryHeader.sweepFreqStart, binBuf + 32, 2); memcpy(&binaryHeader.sweepFreqEnd, binBuf + 34, 2); memcpy(&binaryHeader.sweepLength, binBuf + 36, 2); memcpy(&binaryHeader.sweepType, binBuf + 38, 2); memcpy(&binaryHeader.sweepChannel, binBuf + 40, 2); memcpy(&binaryHeader.sweepTaperStart, binBuf + 42, 2); memcpy(&binaryHeader.sweepTaperEnd, binBuf + 44, 2); memcpy(&binaryHeader.taperType, binBuf + 46, 2); memcpy(&binaryHeader.correlatedTraces, binBuf + 48, 2); memcpy(&binaryHeader.binaryGain, binBuf + 50, 2); memcpy(&binaryHeader.ampRecovery, binBuf + 52, 2); memcpy(&binaryHeader.measurementSystem, binBuf + 54, 2); memcpy(&binaryHeader.impulsePolarity, binBuf + 56, 2); memcpy(&binaryHeader.vibratoryPolarity, binBuf + 58, 2); // Unassigned 60-300 memcpy(&binaryHeader.segyRevision, binBuf + 300, 2); memcpy(&binaryHeader.fixedTraceFlag, binBuf + 302, 2); memcpy(&binaryHeader.extTextHeaders, binBuf + 304, 2); // Unassigned 306-400 // Trace Header (partial) } void printProperties() { std::cout << "Textual Header:" << std::endl << textualHeader << std::endl; std::cout << "Binary Header:" << std::endl; std::cout << "Job ID: " << binaryHeader.jobId << std::endl; std::cout << "Line Number: " << binaryHeader.lineNum << std::endl; std::cout << "Reel Number: " << binaryHeader.reelNum << std::endl; std::cout << "Data Traces per Ensemble: " << binaryHeader.dataTracesEnsemble << std::endl; std::cout << "Auxiliary Traces per Ensemble: " << binaryHeader.auxTracesEnsemble << std::endl; std::cout << "Sample Interval: " << binaryHeader.sampleInterval << std::endl; std::cout << "Original Sample Interval: " << binaryHeader.origSampleInterval << std::endl; std::cout << "Samples per Trace: " << binaryHeader.samplesPerTrace << std::endl; std::cout << "Original Samples per Trace: " << binaryHeader.origSamplesPerTrace << std::endl; std::cout << "Format Code: " << binaryHeader.formatCode << std::endl; std::cout << "Ensemble Fold: " << binaryHeader.ensembleFold << std::endl; std::cout << "Trace Sorting: " << binaryHeader.traceSorting << std::endl; std::cout << "Vertical Sum: " << binaryHeader.verticalSum << std::endl; std::cout << "Sweep Freq Start: " << binaryHeader.sweepFreqStart << std::endl; std::cout << "Sweep Freq End: " << binaryHeader.sweepFreqEnd << std::endl; std::cout << "Sweep Length: " << binaryHeader.sweepLength << std::endl; std::cout << "Sweep Type: " << binaryHeader.sweepType << std::endl; std::cout << "Sweep Channel: " << binaryHeader.sweepChannel << std::endl; std::cout << "Sweep Taper Start: " << binaryHeader.sweepTaperStart << std::endl; std::cout << "Sweep Taper End: " << binaryHeader.sweepTaperEnd << std::endl; std::cout << "Taper Type: " << binaryHeader.taperType << std::endl; std::cout << "Correlated Traces: " << binaryHeader.correlatedTraces << std::endl; std::cout << "Binary Gain: " << binaryHeader.binaryGain << std::endl; std::cout << "Amp Recovery: " << binaryHeader.ampRecovery << std::endl; std::cout << "Measurement System: " << binaryHeader.measurementSystem << std::endl; std::cout << "Impulse Polarity: " << binaryHeader.impulsePolarity << std::endl; std::cout << "Vibratory Polarity: " << binaryHeader.vibratoryPolarity << std::endl; std::cout << "SEG-Y Revision: " << binaryHeader.segyRevision << std::endl; std::cout << "Fixed Trace Flag: " << binaryHeader.fixedTraceFlag << std::endl; std::cout << "Extended Text Headers: " << binaryHeader.extTextHeaders << std::endl; } void write(const std::string& outputPath) { std::ofstream out(outputPath, std::ios::binary); out.write(textualHeader.c_str(), 3200); char binBuf[400] = {0}; memcpy(binBuf + 0, &binaryHeader.jobId, 4); memcpy(binBuf + 4, &binaryHeader.lineNum, 4); memcpy(binBuf + 8, &binaryHeader.reelNum, 4); memcpy(binBuf + 12, &binaryHeader.dataTracesEnsemble, 2); memcpy(binBuf + 14, &binaryHeader.auxTracesEnsemble, 2); memcpy(binBuf + 16, &binaryHeader.sampleInterval, 2); memcpy(binBuf + 18, &binaryHeader.origSampleInterval, 2); memcpy(binBuf + 20, &binaryHeader.samplesPerTrace, 2); memcpy(binBuf + 22, &binaryHeader.origSamplesPerTrace, 2); memcpy(binBuf + 24, &binaryHeader.formatCode, 2); memcpy(binBuf + 26, &binaryHeader.ensembleFold, 2); memcpy(binBuf + 28, &binaryHeader.traceSorting, 2); memcpy(binBuf + 30, &binaryHeader.verticalSum, 2); memcpy(binBuf + 32, &binaryHeader.sweepFreqStart, 2); memcpy(binBuf + 34, &binaryHeader.sweepFreqEnd, 2); memcpy(binBuf + 36, &binaryHeader.sweepLength, 2); memcpy(binBuf + 38, &binaryHeader.sweepType, 2); memcpy(binBuf + 40, &binaryHeader.sweepChannel, 2); memcpy(binBuf + 42, &binaryHeader.sweepTaperStart, 2); memcpy(binBuf + 44, &binaryHeader.sweepTaperEnd, 2); memcpy(binBuf + 46, &binaryHeader.taperType, 2); memcpy(binBuf + 48, &binaryHeader.correlatedTraces, 2); memcpy(binBuf + 50, &binaryHeader.binaryGain, 2); memcpy(binBuf + 52, &binaryHeader.ampRecovery, 2); memcpy(binBuf + 54, &binaryHeader.measurementSystem, 2); memcpy(binBuf + 56, &binaryHeader.impulsePolarity, 2); memcpy(binBuf + 58, &binaryHeader.vibratoryPolarity, 2); memcpy(binBuf + 300, &binaryHeader.segyRevision, 2); memcpy(binBuf + 302, &binaryHeader.fixedTraceFlag, 2); memcpy(binBuf + 304, &binaryHeader.extTextHeaders, 2); out.write(binBuf, 400); // Write traces (partial) } }; // Usage example remains the same. // ===== end task-854 .Y ===== // ===== task-855 .YAML [C] ===== #include #include #include #include typedef struct { char *content; } YamlHandler; YamlHandler *yaml_handler_init(const char *filename) { FILE *file = fopen(filename, "r"); if (!file) { perror("Failed to open file"); return NULL; } fseek(file, 0, SEEK_END); long length = ftell(file); fseek(file, 0, SEEK_SET); YamlHandler *handler = malloc(sizeof(YamlHandler)); handler->content = malloc(length + 1); fread(handler->content, 1, length, file); handler->content[length] = '\0'; fclose(file); return handler; } void yaml_handler_free(YamlHandler *handler) { free(handler->content); free(handler); } bool has_substring(const char *str, const char *sub) { return strstr(str, sub) != NULL; } bool has_indentation(const char *str) { const char *p = str; while ((p = strchr(p, '\n')) != NULL) { p++; if (strncmp(p, " ", 2) == 0) return true; } return false; } int count_occurrences(const char *str, const char *sub) { int count = 0; const char *p = str; while ((p = strstr(p, sub)) != NULL) { count++; p += strlen(sub); } return count; } void print_properties(YamlHandler *handler) { printf("Presence of Byte Order Mark (BOM): %s\n", has_substring(handler->content, "\xEF\xBB\xBF") ? "true" : "false"); // UTF-8 BOM bytes printf("Encoding: UTF-8 (assumed; BOM detection only)\n"); printf("Presence of Document Start Marker: %s\n", has_substring(handler->content, "---") ? "true" : "false"); printf("Presence of Document End Marker: %s\n", has_substring(handler->content, "...") ? "true" : "false"); printf("Presence of Directives: %s\n", (has_substring(handler->content, "\n%") || strncmp(handler->content, "%", 1) == 0) ? "true" : "false"); printf("Presence of Comments: %s\n", has_substring(handler->content, "#") ? "true" : "false"); printf("Presence of Block Sequence Entries: %s\n", has_substring(handler->content, "- ") ? "true" : "false"); printf("Presence of Mappings: %s\n", has_substring(handler->content, ": ") ? "true" : "false"); printf("Presence of Tags: %s\n", has_substring(handler->content, "!") ? "true" : "false"); printf("Presence of Anchors: %s\n", has_substring(handler->content, "&") ? "true" : "false"); printf("Presence of Aliases: %s\n", has_substring(handler->content, "*") ? "true" : "false"); printf("Presence of Literal Block Scalars: %s\n", has_substring(handler->content, "|") ? "true" : "false"); printf("Presence of Folded Block Scalars: %s\n", has_substring(handler->content, ">") ? "true" : "false"); printf("Presence of Single-Quoted Scalars: %s\n", has_substring(handler->content, "'") ? "true" : "false"); printf("Presence of Double-Quoted Scalars: %s\n", has_substring(handler->content, "\"") ? "true" : "false"); printf("Use of Indentation for Structure: %s\n", has_indentation(handler->content) ? "true" : "false"); printf("Support for Multiple Documents: %s\n", count_occurrences(handler->content, "---") > 1 ? "true" : "false"); printf("JSON Compatibility: true\n"); } void write_file(YamlHandler *handler, const char *new_filename) { FILE *file = fopen(new_filename, "w"); if (!file) { perror("Failed to write file"); return; } fprintf(file, "%s", handler->content); fclose(file); } // Example usage: // int main() { // YamlHandler *handler = yaml_handler_init("example.yaml"); // if (handler) { // print_properties(handler); // write_file(handler, "output.yaml"); // yaml_handler_free(handler); // } // return 0; // } // ===== end task-855 .YAML ===== // ===== task-856 .YML [C++] ===== #include #include #include class YmlHandler { private: std::string filename; YAML::Node data; public: YmlHandler(const std::string& filename) : filename(filename) {} void readAndDecode() { // Opens and decodes (parses) the .YML file. std::ifstream file(filename); if (file) { data = YAML::Load(file); } else { std::cerr << "Failed to open file: " << filename << std::endl; } } void printProperties() { // Prints all properties (parsed data) to the console. if (data.IsNull()) { std::cout << "No data loaded. Call readAndDecode() first." << std::endl; return; } std::cout << data << std::endl; } void write(const YAML::Node& newData) { // Writes new data to the .YML file. std::ofstream file(filename); if (file) { file << newData; } else { std::cerr << "Failed to write to file: " << filename << std::endl; } } }; // Example usage: // int main() { // YmlHandler handler("example.yml"); // handler.readAndDecode(); // handler.printProperties(); // YAML::Node newData; // newData["new_key"] = "new_value"; // handler.write(newData); // return 0; // } // ===== end task-856 .YML ===== // ===== task-857 .ZIP [C++] ===== #include #include #include #include #include #include #include #include class ZipHandler { private: std::string filepath; std::map>> file_properties; // local_files, central_directories std::map zip64_eocd; std::map zip64_locator; std::map eocd; public: ZipHandler(const std::string& fp) : filepath(fp) { parse(); } void parse() { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) return; size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(reinterpret_cast(data.data()), size); file_properties["local_files"] = {}; file_properties["central_directories"] = {}; // Find EOCD ssize_t eocd_offset = find_eocd(data); if (eocd_offset == -1) { std::cerr << "Invalid ZIP: No EOCD" << std::endl; return; } // Parse EOCD parse_eocd(data, eocd_offset); // Parse Zip64 if present bool zip64_present = (stoi(eocd["total_entries"]) == 0xFFFF || stoi(eocd["cd_size"]) == 0xFFFFFFFF || stoi(eocd["cd_offset"]) == 0xFFFFFFFF); if (zip64_present) { parse_zip64(data, eocd_offset); } // Parse Central Directory uint64_t cd_offset = stoull(eocd["cd_offset"]); uint64_t total_entries = stoull(eocd["total_entries"]); for (uint64_t i = 0; i < total_entries; ++i) { auto cd_props = parse_central_header(data, cd_offset); file_properties["central_directories"].push_back(cd_props); cd_offset += stoull(cd_props.at("header_size")); } // Parse Local Headers size_t offset = 0; for (uint64_t i = 0; i < total_entries; ++i) { auto local_props = parse_local_header(data, offset); file_properties["local_files"].push_back(local_props); offset += stoull(local_props.at("header_size")) + stoull(local_props.at("compressed_size")); if (stoi(local_props.at("general_flag")) & 0x08) { offset += 12; } } } ssize_t find_eocd(const std::vector& data) { for (ssize_t i = data.size() - 22; i >= 0; --i) { uint32_t sig; memcpy(&sig, &data[i], 4); if (sig == 0x06054b50) return i; } return -1; } void parse_eocd(const std::vector& data, size_t offset) { uint32_t sig; uint16_t disk_num, start_disk, entries_disk, total_entries, comment_len; uint32_t cd_size, cd_offset; memcpy(&sig, &data[offset], 4); memcpy(&disk_num, &data[offset + 4], 2); memcpy(&start_disk, &data[offset + 6], 2); memcpy(&entries_disk, &data[offset + 8], 2); memcpy(&total_entries, &data[offset + 10], 2); memcpy(&cd_size, &data[offset + 12], 4); memcpy(&cd_offset, &data[offset + 16], 4); memcpy(&comment_len, &data[offset + 20], 2); std::string comment(reinterpret_cast(&data[offset + 22]), comment_len); eocd["signature"] = "0x" + to_hex(sig); eocd["disk_number"] = std::to_string(disk_num); eocd["start_disk"] = std::to_string(start_disk); eocd["entries_on_disk"] = std::to_string(entries_disk); eocd["total_entries"] = std::to_string(total_entries); eocd["cd_size"] = std::to_string(cd_size); eocd["cd_offset"] = std::to_string(cd_offset); eocd["comment_length"] = std::to_string(comment_len); eocd["comment"] = comment; } void parse_zip64(const std::vector& data, size_t eocd_offset) { size_t locator_offset = eocd_offset - 20; uint32_t sig; memcpy(&sig, &data[locator_offset], 4); if (sig == 0x07064b50) { uint32_t start_disk, total_disks; uint64_t rel_offset; memcpy(&start_disk, &data[locator_offset + 4], 4); memcpy(&rel_offset, &data[locator_offset + 8], 8); memcpy(&total_disks, &data[locator_offset + 16], 4); zip64_locator["signature"] = "0x" + to_hex(sig); zip64_locator["start_disk"] = std::to_string(start_disk); zip64_locator["relative_offset"] = std::to_string(rel_offset); zip64_locator["total_disks"] = std::to_string(total_disks); size_t zip64_offset = rel_offset; uint32_t zip64_sig; memcpy(&zip64_sig, &data[zip64_offset], 4); if (zip64_sig == 0x06064b50) { uint64_t record_size; uint16_t ver_made, ver_needed; uint32_t disk_num, start_disk2; uint64_t entries_disk, total_entries, cd_size, cd_offset; memcpy(&record_size, &data[zip64_offset + 4], 8); memcpy(&ver_made, &data[zip64_offset + 12], 2); memcpy(&ver_needed, &data[zip64_offset + 14], 2); memcpy(&disk_num, &data[zip64_offset + 16], 4); memcpy(&start_disk2, &data[zip64_offset + 20], 4); memcpy(&entries_disk, &data[zip64_offset + 24], 8); memcpy(&total_entries, &data[zip64_offset + 32], 8); memcpy(&cd_size, &data[zip64_offset + 40], 8); memcpy(&cd_offset, &data[zip64_offset + 48], 8); zip64_eocd["signature"] = "0x" + to_hex(zip64_sig); zip64_eocd["record_size"] = std::to_string(record_size); zip64_eocd["version_made"] = std::to_string(ver_made); zip64_eocd["version_needed"] = std::to_string(ver_needed); zip64_eocd["disk_number"] = std::to_string(disk_num); zip64_eocd["start_disk"] = std::to_string(start_disk2); zip64_eocd["entries_on_disk"] = std::to_string(entries_disk); zip64_eocd["total_entries"] = std::to_string(total_entries); zip64_eocd["cd_size"] = std::to_string(cd_size); zip64_eocd["cd_offset"] = std::to_string(cd_offset); eocd["total_entries"] = std::to_string(total_entries); eocd["cd_size"] = std::to_string(cd_size); eocd["cd_offset"] = std::to_string(cd_offset); } } } std::map parse_local_header(const std::vector& data, size_t offset) { std::map props; uint32_t sig, crc, comp_size, uncomp_size; uint16_t ver_needed, flag, comp_method, mod_time, mod_date, fn_len, extra_len; memcpy(&sig, &data[offset], 4); memcpy(&ver_needed, &data[offset + 4], 2); memcpy(&flag, &data[offset + 6], 2); memcpy(&comp_method, &data[offset + 8], 2); memcpy(&mod_time, &data[offset + 10], 2); memcpy(&mod_date, &data[offset + 12], 2); memcpy(&crc, &data[offset + 14], 4); memcpy(&comp_size, &data[offset + 18], 4); memcpy(&uncomp_size, &data[offset + 22], 4); memcpy(&fn_len, &data[offset + 26], 2); memcpy(&extra_len, &data[offset + 28], 2); props["signature"] = "0x" + to_hex(sig); props["version_needed"] = std::to_string(ver_needed); props["general_flag"] = std::to_string(flag); props["compression_method"] = std::to_string(comp_method); props["mod_time"] = std::to_string(mod_time); props["mod_date"] = std::to_string(mod_date); props["crc32"] = std::to_string(crc); props["compressed_size"] = std::to_string(comp_size); props["uncompressed_size"] = std::to_string(uncomp_size); props["file_name_length"] = std::to_string(fn_len); props["extra_length"] = std::to_string(extra_len); offset += 30; std::string file_name(reinterpret_cast(&data[offset]), fn_len); props["file_name"] = file_name; offset += fn_len; props["extra_field"] = to_hex_string(&data[offset], extra_len); props["header_size"] = std::to_string(30 + fn_len + extra_len); // Parse ZIP64 extra if (comp_size == 0xFFFFFFFF || uncomp_size == 0xFFFFFFFF) { size_t extra_offset = 0; while (extra_offset < extra_len) { uint16_t extra_id, extra_size; memcpy(&extra_id, &data[offset + extra_offset], 2); memcpy(&extra_size, &data[offset + extra_offset + 2], 2); if (extra_id == 0x0001) { size_t data_offset = extra_offset + 4; if (uncomp_size == 0xFFFFFFFF) { uint64_t val; memcpy(&val, &data[offset + data_offset], 8); props["uncompressed_size"] = std::to_string(val); data_offset += 8; } if (comp_size == 0xFFFFFFFF) { uint64_t val; memcpy(&val, &data[offset + data_offset], 8); props["compressed_size"] = std::to_string(val); } } extra_offset += 4 + extra_size; } } return props; } std::map parse_central_header(const std::vector& data, size_t offset) { std::map props; uint32_t sig, crc, comp_size, uncomp_size, ext_attr, rel_offset; uint16_t ver_made, ver_needed, flag, comp_method, mod_time, mod_date, fn_len, extra_len, comment_len, disk_start, int_attr; memcpy(&sig, &data[offset], 4); memcpy(&ver_made, &data[offset + 4], 2); memcpy(&ver_needed, &data[offset + 6], 2); memcpy(&flag, &data[offset + 8], 2); memcpy(&comp_method, &data[offset + 10], 2); memcpy(&mod_time, &data[offset + 12], 2); memcpy(&mod_date, &data[offset + 14], 2); memcpy(&crc, &data[offset + 16], 4); memcpy(&comp_size, &data[offset + 20], 4); memcpy(&uncomp_size, &data[offset + 24], 4); memcpy(&fn_len, &data[offset + 28], 2); memcpy(&extra_len, &data[offset + 30], 2); memcpy(&comment_len, &data[offset + 32], 2); memcpy(&disk_start, &data[offset + 34], 2); memcpy(&int_attr, &data[offset + 36], 2); memcpy(&ext_attr, &data[offset + 38], 4); memcpy(&rel_offset, &data[offset + 42], 4); props["signature"] = "0x" + to_hex(sig); props["version_made"] = std::to_string(ver_made); props["version_needed"] = std::to_string(ver_needed); props["general_flag"] = std::to_string(flag); props["compression_method"] = std::to_string(comp_method); props["mod_time"] = std::to_string(mod_time); props["mod_date"] = std::to_string(mod_date); props["crc32"] = std::to_string(crc); props["compressed_size"] = std::to_string(comp_size); props["uncompressed_size"] = std::to_string(uncomp_size); props["file_name_length"] = std::to_string(fn_len); props["extra_length"] = std::to_string(extra_len); props["comment_length"] = std::to_string(comment_len); props["disk_start"] = std::to_string(disk_start); props["internal_attributes"] = std::to_string(int_attr); props["external_attributes"] = std::to_string(ext_attr); props["relative_offset"] = std::to_string(rel_offset); offset += 46; std::string file_name(reinterpret_cast(&data[offset]), fn_len); props["file_name"] = file_name; offset += fn_len; props["extra_field"] = to_hex_string(&data[offset], extra_len); offset += extra_len; std::string file_comment(reinterpret_cast(&data[offset]), comment_len); props["file_comment"] = file_comment; props["header_size"] = std::to_string(46 + fn_len + extra_len + comment_len); // Parse ZIP64 extra if (comp_size == 0xFFFFFFFF || uncomp_size == 0xFFFFFFFF || rel_offset == 0xFFFFFFFF) { size_t extra_offset = 0; size_t extra_base = offset - extra_len - comment_len; while (extra_offset < extra_len) { uint16_t extra_id, extra_size; memcpy(&extra_id, &data[extra_base + extra_offset], 2); memcpy(&extra_size, &data[extra_base + extra_offset + 2], 2); if (extra_id == 0x0001) { size_t data_offset = extra_offset + 4; if (uncomp_size == 0xFFFFFFFF) { uint64_t val; memcpy(&val, &data[extra_base + data_offset], 8); props["uncompressed_size"] = std::to_string(val); data_offset += 8; } if (comp_size == 0xFFFFFFFF) { uint64_t val; memcpy(&val, &data[extra_base + data_offset], 8); props["compressed_size"] = std::to_string(val); data_offset += 8; } if (rel_offset == 0xFFFFFFFF) { uint64_t val; memcpy(&val, &data[extra_base + data_offset], 8); props["relative_offset"] = std::to_string(val); } } extra_offset += 4 + extra_size; } } return props; } std::string to_hex(uint32_t val) { std::stringstream ss; ss << std::hex << val; return ss.str(); } std::string to_hex_string(const uint8_t* bytes, size_t len) { std::stringstream ss; for (size_t i = 0; i < len; ++i) { ss << std::hex << std::setw(2) << std::setfill('0') << static_cast(bytes[i]); } return ss.str(); } void printProperties() { std::cout << "Local Files:" << std::endl; for (size_t i = 0; i < file_properties["local_files"].size(); ++i) { std::cout << "File " << (i + 1) << ":" << std::endl; for (const auto& kv : file_properties["local_files"][i]) { std::cout << " " << kv.first << ": " << kv.second << std::endl; } } std::cout << "\nCentral Directories:" << std::endl; for (size_t i = 0; i < file_properties["central_directories"].size(); ++i) { std::cout << "Central Directory " << (i + 1) << ":" << std::endl; for (const auto& kv : file_properties["central_directories"][i]) { std::cout << " " << kv.first << ": " << kv.second << std::endl; } } if (!zip64_eocd.empty()) { std::cout << "\nZip64 EOCD:" << std::endl; for (const auto& kv : zip64_eocd) { std::cout << " " << kv.first << ": " << kv.second << std::endl; } } if (!zip64_locator.empty()) { std::cout << "\nZip64 Locator:" << std::endl; for (const auto& kv : zip64_locator) { std::cout << " " << kv.first << ": " << kv.second << std::endl; } } std::cout << "\nEOCD:" << std::endl; for (const auto& kv : eocd) { std::cout << " " << kv.first << ": " << kv.second << std::endl; } } void write(const std::string& output_path) { // Basic write: Create a new ZIP with one file std::string add_file_name = "sample.txt"; std::string add_file_content = "Hello, ZIP!"; uint32_t crc = calculate_crc32(reinterpret_cast(add_file_content.data()), add_file_content.size()); uint16_t fn_len = add_file_name.length(); std::vector local_header(30 + fn_len); uint32_t sig = 0x04034b50; memcpy(&local_header[0], &sig, 4); uint16_t ver = 10; memcpy(&local_header[4], &ver, 2); uint16_t flag = 0; memcpy(&local_header[6], &flag, 2); uint16_t method = 0; memcpy(&local_header[8], &method, 2); uint16_t time = 0; memcpy(&local_header[10], &time, 2); uint16_t date = 0; memcpy(&local_header[12], &date, 2); memcpy(&local_header[14], &crc, 4); uint32_t size = add_file_content.size(); memcpy(&local_header[18], &size, 4); memcpy(&local_header[22], &size, 4); memcpy(&local_header[26], &fn_len, 2); uint16_t extra = 0; memcpy(&local_header[28], &extra, 2); memcpy(&local_header[30], add_file_name.data(), fn_len); std::vector cd_header(46 + fn_len); sig = 0x02014b50; memcpy(&cd_header[0], &sig, 4); memcpy(&cd_header[4], &ver, 2); memcpy(&cd_header[6], &ver, 2); memcpy(&cd_header[8], &flag, 2); memcpy(&cd_header[10], &method, 2); memcpy(&cd_header[12], &time, 2); memcpy(&cd_header[14], &date, 2); memcpy(&cd_header[16], &crc, 4); memcpy(&cd_header[20], &size, 4); memcpy(&cd_header[24], &size, 4); memcpy(&cd_header[28], &fn_len, 2); memcpy(&cd_header[30], &extra, 2); uint16_t zero16 = 0; memcpy(&cd_header[32], &zero16, 2); memcpy(&cd_header[34], &zero16, 2); memcpy(&cd_header[36], &zero16, 2); uint32_t zero32 = 0; memcpy(&cd_header[38], &zero32, 4); memcpy(&cd_header[42], &zero32, 4); memcpy(&cd_header[46], add_file_name.data(), fn_len); std::vector eocd_data(22); sig = 0x06054b50; memcpy(&eocd_data[0], &sig, 4); memcpy(&eocd_data[4], &zero16, 2); memcpy(&eocd_data[6], &zero16, 2); uint16_t one = 1; memcpy(&eocd_data[8], &one, 2); memcpy(&eocd_data[10], &one, 2); uint32_t cd_size = cd_header.size(); memcpy(&eocd_data[12], &cd_size, 4); uint32_t local_end = local_header.size() + add_file_content.size(); memcpy(&eocd_data[16], &local_end, 4); memcpy(&eocd_data[20], &zero16, 2); std::ofstream out(output_path, std::ios::binary); out.write(reinterpret_cast(local_header.data()), local_header.size()); out.write(add_file_content.data(), add_file_content.size()); out.write(reinterpret_cast(cd_header.data()), cd_header.size()); out.write(reinterpret_cast(eocd_data.data()), eocd_data.size()); } uint32_t calculate_crc32(const uint8_t* data, size_t len) { uint32_t crc = 0xFFFFFFFF; for (size_t i = 0; i < len; ++i) { crc ^= data[i]; for (int j = 0; j < 8; ++j) { crc = (crc & 1) ? (crc >> 1) ^ 0xEDB88320 : crc >> 1; } } return crc ^ 0xFFFFFFFF; } }; int main() { ZipHandler handler("sample.zip"); handler.printProperties(); handler.write("modified.zip"); return 0; } // ===== end task-857 .ZIP ===== // ===== task-858 .ZRX [C] ===== #include #include #include #include #define MAX_LINE 1024 #define MAX_KEYS 50 #define MAX_COLS 20 #define MAX_DATA_ROWS 1000 // Arbitrary limit for sample typedef struct { char *filepath; char *encoding; // ISO-8859-1, but C file ops use default; assume ASCII compatible struct { char *key[MAX_KEYS]; char *value[MAX_KEYS]; int count; } header; char *columns[MAX_COLS]; int col_count; char *data[MAX_DATA_ROWS][MAX_COLS]; int data_rows; } ZRXFile; ZRXFile* zrx_create(const char *filepath) { ZRXFile *zrx = malloc(sizeof(ZRXFile)); zrx->filepath = strdup(filepath); zrx->encoding = "ISO-8859-1"; // Note: C stdio doesn't handle encoding directly zrx->header.count = 0; zrx->col_count = 0; zrx->data_rows = 0; return zrx; } void zrx_destroy(ZRXFile *zrx) { for (int i = 0; i < zrx->header.count; i++) { free(zrx->header.key[i]); free(zrx->header.value[i]); } for (int i = 0; i < zrx->col_count; i++) { free(zrx->columns[i]); } for (int i = 0; i < zrx->data_rows; i++) { for (int j = 0; j < zrx->col_count; j++) { free(zrx->data[i][j]); } } free(zrx->filepath); free(zrx); } void zrx_read(ZRXFile *zrx) { FILE *file = fopen(zrx->filepath, "r"); if (!file) return; char line[MAX_LINE]; int in_header = 1; while (fgets(line, MAX_LINE, file)) { char *trimmed = line; while (isspace(*trimmed)) trimmed++; if (strncmp(trimmed, "##", 2) == 0 || *trimmed == '\0') continue; if (*trimmed == '#') { trimmed++; char *token = strtok(trimmed, "|*| ;*;"); while (token) { char *open = strchr(token, '<'); char *close = strchr(token, '>'); if (open && close) { *open = '\0'; *close = '\0'; char *key = strdup(token); char *value = strdup(open + 1); if (strcmp(key, "LAYOUT") == 0) { char *col_token = strtok(value, "(), "); while (col_token && zrx->col_count < MAX_COLS) { zrx->columns[zrx->col_count++] = strdup(col_token); col_token = strtok(NULL, "(), "); } } else { zrx->header.key[zrx->header.count] = key; zrx->header.value[zrx->header.count++] = value; } } token = strtok(NULL, "|*| ;*;"); } } else { if (in_header) in_header = 0; if (zrx->data_rows >= MAX_DATA_ROWS) continue; char *val_token = strtok(trimmed, " \t"); int col = 0; while (val_token && col < zrx->col_count) { zrx->data[zrx->data_rows][col++] = strdup(val_token); val_token = strtok(NULL, " \t"); } if (col > 0) zrx->data_rows++; } } fclose(file); } void zrx_decode(ZRXFile *zrx) { // Decoding is parsing as per read zrx_read(zrx); } void zrx_write(ZRXFile *zrx, const char *new_filepath) { const char *path = new_filepath ? new_filepath : zrx->filepath; FILE *file = fopen(path, "w"); if (!file) return; for (int i = 0; i < zrx->header.count; i++) { fprintf(file, "#%s<%s>|*|\n", zrx->header.key[i], zrx->header.value[i]); } if (zrx->col_count > 0) { fprintf(file, "#LAYOUT("); for (int i = 0; i < zrx->col_count; i++) { fprintf(file, "%s%s", zrx->columns[i], i < zrx->col_count - 1 ? "," : ""); } fprintf(file, ")\n"); } for (int i = 0; i < zrx->data_rows; i++) { for (int j = 0; j < zrx->col_count; j++) { fprintf(file, "%s ", zrx->data[i][j]); } fprintf(file, "\n"); } fclose(file); } void zrx_print_properties(ZRXFile *zrx) { printf("Header Properties:\n"); for (int i = 0; i < zrx->header.count; i++) { printf("%s: %s\n", zrx->header.key[i], zrx->header.value[i]); } printf("\nColumns:\n"); for (int i = 0; i < zrx->col_count; i++) { printf("%s ", zrx->columns[i]); } printf("\n\nData Sample (first 5 rows):\n"); for (int i = 0; i < 5 && i < zrx->data_rows; i++) { for (int j = 0; j < zrx->col_count; j++) { printf("%s ", zrx->data[i][j]); } printf("\n"); } } // Example usage: // int main() { // ZRXFile *zrx = zrx_create("example.zrx"); // zrx_read(zrx); // zrx_print_properties(zrx); // zrx_write(zrx, "new.zrx"); // zrx_destroy(zrx); // return 0; // } // ===== end task-858 .ZRX ===== // ===== task-859 .ZS [C] ===== #include #include #include #include typedef struct { uint8_t magic[8]; uint64_t header_length; uint64_t root_index_offset; uint64_t root_index_length; uint64_t total_file_length; uint8_t sha256[32]; char codec[17]; uint64_t metadata_length; char *metadata; uint64_t header_crc; // Blocks omitted } ZSHeader; typedef struct { char *filename; ZSHeader header; // Additional fields for blocks } ZSFile; void init_zsfile(ZSFile *zs, const char *filename) { zs->filename = strdup(filename); // Initialize other fields to 0/NULL } void read_zsfile(ZSFile *zs) { FILE *f = fopen(zs->filename, "rb"); if (!f) { perror("Failed to open file"); exit(1); } fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *data = malloc(size); fread(data, 1, size, f); fclose(f); // Parse magic memcpy(zs->header.magic, data, 8); if (memcmp(zs->header.magic, "\xab\x5a\x53\x66\x69\x4c\x65\x01", 8) != 0 && memcmp(zs->header.magic, "\xab\x5a\x53\x74\x6f\x42\x65\x01", 8) != 0) { fprintf(stderr, "Invalid magic number\n"); exit(1); } uint64_t *u64data = (uint64_t *)(data + 8); zs->header.header_length = u64data[0]; zs->header.root_index_offset = u64data[1]; zs->header.root_index_length = u64data[2]; zs->header.total_file_length = u64data[3]; memcpy(zs->header.sha256, data + 8 + 32, 32); memcpy(zs->header.codec, data + 8 + 32 + 32, 16); zs->header.codec[16] = '\0'; zs->header.metadata_length = u64data[7]; zs->header.metadata = malloc(zs->header.metadata_length + 1); memcpy(zs->header.metadata, data + 8 + 32 + 32 + 16 + 8, zs->header.metadata_length); zs->header.metadata[zs->header.metadata_length] = '\0'; uint64_t header_end = 8 + zs->header.header_length; zs->header.header_crc = *(uint64_t *)(data + header_end); free(data); } void print_properties(const ZSFile *zs) { printf("ZS File Properties:\n"); printf("Magic: "); for (int i = 0; i < 8; i++) printf("%02x ", zs->header.magic[i]); printf("\n"); printf("Header length: %llu\n", zs->header.header_length); printf("Root index offset: %llu\n", zs->header.root_index_offset); printf("Root index length: %llu\n", zs->header.root_index_length); printf("Total file length: %llu\n", zs->header.total_file_length); printf("SHA-256: "); for (int i = 0; i < 32; i++) printf("%02x", zs->header.sha256[i]); printf("\n"); printf("Codec: %s\n", zs->header.codec); printf("Metadata length: %llu\n", zs->header.metadata_length); printf("Metadata: %s\n", zs->header.metadata); printf("Header CRC: %llu\n", zs->header.header_crc); } void free_zsfile(ZSFile *zs) { free(zs->filename); free(zs->header.metadata); } void write_zsfile(const ZSFile *zs, const uint8_t **records, int num_records, const char *metadata) { // Simplified write; full implementation required. } // Example usage: // int main() { // ZSFile zs; // init_zsfile(&zs, "example.zs"); // read_zsfile(&zs); // print_properties(&zs); // free_zsfile(&zs); // return 0; // } // ===== end task-859 .ZS ===== // ===== task-860 .ZST [C++] ===== #include #include #include #include #include #include class ZstFileHandler { private: std::string filepath; std::map>> properties; // Simplified structure public: ZstFileHandler(const std::string& fp) : filepath(fp) {} void readAndDecode() { std::ifstream file(filepath, std::ios::binary); if (!file) throw std::runtime_error("Cannot open file"); file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0); std::vector data(size); file.read(reinterpret_cast(data.data()), size); size_t pos = 0; std::vector> frames; while (pos < size) { uint32_t magic; std::memcpy(&magic, data.data() + pos, 4); pos += 4; if (magic == 0xFD2FB528) { std::map frame; frame["type"] = "Zstandard"; uint8_t fhd = data[pos++]; uint8_t fcsFlag = (fhd >> 6) & 0x03; uint8_t singleSeg = (fhd >> 5) & 0x01; uint8_t checksumFlag = (fhd >> 2) & 0x01; uint8_t dictFlag = fhd & 0x03; frame["FCS_Flag"] = std::to_string(fcsFlag); frame["Single_Segment"] = std::to_string(singleSeg); frame["Checksum_Flag"] = std::to_string(checksumFlag); frame["Dict_Flag"] = std::to_string(dictFlag); uint64_t windowSize = 0; if (!singleSeg) { uint8_t wd = data[pos++]; uint8_t exp = (wd >> 3) & 0x1F; uint8_t mant = wd & 0x07; windowSize = (1ULL << (10 + exp)) + (mant * (1ULL << (10 + exp)) / 8); frame["Window_Exponent"] = std::to_string(exp); frame["Window_Mantissa"] = std::to_string(mant); frame["Window_Size"] = std::to_string(windowSize); } uint64_t dictId = 0; if (dictFlag) { std::memcpy(&dictId, data.data() + pos, [0,1,2,4][dictFlag]); pos += [0,1,2,4][dictFlag]; frame["Dictionary_ID"] = std::to_string(dictId); } uint64_t contentSize = 0; if (fcsFlag) { size_t fcsSize = [0,1,2,4,8][fcsFlag > 2 ? 3 : fcsFlag]; std::memcpy(&contentSize, data.data() + pos, fcsSize); if (fcsSize == 2) contentSize += 256; pos += fcsSize; frame["Frame_Content_Size"] = std::to_string(contentSize); } if (singleSeg) windowSize = contentSize; frame["Data_Blocks"] = "Blocks: "; // Stub for blocks bool lastBlock = false; while (!lastBlock && pos < size) { uint32_t bh = 0; std::memcpy(&bh, data.data() + pos, 3); pos += 3; lastBlock = bh & 0x01; uint8_t blockType = (bh >> 1) & 0x03; uint32_t blockSize = bh >> 3; frame["Data_Blocks"] += "Last=" + std::to_string(lastBlock) + ", Type=" + std::string({"Raw","RLE","Compressed","Reserved"}[blockType]) + ", Size=" + std::to_string(blockSize) + "; "; if (blockType == 2) { frame["Data_Blocks"] += "(Compressed stub); "; } pos += blockSize; } if (checksumFlag) { uint32_t checksum; std::memcpy(&checksum, data.data() + pos, 4); pos += 4; frame["Content_Checksum"] = std::to_string(checksum); } frames.push_back(frame); } else if (magic >= 0x184D2A50 && magic <= 0x184D2A5F) { std::map frame; frame["type"] = "Skippable"; uint32_t frameSize; std::memcpy(&frameSize, data.data() + pos, 4); pos += 4; frame["Magic_Number"] = std::to_string(magic); frame["Frame_Size"] = std::to_string(frameSize); frame["User_Data"] = "Skipped - arbitrary data"; pos += frameSize; frames.push_back(frame); } else { throw std::runtime_error("Invalid frame magic number"); } } properties["frames"] = frames; } void printProperties() { std::cout << "Zstandard (.zst) File Properties:" << std::endl; for (const auto& frame : properties["frames"]) { std::cout << "\n" << frame.at("type") << " Frame:" << std::endl; for (const auto& [key, value] : frame) { if (key != "type") { std::cout << " " << key << ": " << value << std::endl; } } } } void writeSimpleFrame(const std::string& outputPath, const std::vector& rawData = { 'H','e','l','l','o',',',' ','Z','s','t','a','n','d','a','r','d','!' }) { // Writes a simple single raw block frame std::ofstream file(outputPath, std::ios::binary); uint32_t magic = 0xFD2FB528; file.write(reinterpret_cast(&magic), 4); uint8_t fhd = 0x20; file.write(reinterpret_cast(&fhd), 1); uint16_t contentSize = rawData.size() - 256; file.write(reinterpret_cast(&contentSize), 2); uint32_t bh = (1 << 0) | (0 << 1) | (static_cast(rawData.size()) << 3); file.write(reinterpret_cast(&bh), 3); file.write(reinterpret_cast(rawData.data()), rawData.size()); } }; // Example usage: // int main() { // ZstFileHandler handler("example.zst"); // handler.readAndDecode(); // handler.printProperties(); // handler.writeSimpleFrame("output.zst"); // return 0; // } // ===== end task-860 .ZST =====