gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:43:35 24 4
gpt4 key购买 nike

因此,我一直在尝试编写一种转置算法,其中每个字符的位置都会移动到文件中的新位置。例如,如果键是 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;
}

最佳答案

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

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

关于c - 如何使这个转置算法读取整个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20211848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com