|
文字列が複数格納されているファイルに対して
先頭の文字列を削除して最後尾に追加するプログラムを作っています。
ただ今の状態ですと削除する文字列が追加する文字列より長いと
ファイルの後方にごみが残ってしまいます。
例えば
aaa
b
c
のファイルに対してdを入れると
b
c
d
c
となってしまいます。
どう対処したら
b
c
d
だけのファイルにすることができるのでしょうか?
ソースは以下のとおりです。
int fileupdate( const char *filename, char *new_data)
{
FILE *fp;
int old_fp=0, new_fp=0;
int over_cnt=1;
char log[DATASIZE];
memset(log, '\0', sizeof(log));
fp = fopen(filename, "r+" );
if (fp == NULL){
return(1);
}
while (fgets(log, DATASIZE, fp)){
old_fp += strlen(log);
/* 先頭は無視 */
if (over_cnt != 0){
over_cnt--;
continue;
}
/* ファイル更新後のファイルポインタに移動 */
fseek(fp, new_fp, SEEK_SET);
fprintf(fp, "%s", log);
new_fp += strlen(log);
/* ファイル更新前のファイルポインタに移動 */
fseek(fp, old_fp, SEEK_SET);
}
fseek(fp, new_fp, SEEK_SET);
fprintf(fp, "%s\n", new_data);
fclose(fp);
return(0);
}
|