我正在学习用C语言编程,现在我的作业就是这样。我应该能够使用单词/字母来获取文本文件,我的程序应该打印ascii代码+它获得的1个字母。它正在“编码”它。所以例如字母“A”将打印为066.所以我的问题是程序还需要能够将那些ascii代码解码回字母,但我不知道如何让我的程序读取3个数字at一旦。我用了
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;
}
我知道我的代码是乱七八糟的,而且我可能要做的所有改变都可能不存在的事情= [
答案 0 :(得分: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。
#include <stdio.h>
int main(void)
{
int c;
while ((c = getchar()) != EOF)
printf("%.3d", (c+1)&0xFF);
return 0;
}
#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 -
$
编码和解码的基本往返显示代码可以正常工作。
答案 1 :(得分:1)
while (fread(buf, 1, 3, pF) == 3)
{
...
}