簡體   English   中英

c:如何從文件中讀取並將值保存到另一個文件凱撒密碼程序?

[英]c: How can I read from a file and save value to another file caeser cipher program?

這是我的問題:

凱撒密碼技術是最早和最簡單的加密技術之一。 它只是一種替換密碼,即給定文本的每個字母都被字母表中一些固定位置的字母替換。 例如,移位為 1,A 將替換為 B,B 將變為 C,依此類推。 該方法顯然是以朱利葉斯凱撒命名的,他顯然用它來與他的官員交流。 因此,要加密給定的文本,我們需要一個 integer 值,稱為移位,表示文本的每個字母已被向下移動的 position 的數量。 加密可以使用模算術表示,首先將字母轉換為數字,根據該方案,A = 0,B = 1,...,Z = 25。通過移位 n 對字母的加密可以在數學上描述為。

 E_n(x)=(x+n)mod\ 26 (Encryption Phase with shift n) D_n(x)=(xn)mod\ 26 (Decryption Phase with shift n)

在 c 中編寫一個算法並執行一個程序,從一個文件(稱為“test.txt”)中讀取數據,根據討論轉換數據,然后將其保存在另一個文件中(稱為“final.txt”)

這是我的代碼,但我不知道該怎么做

#include <stdio.h>
#include <stdlib.h>

char data[50], temp; int key, count;

void
getmessage()
{
    // printf("Enter a String:\t");
    // scanf("%[^\n]s", data);

    FILE *file_pointer;
    char buffer[30], c;

    file_pointer = fopen("test.txt", "r");
    printf("----reading the file----\n");
    fgets(buffer, 50, file_pointer);
    data[50] = buffer;
    printf("%s\n", buffer);

#if 0
    printf("----read and parse data----\n");
    file_pointer = fopen("test.txt", "r");  // reset the pointer
    char str1[10], str2[2], str3[20], str4[2];

    fscanf(file_pointer, "%s %s %s %s", str1, str2, str3, str4);
    printf("Read String1 |%s|\n", str1);
    printf("Read String2 |%s|\n", str2);
    printf("Read String3 |%s|\n", str3);
    printf("Read String4 |%s|\n", str4);
#endif

}

void
key_input()
{
    printf("Enter a Key:\t");
    scanf("%d", &key);
}

void
caesar_cipher_encryption()
{
    for (count = 0; data[count] != '\0'; count++) {
        temp = data[count];
        if (temp >= 'a' && temp <= 'z') {
            temp = temp + key;
            if (temp > 'z') {
                temp = temp - 'z' + 'a' - 1;
            }
            data[count] = temp;
        }
        else if (temp >= 'A' && temp <= 'Z') {
            temp = temp + key;
            if (temp > 'Z') {
                temp = temp - 'Z' + 'A' - 1;
            }
            data[count] = temp;
        }
    }
    printf("\nEncrypted Message:\t%s\n", data);
}

void
caesar_cipher_decryption()
{
    for (count = 0; data[count] != '\0'; count++) {
        temp = data[count];
        if (temp >= 'a' && temp <= 'z') {
            temp = temp - key;
            if (temp < 'a') {
                temp = temp + 'z' - 'a' + 1;
            }
            data[count] = temp;
        }
        else if (temp >= 'A' && temp <= 'Z') {
            temp = temp - key;
            if (temp < 'A') {
                temp = temp + 'Z' - 'A' + 1;
            }
            data[count] = temp;
        }
    }
    printf("\nDecrypted Message:\t%s\n", data);
}

int
main()
{
    int choice;

    getmessage();
    key_input();
    while (1) {
        printf("\n1. Encryption\n2. Decryption\n3. Exit\n");
        printf("\nEnter You Choice:\t");
        scanf("%d", &choice);
        switch (choice) {
        case 1:
            caesar_cipher_encryption();
            break;
        case 2:
            caesar_cipher_decryption();
            break;
        case 3:
            exit(0);
        default:
            printf("\nPlease select a correct option:\n");
        }
    }
    printf("\n");
    return 0;
}

您在get_message中輸入的數據字符串錯誤:

  1. 它具有 UB (未定義的行為),因為它寫入了buffer的末尾。
  2. 此外, buffer永遠不會復制到 [全局變量] data ,因此data總是有垃圾。
  3. 最好直接輸入data [並消除buffer ]。 這似乎沒問題,因為其他函數使用全局data
  4. 我們應該增加緩沖區的大小以允許更長的短語

