作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想制作一个程序,删除与文件中用户输入相同的字符串以下是文件中的内容
G12
G13
G14
例如用户输入 G13 ,预期输出如下:
G12
G14
我有一些创建临时文件的想法,但不知道如何逐行获取字符串,因为我使用这些代码打印文件内容
if(file!=NULL)
{
while ((c = getc(file)) != EOF)
putchar(c);
fclose(file);
}
所以基本上我只是逐字读取所有文件内容(不知道如何让它逐字读取
提前致谢
最佳答案
简单的逐行示例
#include <stdio.h>
#include <string.h>
char *esc_cnv(char *str){
char *in, *out;
out = in = str;
while(*in){
if(*in == '\\' && in[1] == 'n'){
*out++ = '\n';
in += 2;
} else
*out++ = *in++;
}
*out = '\0';
return str;
}
int main(void){
FILE *fin = stdin, *fout = stdout;
char line[1024];
char del_str[1024];
char *p, *s;
int len;
int find=0;//this flag indicating whether or not there is a string that you specify
fin = fopen("input.txt", "r");
fout = fopen("output.txt", "w");//temp file ->(delete input file) -> rename temp file.
printf("input delete string :");
scanf("%1023[^\n]", del_str);
esc_cnv(del_str);//"\\n" -> "\n"
len = strlen(del_str);
while(fgets(line, sizeof(line), fin)){
s = line;
while(p = strstr(s, del_str)){
find = 1;//find it!
*p = '\0';
fprintf(fout, "%s", s);
s += len;
}
fprintf(fout, "%s", s);
}
fclose(fout);
fclose(fin);
if(find==0)
fprintf(stderr, "%s is not in the file\n", del_str);
return 0;
}
关于C - 如何从c文件中删除与用户输入相同的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23297037/
我是一名优秀的程序员,十分优秀!