I'm trying find and print a number after a specific user passed string in each line of a text file using C (as requested by the powers that be). I've pieced together enough to read the file, find the string and print the line it was found on but I�m not sure where to even start in terms of finding the number after the string. Any tips would be much appreciated.
The below code outputs the line number where the string is found:
/* usage exename textfile searchstring */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *file;
char line[BUFSIZ];
int linen = 1;
file = fopen(argv[1], "r");
if(file != NULL) {
while(fgets(line, sizeof(line), file)){
if(strstr(line, argv[2]) != NULL) {
printf("Found %s %s %i\n",argv[2],"@ line",linen);
}
++linen;
}
}
else {
perror(argv[1]);
perror(argv[2]);
}
fclose(file);
return 0;
}
My text file looks like below. I'm trying to print the number as is the file (2 decimals) after "val=".
123 test=123 val=233.33 x=111 y=222
123 test=123 val=.33 x=111
123 xr=3 test=123 x=111 y=222
123 test=123 val=233. x=111 y=222
123 test=123 val=233.33 x=111 y=222
Output from current code:
Found val @ line 1
Found val @ line 2
Found val @ line 4
Found val @ line 5