遇到的问题,在网上找的方法,改改,能用。真的很好,大体思想是创建令一个文件,把没有该字符串的内容都写进去,让新的覆盖就的,就完成了删除指定字符串,等于把旧的字符串过滤掉了。但也有个问题,我的匹配(中文)会出问题,英文没事,知道的可以告诉我,呵呵。
#include<stdio.h>
#include<cstdlib.h>
#include<cmath>
#include<string.h>
#include<stdlib.h>
#Include<time.h>
#include<conio.h>
#include<malloc.h>
#include<io.h>
#include<locale.h> //setlocale
//删除文件中指定的字符串
void main()
{
//setlocale(LC_ALL ,"chs");
FILE* fp,*temp;
char ch,del_str[30],str[30],filename[30];
int len;
/*
//输入文件名
printf("input the filename:\n");
gets(filename);
*/
//以只读模式打开文件
char* str1="E:\\xiao.txt";
strcpy(filename,str1);
if((fp=fopen(filename,"r"))==NULL)
//if((fp=fopen(str1,"r"))==NULL)
{
perror("fail to open file");
exit(0);
}
//创建临时文件
temp=tmpfile();
/*
if((temp=tmpfile())==NULL)
{
perror("fail to create temporary file");
exit(0);
}
*/
char* str2="xiaopang"; //要删除的字符串
strcpy(del_str,str2);
/*
//输入待删除字符串
printf("input the string you want to delete:\n");
gets(del_str);
*/
//将文件中所有非del_str的字符串拷贝到临时文件中
while(fgets(str,strlen(del_str)+1,fp))
{
/*字符串不匹配则将相应字符存入temp中
匹配则继续比较下个字符串
*/
len=strlen(str);
if(strcmp(str,del_str)!=0)
{
//遇到了换行或回车符,则直接将字符串放进temp中
if(str[len-1]=='\n'||str[len-1]=='\r')
fputs(str,temp);
else
{
fputc(str[0],temp); //将第一个字符存入temp中
fseek(fp,-(len-1),1); //文件指针回移,SEEK_SET,SEEK_CUR,SEEK_END依次为0,1,2。-(len-1)正数表示正向偏移,负数表示负向偏移
/*fseek原来没看懂,后请教大神。每次都是写一个字符,fputc,但比较后,光标会到字符串末尾,于是字符串长度-1就是第二个字符位置,
在进行下一个字符串比较,第一个写到了temp临时文件里,就这样,感谢大神。*/
}
}
}
fclose(fp);
//以只写模式打开文件
if((fp=fopen(filename,"w"))==NULL)
{
perror("fail to open file");
exit(0);
}
//将临时文件指针重新设置到起点
rewind(temp);
ch=fgetc(temp);
while(!feof(temp))
{
fputc(ch,fp);
ch=fgetc(temp);
}
printf("delete over!\n");
//关闭文件
fclose(fp);
fclose(temp);
}