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
- int read_error() {
- fprintf(stderr, "Read error!\n");
- return -2;
- }
- 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");
- if (!in) {
- fprintf(stderr, "Can't read \"%s\"!\n", INPUT_FILE);
- return -1;
- }
- int func, cols;
- if (fscanf(in, "%d %d", &func, &cols) != 2) return read_error();
- int key[10];
- size_t i;
- for (i = 0; i < cols; i++) {
- if (fscanf(in, "%d", &key[i]) != 1) return read_error();
- }
- char *str = (char *) malloc(sizeof(char) * MAX_WORD_SIZE + 1);
- if (fscanf(in, "%s", str) != 1) return read_error();
- if (func == 1) {
- str = encode(str, key, cols);
- } else {
- str = decode(str, key, cols);
- }
- FILE *out = fopen(OUTPUT_FILE, "w");
- if (!out) {
- fprintf(stderr, "Can't write \"%s\"!\n", OUTPUT_FILE);
- return -3;
- }
- 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);
- size_t i, j;
- for (i = 0; i < rows; i++) {
- table[i] = (char *) malloc(sizeof(char) * cols);
- for (j = 0; j < cols; j++) {
- // printf("%c ", str[i * cols + j]);
- table[i][j] = str[i * cols + j];
- }
- // printf("\n");
- }
- char *coded = (char *) malloc(sizeof(char) * strlen(str) + 1);
- for (i = 0; i < cols; i++) {
- // printf("Key: %d\n", key[i]);
- for (j = 0; j < rows; j++) {
- // printf("%d %d %d %c\n", i, j, i * rows + j, table[j][key[i] - 1]);
- coded[i * rows + j] = table[j][key[i] - 1];
- }
- }
- coded[strlen(str)] = '\0';
- //printf("coded: '%s'\n", coded);
- return coded;
- }
- char *decode(const char *str, const int *key, int cols) {
- int rows = strlen(str) / cols;
- char **table = (char **) malloc(sizeof(char *) * cols);
- size_t i, j;
- for (i = 0; i < cols; i++) {
- table[key[i]] = (char *) malloc(sizeof(char) * rows + 1);
- for (j = 0; j < rows; j++) {
- // printf("%d %d %d\n", i, j, key[i]);
- table[key[i]][j] = str[i * rows + j];
- // printf("%c ", table[key[i]][j]);
- }
- // printf("\n");
- }
- 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