Reputation: 25
I want to make a program that delete a String that the same as user input from a file below are contents in the file
G12
G13
G14
For example user input G13 , expected output is as following :
G12
G14
I got some idea that make a temporary file , but don't get any idea on how to get a string line by line because i print the file content using these code
if(file!=NULL)
{
while ((c = getc(file)) != EOF)
putchar(c);
fclose(file);
}
so basically i reads all the file content only letter by letter (dont have any idea how to make it reads word by word
Thanks in advance
Upvotes: 0
Views: 314
Reputation: 40145
simple line by line sample
#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;
}
Upvotes: 1
Reputation: 13
Exactly as Micheal said. On a file you can do only write and read operation. So you must read the char and when you find the exact word that you don't want to write, just don't write it. Otherwise you write it :)
Upvotes: 0