とするようなコードです。また、削除するのはjapanからkoreaの間の文字列のみで、koreaからjapanの間の文字列は削除しません。またjapanとkoreaの文字列は交互に並んでいるとします。
このような処理をするコードで、japanとkoreaの文字列が一つずつしかないような時にしか対応できないコードは作ることができました。しかし複数マッチに対応するコードがどうもうまくいきません。今のところ下のようなコードになっているのですが、output.txtに出力される内容はinput.txtと全く同じ内容になってしまっている状況です。
input.txtは"japan somesome korea friends japan somesomerr korea friends japan somesomerw korea friends japan"とします。
今まで様々の方に質問してきたのですが、解決できず困っていました。みなさんにご協力いただきたいです。よろしくお願いします。
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void chop_crlf(char* buf);
char* FindAndDeleteString(char* buf, char* head, char* tail);
FILE *fp;
const char* ifile = "input.txt";
#define HEAD "japan"
#define TAIL "korea"
char *p,buf[5040];
int main(int argc, char* argv[])
{
FILE *hp = fopen("output.txt","w");
if ( hp == NULL ){
fprintf(stderr,"cannot output to file.\n");}
if ( ( fp = fopen(ifile,"r") ) == NULL ) {
fprintf(stderr,"%s: no such file or directory.\n", ifile);
return -1;
}
// 文字列の検索(文字列の置換)
rewind(fp);
while ( fgets(buf,5040,fp) ) {
chop_crlf(buf);
p = FindAndDeleteString(buf,(char*)HEAD,(char*)TAIL);
fprintf(hp,"%s\n",p);
if ( p != buf ) free(p);
}
fclose(fp);
fclose(hp);
return 0;
}
char* FindAndDeleteString(char* buf, char* head, char* tail)
{
char *newstring,*sp,*oldsp,*check;
oldsp = buf;
sp = strstr(buf,head)+strlen(head);
if ( strstr(buf,head) == NULL && strstr(buf,tail) == NULL ) return buf;
newstring = (char*)calloc(sizeof(char),strlen(buf));
while((check = strstr(sp,head)) != NULL){
strncpy(newstring+strlen(newstring),oldsp,sp-oldsp);
oldsp = strstr(sp,tail);
sp = strstr(oldsp,head)+strlen(head);
}
strncpy(newstring+strlen(newstring),oldsp,sp - oldsp);
return newstring;
}
// 改行コードの除去
void chop_crlf(char* buf)
{
for ( unsigned i=0; i<strlen(buf); i++ ) {
if ( buf[i] == '\r' || buf[i] == '\n' ) buf[i] = 0;
}
}