0

我正在学习用C编程,现在我的作业是这样的。我应该能够获取带有单词/字母的文本文件,并且我的程序应该打印它得到的字母的 ascii 代码+1。它正在“编码”它。例如,字母“A”将打印为 066。所以我的问题是程序还需要能够将这些 ascii 代码解码回字母,但我不知道如何让我的程序读取 3 个数字一次。我用了

c = fgetc(pF);  
while (c != EOF) {  
fprintf(pF2,"%03i",c+1); 
c = fgetc(pF);  

一次读取一个字符的文件。我应该使用类似的东西来获得我需要的 3 个数字,还是完全不同的东西?

#include "stdio.h"
#include "stdlib.h"

int encode(){
char * fName = "testR.txt";
char * fName2="testW.txt";
FILE * pF;
FILE * pF2;
char c, cArray[500];
int i=0;

pF = fopen(fName, "r");
if ( pF == NULL ) {
    printf("Error: The specified file could not be opened.\n");
    return -1;
}
pF2 = fopen(fName2, "w");

c = fgetc(pF);
while (c != EOF) {
fprintf(pF2,"%03i",c+1);
    c = fgetc(pF);
}
fclose(pF); 
fclose(pF2);
return;
}

char decode(){
char * fName = "testW.txt";
char * fName2="testW2.txt";
char * buf;
FILE * pF;
FILE * pF2;
char  cArray[500];
char buffer[4];
     buffer[3] = '\0';

pF = fopen(fName, "r");
if ( pF == NULL ) {
    printf("Error: The specified file could not be opened.\n");
    return -1;
}
pF2 = fopen(fName2, "w");
while (fread(buffer, 3, 1, stdin)){
putchar((atoi(buffer)-1) & 0xFF);
}
fclose(pF); 
fclose(pF2);
}

int main (int argc, char *argv[]){
char c;

if ( argc != 2 ) { 
  printf("Incorrect number of arguments.\n"); 
  exit(-1); 
} 

if (strcmp(argv[1], "-e") == 0){
   encode();
   }
if (strcmp(argv[1], "-d") == 0){
   decode();
   }
return 0;
}

我知道我的代码是一团糟,而且我一直在尝试进行的所有更改可能不应该存在= [

4

2 回答 2

3

编码:

int c;

while ((c = getchar()) != EOF)
    printf("%.3d", (c+1)&0xFF);

解码:

char buffer[4];
buffer[3] = '\0';

while (fread(buffer, 3, 1, stdin))
    putchar((atoi(buffer)-1) & 0xFF);

从技术上讲,如果在编码时输出不以换行符结尾,则输出不是文本文件。输入没有错误检查。fread()读取三个字符时将返回 1 ;否则,它将返回 0。

工作计划

e3.c — 加密

#include <stdio.h>

int main(void)
{
    int c;

    while ((c = getchar()) != EOF)
        printf("%.3d", (c+1)&0xFF);
    return 0;
}

d3.c — 解密

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

int main(void)
{
    char buffer[4];
    buffer[3] = '\0';

    while (fread(buffer, 3, 1, stdin))
        putchar((atoi(buffer)-1) & 0xFF);
    return 0;
}

样本输出

$ e3 < e3.c
036106111100109118101102033061116117101106112047105063011011106111117033110098106111041119112106101042011124011033033033033106111117033100060011011033033033033120105106109102033041041100033062033104102117100105098115041042042033034062033070080071042011033033033033033033033033113115106111117103041035038047052101035045033041100044050042039049121071071042060011033033033033115102117118115111033049060011126011011$
$

行尾的美元是提示符。

$ e3 <e3.c | d3
#include <stdio.h>

int main(void)
{
    int c;

    while ((c = getchar()) != EOF)
        printf("%.3d", (c+1)&0xFF);
    return 0;
}

$ e3 <e3.c | d3 | diff e3.c -
$

编码和解码的基本往返表明代码有效。

于 2013-11-30T03:03:14.423 回答
1
while (fread(buf, 1, 3, pF) == 3) 
{
  ...
}
于 2013-11-30T02:45:29.937 回答