arynhard arynhard - 12 days ago 7
C Question

Scan a file to search pre-defined c keywords and print them on console

How can I scan a file for a word and then print the line containing that word in C programming?

I am trying to find a way to scan a file for a keyword and then print only the line containing that word. I am off to a very rough start. Here is what I 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: This did what I 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 the text, print it
}
}

int main(int argc, const char * argv[])
{
getDsk();
return 0;
}

Answer

A few things:

1) You should pretty much never write while(!feof(fp)) { ... } It is a broken pattern because feof will only return true after a read attempt. So you are open to off by one errors.

2) why the heck are you doing this?

fp = popen("diskutil list","r");
fread(result,1,sizeof(result),fp);
fclose (fp);

You are reading 1000 chars of the file then closing it, then later your stub code acts as if it plans on reading the file some more... makes no sense.

3) here's a reasonable approach:

char line[1024];
while(fgets(line, sizeof(line), fp)) {
    // if line contains the text, print it
}

what is going on here is fgets will read a line and return non-NULL if it succeeds. (NULL is treated as "false", non-NULL is "true" when used in a test).

So it is saying "while we could successfully read a line, do the following", which is really what you want. Also, I am making the assumption that no lines will exceed 1024 characters which is usually a reasonable assumption, if this is not the case, then you will need to adjust accordingly.

Comments