gpt4 book ai didi

C - 如何从c文件中删除与用户输入相同的字符串?

转载 作者:行者123 更新时间:2023-11-30 15:34:25 26 4
gpt4 key购买 nike

我想制作一个程序,删除与文件中用户输入相同的字符串以下是文件中的内容

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com