Reputation: 33
I need to read whole file between START and STOP strings and write that string into new file.
For example file1.txt = "Hello START world! STOP" and write to new file2.txt = "world!" (without spaces after START and before STOP)
I have that code already
I can use only 4 functions: fopen()
, fclose()
, fgetc()
, fputc()
My code wont work properly. It starts from START but at the end it writes space STO characters.
Could you help me with that algorithm? Thank you
#include <stdio.h>
int main( int argc, char *argv[] ) {
FILE *input;
FILE *output;
char c;
char start[] = "START";
char stop[] = "STOP";
int started = 0;
int stopped = 0;
input = fopen(argv[1], "r");
output = fopen(argv[2], "w");
c = fgetc(input);
int i = 0;
while(c != EOF) {
if(started == 0) {
//find start
if(c == ' ' || c == '\n' || c == ',' || c == '.')
i = 0;
else
{
if(c == start[i])
i++;
else
i = 0;
}
if(i == 5) {
started = 1;
i = 0;
c = fgetc(input); //move space
}
} else {
//write letters until stop
if(stopped == 0) {
//find stop
if(c == ' ' || c == '\n' || c == ',' || c == '.')
i = 0;
else
{
if(c == stop[i])
i++;
else
i = 0;
}
if(i == 4) {
stopped = 1;
i = 0;
break;
}
}
if(c != 'S' && c != 'T' && c != 'O' && c != 'P')
fputc(c, output);
}
c = fgetc(input);
}
fclose(input);
fclose(output);
return 0;
}
Upvotes: 0
Views: 137
Reputation: 14360
In order to achieve what you want you could read the whole file and then use srtok function for separating the text into tokens(using the space character as separator).
Then you could compare each token and look for your start and stop conditions.
According your example this should help.
Ref: https://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm
Upvotes: -2