C語言字符替換

函數 ReadDat()實現從文件 ENG.IN 中讀取一篇英文文章,存入到字符串數組 xx 中;請編制函數 encryptChar(),按給定的替代關係對數組 xx 中的所有字符進行替代,仍存入數組 xx 的對應的位置上,後調用函數 WriteDat()把結果 xx 輸出到文件 PS1.DAT 中。

替代關係:f(p)=p*11 mod 256(p 是數組中某一個字符的 ASCII 值,f(p)是計算後新字 符的 ASCII 值),如果計算後 f(p)值小於等於 32 或大於 130,則該字符不變,否則將 f(p)所對應的字符進行替代。(注意中間變量用無符號整型),原始數據文件存放的格式是:每行的寬度均小於 80 個字符。
#include <stdio.h>

#include <string.h>

#include <conio.h>

#include <ctype.h>

unsigned char xx[50][80];

int maxline=0;/文章的總行數/

int ReadDat(void);

void WriteDat(void);

void encryptChar()

{

int i,j;

for(i=0;i<maxline;i++)

for(j=0;j<strlen(xx[i]);j++)

if(xx[i][j]*11%256<=32||xx[i][j]*11%256>130) continue;

else xx[i][j]=xx[i][j]*11%256;

}

void main()

{

clrscr();

if(ReadDat()){ printf(“數據文件 ENG.IN 不能打開!\n\007”);

return;

}

encryptChar();

WriteDat();

}

int ReadDat(void)

{

FILE *fp;

int i=0;

unsigned char *p;

if((fp=fopen(“eng.in”,“r”))==NULL) return 1;

while(fgets(xx[i],80,fp)!=NULL){

p=strchr(xx[i],’\n’);

if§*p=0; i++; } maxline=i;

fclose(fp); return 0;

}

void WriteDat(void)

{

FILE *fp;

int i;

fp=fopen(“ps1.dat”,“w”);

for(i=0;i<maxline;i++){

printf("%s\n",xx[i]);

fprintf(fp,"%s\n",xx[i]);

}

fclose(fp);

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章