加密和解密函數都根據字符是大寫還是小寫來復制代碼。 我們應該創建兩個函數來集中轉換(將限制作為參數傳遞)。

實際的加密/描述算法不匹配 [AFAICT during testing]。

這是一些重構的代碼。 它帶有注釋,我使用cpp條件來顯示舊代碼和新代碼:

#if 0
// old code
#else
// new code
#endif

#if 1
// new code
#endif

請注意,此代碼可以進一步清理,但我不想進一步了解現有代碼(例如更改函數以接受緩沖區指針作為參數等):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// NOTE/BUG: data must be [at least] the same size as buffer in getmessage
// NOTE/BUG: temp should be function scoped
#if 0
char data[50], temp;
#else
#define BUFMAX      1000
char data[BUFMAX];
#endif
int key, count;

void
getmessage()
{
    // printf("Enter a String:\t");
    // scanf("%[^\n]s", data);

    FILE *file_pointer;
// NOTE/BUG: the buffer is local and we can input directly into temp
#if 0
    char buffer[30], c;
#endif

// NOTE/BUG: there is no corresponding fclose for this
    file_pointer = fopen("test.txt", "r");

    printf("----reading the file----\n");

// NOTE/BUG: this causes UB (undefined behavior) because we store past the
// end of buffer
// NOTE/BUG: buffer never gets into data
// NOTE/BUG: newline is not stripped properly
#if 0
    fgets(buffer, 50, file_pointer);
    data[50] = buffer;
    printf("%s\n", buffer);
// NOTE/FIX: we can input directly into data
#else
    if (file_pointer == NULL) {
        perror("test.txt");
        exit(1);
    }
    fgets(data, sizeof(data), file_pointer);
    data[strcspn(data,"\n")] = 0;
    fclose(file_pointer);
    printf("%s\n", data);
#endif

#if 0
    printf("----read and parse data----\n");
    file_pointer = fopen("test.txt", "r");  // reset the pointer
    char str1[10], str2[2], str3[20], str4[2];

    fscanf(file_pointer, "%s %s %s %s", str1, str2, str3, str4);
    printf("Read String1 |%s|\n", str1);
    printf("Read String2 |%s|\n", str2);
    printf("Read String3 |%s|\n", str3);
    printf("Read String4 |%s|\n", str4);
#endif

}

void
key_input()
{
    printf("Enter a Key:\t");
    scanf("%d", &key);
}

int
encrypt(int chr,int lo,int hi)
{

    if ((chr >= lo) && (chr <= hi)) {
        chr += key;
        if (chr > hi) {
            chr -= hi;
            chr += lo;
            chr -= 1;
        }
    }
    else
        chr = 0;

    return chr;
}

int
decrypt(int chr,int lo,int hi)
{

    if ((chr >= lo) && (chr <= hi)) {
        chr -= key;
        if (chr < lo) {
            chr = chr - lo;
            chr += hi;
            chr += 1;
        }
    }
    else
        chr = 0;

    return chr;
}

void
caesar_cipher_encryption()
{
    int temp;
    int code;

    for (count = 0; data[count] != '\0'; count++) {
        temp = data[count];

        code = encrypt(temp,'a','z');
        if (code) {
            data[count] = code;
            continue;
        }

        code = encrypt(temp,'A','Z');
        if (code) {
            data[count] = code;
            continue;
        }
    }

    printf("\nEncrypted Message:\t%s\n", data);
}

void
caesar_cipher_decryption()
{
    int temp;
    int code;

    for (count = 0; data[count] != '\0'; count++) {
        temp = data[count];

        code = decrypt(temp,'a','z');
        if (code) {
            data[count] = code;
            continue;
        }

        code = decrypt(temp,'A','Z');
        if (code) {
            data[count] = code;
            continue;
        }
    }

    printf("\nDecrypted Message:\t%s\n", data);
}

int
main()
{
    int choice;

    getmessage();
    key_input();
    while (1) {
        printf("\n1. Encryption\n2. Decryption\n3. Exit\n");
        printf("\nEnter You Choice:\t");
        scanf("%d", &choice);
        switch (choice) {
        case 1:
            caesar_cipher_encryption();
            break;
        case 2:
            caesar_cipher_decryption();
            break;
        case 3:
            exit(0);
        default:
            printf("\nPlease select a correct option:\n");
        }
    }
    printf("\n");
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM