Scan a file to search pre-defined c keywords and print them on console -
how can scan file word , print line containing word in c programming?
i trying find way scan file keyword , print line containing word. off rough start. here have:
#include <stdio.h> void getdsk (void); void getdsk () { file* fp; char result [1000]; fp = popen("diskutil list","r"); fread(result,1,sizeof(result),fp); fclose (fp); while(!feof(fp)) { if(//line contains "test".) { //show line. } } } int main(int argc, const char * argv[]) { getdsk(); return 0; }
edit: did needed.
#include <stdio.h> void getdsk (void); void getdsk () { printf("your available windows installations are:\n"); file* fp = popen("diskutil list","r"); char line[1024]; while(fgets(line, sizeof(line), fp)) { if (strstr(line,"microsoft")) { printf("%s", line); } // if line contains text, print } } int main(int argc, const char * argv[]) { getdsk(); return 0; }
a few things:
1) should pretty never write while(!feof(fp)) { ... }
broken pattern because feof
return true after read attempt. open off 1 errors.
2) why heck doing this?
fp = popen("diskutil list","r"); fread(result,1,sizeof(result),fp); fclose (fp);
you reading 1000
chars of file closing it, later stub code acts if plans on reading file more... makes no sense.
3) here's reasonable approach:
char line[1024]; while(fgets(line, sizeof(line), fp)) { // if line contains text, print }
what going on here fgets
read line , return non-null
if succeeds. (null
treated "false", non-null
"true" when used in test).
so saying "while read line, following", want. also, making assumption no lines exceed 1024
characters reasonable assumption, if not case, need adjust accordingly.
Comments
Post a Comment