How to check if a string is in a file

偶尔善良 提交于 2019-12-12 01:34:09

问题


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.



来源:https://stackoverflow.com/questions/20278294/how-to-check-if-a-string-is-in-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!