sgript
sgript

Reputation: 317

Removing a line from file that contains an inputted word

I've been trying to remove whole lines in a file (.txt) where a line contains the number ('1234' for example) using C. The number is given through scanf input.

Note that the line contain whitespaces, such as: Bob 1234 Apple Tree

I was wondering if someone could explain to me a method that could work effectively.

Thanks.

Upvotes: 0

Views: 44

Answers (1)

szpal
szpal

Reputation: 647

I hope this help you to start:

char *in_file, *out_file, line[255];
FILE *fp1, *fp2;

in_file  = "input.txt";
out_file = "output.txt";

fp1 = fopen( in_file, "r" );
fp2 = fopen( out_file, "w" );

while ( fgets( line, sizeof( line ), fp1 ) != NULL ) {
  if ( strstr( line, "1234" ) ) {
     fputs( line, fp2 );
  }
}

fclose( fp2 );
fclose( fp1 );

Upvotes: 1

Related Questions