I am facing problems scanning an existing file.
The challenge is that I have a source text file with some strings. I have to scan this file for the word "o'clock"
, and where I find it, I have to take the word before "o'clock"
and enclose it in square brackets.
I found a function to find the trigger, but I don't understand what I need to do next. I would be grateful if you could explain how to replace the characters in the read string.
For example: We have a string:
"Let's go to the graveyard at night - at twelve o'clock!"
I need to replace the word twelve
with [twelve]
.
Here is the code:
#include <stdio.h>
#include <string.h>
int main() {
FILE * fp; //open exists file
FILE * fn; //open empty file
char c[1000]; // buffer
char trigger[] = "o'clock"; // the word before which the characters should be added
char name [] = "startFile.txt"; // name of source file
char secondName[] = "newFile.txt"; // name of output file
fp = fopen (name, "r"); // open only for reading
if (fp == NULL) { // testing on exists
printf ( "Error");
getchar ();
return 0;
}
fn = fopen(secondName, "w"); // open empty file for writing
while (!feof(fp)) { // scanning all string in the source
if(fgets(c,1000, fp) != NULL) { // reading charter from file
fprintf(fn, c); // writing charter from buffer "c" to empty file
if (strstr(c, trigger)) { // find triggered word
// I tried compare string which has a trigger-word
}
}
}
fclose(fp); // closing file
fclose(fn);
return 0;
}