如何使这个转置算法读取整个文本文件

时间:2013-11-26 08:27:00

标签: c algorithm encryption

所以我一直在尝试编写一个转置算法,其中每个字符的位置都转移到文件中的新位置。例如,如果键为3且字符数组为

"This program is supposed to encrypt a file."
加密后

输出

"Tsrr  ps  cpai.h oaispetert lipgmsuodony fe"

问题是,在加密文件的第一行之后,它会停止并且不会继续加密整个文件。编译后,它可以像这样执行

./executable -e 3 inputfile outputfile

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 200

int main ( int argc, char* argv[ ] ) {
    int pos = 0;
    char characters[ BUFFER_SIZE ];
    int index, k, size, key;
    char* echars;
    FILE* input;
    FILE* output;


    if ( argc == 5 ) {

        // exits if key is lower than 1
        key = atoi ( argv[ 2 ] );
        if ( key < 1 ) {
            perror ( "Error: This value cannot be used as a key" );
            exit ( EXIT_FAILURE );
        }

        input = fopen ( argv[ 3 ], "r" );

        //Shows error if there's no file
        if ( input == NULL ) {
            perror ( "Error, File doesn't exits" );
            exit ( EXIT_FAILURE );
        }
        output = fopen ( argv[ 4 ], "w" );
        fgets (characters, BUFFER_SIZE, input);
        fseek (input, 0, SEEK_END);
        size = ftell ( input );
        echars = ( char* ) malloc ( size );




        if ( strcmp ( argv[ 1 ], "-e" ) == 0 ) {
        while (strlen(characters) && characters[strlen(characters)-1] == '\n'){
         characters[strlen(characters)-1] = '\0';
            for (index = 0; index < key; index++) {
                for (k = index; k < strlen( characters ); k += key)
                     echars[ pos++ ] = characters[ k ];
            }
            printf("Successfuly encrypted\n");
            }

        } else if( strcmp ( argv[ 1 ], "-d" ) == 0 ) {
            for (index = 0; index < key; index++) {
                for (k = index; k < strlen( characters ); k += key)
                     echars[ k ] = characters[ pos++ ];
            }
            printf("Successfuly decrypted\n");
        }

        fputs( echars, output );
        fclose ( input );
        fclose ( output );
    } else {
        perror("Too few arguments, something went wrong\n");
        printf("Usage: ./program -e (encrypts) or -d (decripts) 3 (key) inputfile destinationfile\n");
        printf("Example:'./exectutable -e 3 inputfile.txt outputfile.txt\n");
        exit ( EXIT_FAILURE );
    }


    return 0;
}

1 个答案:

答案 0 :(得分:0)

fgets在遇到换行符时停止阅读。

您需要在其周围放置一个循环或使用可以读取更大块的读取操作。