文件较小的话可以一次读入内存,按字符串处理。
#include <stdio.h>
#include <ctype.h>
#include <string.h>
char *upper(char *str)
{
char *p=str;
for (; *p; ++p)
*p = toupper(*p);
return str;
}
main()
{
FILE *fp = fopen("test.txt", "w");
fprintf(fp, "%s\n", "abc asd abc");
fprintf(fp, "%s\n", "abc aSd");
fprintf(fp, "%s\n", "abc asdd");
fclose(fp);
char s[256];
fp = fopen("test.txt", "r+");
while (fscanf(fp, "%s", s)==1)
{
if (strcmp("ASD",upper(s))==0)
{
fseek(fp, -3, SEEK_CUR);
fwrite(s, 3, 1, fp);
fseek(fp, 1, SEEK_CUR);
}
}
fclose(fp);
fp = fopen("test.txt", "r");
while (fgets(s, 256, fp))
printf("%s", s);
fclose(fp);
}