编码文本和文件写入读取错误

时间:2014-10-08 17:14:31

标签: c if-statement encryption file-io

我想编写从in.txt读取的简单加密文本系统,然后写入out.txt 加密类型是每个ascii加五,如果char btw u和z,u = a,v = b,......,z = f哪里是我的问题? 此外,我们可以使用模运算符(%)代替(char-20)如果char btw u和z,u = a,v = b,......,z = f哪里是我的问题? 我的代码在下面谢谢你们所有赞赏的答案。 text在in.txt中测试abcde

#include <stdio.h>


int main(){

        char ch;
        int st;

        FILE *fptr_in;
        FILE *fptr_out;

        fptr_in=fopen("in.txt","r");
        fptr_out=fopen("out.txt","w");
        if(fptr_in== NULL || fptr_out==NULL)
                    printf("File cannot be opened\n");
        else{
            st=(fscanf(fptr_in,"%c",&ch));
                while(st==1){
           /* for(st=(fscanf(fptr_in,"%c",&ch));
                st==1;
                st=(fscanf(fptr_in,"%c",&ch)))*/

                        st=(fscanf(fptr_in,"%c",&ch));

            if('a'<=ch && ch<='z'){
                fscanf(fptr_in,"%c",&ch);
            if(ch==' ')
                fprintf(fptr_out, "%c", ' ');
            else if('u'<=ch && ch<='z')
                fprintf(fptr_out, "%c", (char)((int)ch-20));
            else
            fprintf(fptr_out, "%c", (char)((int)ch+5));
            }
    }

}
        fclose(fptr_in);
            fclose(fptr_out);

        return 0;
}

1 个答案:

答案 0 :(得分:0)

对您的代码的一些评论:

  • 调用fopen后检查文件指针是件好事,但如果无法打开它们,则应该退出程序。否则,输入while循环并在空指针上调用fscan。您可以使用exit(1)中的<stdlib.h>。 (这几乎就像从main返回1,但可以从任何地方调用。)
  • fscanf(f, "%c", &ch)最好呈现为ch = getc(f)。同样,fprintf(f, "%c", ch)可以更简洁地写为putc(ch, f)。 (在我看来,你的变体不是很糟糕,但不必刻意罗嗦。)
  • 你的密码有三种情况:空格,字母u到z,以及其他一切。这意味着您还可以移动标点符号和特殊字符,如换行符。您可能应该使用大写字母,小写字母和其他所有三种情况。

下面是一个有效的实施方案。注意事项:

  • 我使用getc,这需要ch为int。
  • in.txt 中读取字符是在for(;;)的无限循环中完成的。读取break时,循环以EOF语句结束。 (Ii通常更好地拥有具有适当条件的循环,但在这种情况下我更喜欢break,因为它允许我在此循环中使ch本地化,并且在条件中也不需要赋值,我觉得很难看。
  • Caesar密码是作为一个单独的函数实现的,传递到该函数。它使用您建议的模数函数对大写和小写字母进行编码。这需要一个积极的转变。
  • 请注意,I / O循环和密码功能都非常短,这很不错。

以下是示例:

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

#define INFILE "in.txt"
#define OUTFILE "out.txt"

int caesar(int ch, int shift)
{
    while (shift < 0) shift += 26;
    if ('a' <= ch && ch <= 'z') return ('a' + (ch - 'a' + shift) % 26);
    if ('A' <= ch && ch <= 'Z') return ('A' + (ch - 'A' + shift) % 26);
    return ch;
}

int main()
{
    FILE *fptr_in;
    FILE *fptr_out;

    fptr_in = fopen(INFILE, "r");
    if (fptr_in == NULL) {
        fprintf(stderr, "Can't open %s.\n", INFILE);
        exit(1);
    }

    fptr_out = fopen(OUTFILE, "w");
    if (fptr_in == NULL) {
        fprintf(stderr, "Can't create %s.\n", OUTFILE);
        exit(1);
    }

    for (;;) {
        int ch = getc(fptr_in);

        if (ch == EOF) break;
        putc(caesar(ch, 5), fptr_out);
    }

    fclose(fptr_in);
    fclose(fptr_out);

    return 0;
}
相关问题