-1

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;
}
4

2 に答える 2

3

In your current code, it looks like you're reading the entire file at once into result, so there is no concept of a "line".

I recommend changing your loop so you read the file one line at a time.
Investigate fgets.
On each line, check that line for the keyword (strstr).

while(fgets(line, sizeof(line), fp)) {
    if (strstr(line, keyword) != NULL) {
        puts(line);   // if line contains the text, print it
    }
}
于 2012-06-05T18:44:36.557 に答える
2

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.

于 2012-06-05T18:45:16.007 に答える