Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define INPUT_FILE "be.txt"
- #define OUTPUT_FILE "ki.txt"
- #define MAX_WORD_SIZE 200
- char *encode(const char *str, const int *key, int cols);
- char *decode(const char *str, const int *key, int cols);
- int main() {
- FILE *in = fopen(INPUT_FILE, "r");
- int func, cols;
- fscanf(in, "%d %d", &func, &cols);
- int key[10];
- int i;
- for (i = 0; i < cols; i++) {
- fscanf(in, "%d", &key[i]);
- }
- char *str = (char *) malloc(sizeof(char) * MAX_WORD_SIZE + 1);
- fscanf(in, "%s", str);
- if (func == 1) {
- str = encode(str, key, cols);
- } else {
- str = decode(str, key, cols);
- }
- FILE *out = fopen(OUTPUT_FILE, "w");
- fprintf(out, "%s\n", str);
- fclose(out);
- }
- char *encode(const char *str, const int *key, int cols) {
- int rows = strlen(str) / cols;
- char **table = (char **) malloc(sizeof(char *) * rows);
- int i, j;
- for (i = 0; i < rows; i++) {
- table[i] = (char *) malloc(sizeof(char) * cols);
- for (j = 0; j < cols; j++) {
- table[i][j] = str[i * cols + j];
- }
- }
- char *coded = (char *) malloc(sizeof(char) * strlen(str) + 1);
- for (i = 0; i < cols; i++) {
- for (j = 0; j < rows; j++) {
- coded[i * rows + j] = table[j][key[i] - 1];
- }
- }
- coded[strlen(str)] = '\0';
- return coded;
- }
- char *decode(const char *str, const int *key, int cols) {
- int rows = strlen(str) / cols;
- char **table = (char **) malloc(sizeof(char *) * cols);
- int i, j;
- for (i = 0; i < cols; i++) {
- table[key[i]] = (char *) malloc(sizeof(char) * rows + 1);
- for (j = 0; j < rows; j++) {
- table[key[i]][j] = str[i * rows + j];
- }
- }
- char *decoded = (char *) malloc(sizeof(char) * strlen(str) + 1);
- for (j = 0; j < rows; j++) {
- for (i = 1; i <= cols; i++) {
- decoded[j * cols + i - 1] = table[i][j];
- }
- }
- decoded[strlen(str)] = '\0';
- return decoded;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement