How to check if a string is in a file

2019-09-14 19:43发布

问题:

I'm new to C and I am trying to figure out how I can search for a specific string and the number that follows it in a file that has several numbers and words.

The input file that I'm using looks like this:

TREES 2
BENCHES 5
ROCKS 10
PLANTS 8

I know how to make a function read a string and I know how to compare two strings but I don't know how to put them both together or how to set the array up to read through the whole file.

I've been using strcmp, but I just don't know how to go about initializing the word I'm trying to look for.

回答1:

You could do something like this:

#include <stdio.h>

int main(void){
FILE *fp;
char *searchString="ROCKS";
fp = fopen("myfile.txt", "r");
char *buf[100];
int myNumber = -1;
while((fgets(buf, 100, fp)!=NULL) {
  if(strstr(buf, searchString)!=NULL) {
    sscanf(buf + strlen(searchString), "%d", &myNumber);
    break;
  }
}
printf("After the loop, myNumber is %d\n", myNumber);
fclose(fp);
}

Disclaimer - untested. Should be close...



回答2:

Create an array that contains the words to search for. Create an outer loop that advances through your file stream of data one character offset at a time. Create a second inner loop that iterates over your array of terms to search for. The inner loop examines each term in the array against the data provided by the outer loop. Use strncmp to limit the length of each compare to the length of the word being searched for. Upon a match, check the following character in the source buffer to ensure it doesn't negate the match.