ホームに戻る
文字列置換
#include <stdio.h>
/*
* 使用例
* chtxt before.txt after.txt "<" &lt;
*/
/* ヌル文字を除くヌル文字までのバイト数を返す */
int length(char *s){
int count = 0;
for(;;){
if(s[count] == '\0'){
return count;
}
count++;
}
}
/* FILE *fp の現在の位置からの文字列が s と等しければ 1 を返す 違えば 0 */
/* 注:文字列が等しい場合探索後の位置を戻さない 違う場合位置を戻す */
int filecmp(FILE *fp, char *s){
int c, i, l;
fpos_t pos;
fgetpos(fp, &pos);
l = length(s);
for(i = 0; i < l; i++){
c = fgetc(fp);
if(c != s[i]){
fsetpos(fp, &pos);
return 0;
}
}
return 1;
}
/* FILE *bfp に含まれる文字 before_word を after_word に変えて FILE *afp へ*/
int chenge_text(FILE *bfp, FILE *afp, char *before_word, char *after_word){
int c, i, l;
l = length(after_word);
for(;;){
if((filecmp(bfp, before_word)) == 1){
for(i = 0; i < l; i++){
c = after_word[i];
fputc(c, afp);
}
continue;
}
else{
if((c = fgetc(bfp)) == EOF){
break;
}
fputc(c, afp);
}
}
return 1;
}
int main(int argc, char *argv[]){
FILE *ifp, *ofp;
if(argc != 5){
printf("usage:chtxt before_file after_file before_word after_word\n");
return -1;
}
if((ifp = fopen(argv[1], "r")) == NULL){
printf("before_file is not found.\n");
return -1;
}
if((ofp = fopen(argv[2], "w")) == NULL){
printf("after_file is not found.\n");
return -1;
}
chenge_text(ifp, ofp, argv[3], argv[4]);
fclose(ifp);
fclose(ofp);
return 0;
}