Genato
Genato

Reputation: 606

Reading the lines from command prompt?

I have question about C but my programming skills are not good as am still learning/studying.

Let me first explain my problem, out of pure curiosity and laziness i wanted to create some program in C that can auto ping some range of IP on my local network and give me what IP is alive.

Ok, so far without problem i managed to write few lines but am stuck on part where i need to read some lines from command prompt. After it execute this line, cmd start pinging the address it is provided.

system("ping 192.168.000.000")

So after it finishes this line can i read the info from cmd and use it to compare with other ping info?

Or there is some other way that i should start looking to solve this problem?

Upvotes: 0

Views: 143

Answers (3)

chqrlie
chqrlie

Reputation: 145307

You can use this method:

int main() {
    FILE *fp = popen("ping 192.168.000.000", "r");
    //Read process output via fp and compare with other ping info
    pclose(fp);
    return 0;
}

The advantage of this method is you do not need a temporary file and you can read the output as it is produced, unbounded in size or time, which is very handy for ping as it does not stop under unix. You can kill the process at any time with pclose(fp);.

Upvotes: 6

aschepler
aschepler

Reputation: 72473

You may want popen, which allows you to read from the results of a command as from a file.

Upvotes: 1

Ryan Fitzpatrick
Ryan Fitzpatrick

Reputation: 783

Redirect the output of your command to a text file and then read that file to get the output:

int main()
{
    FILE * fp;
    system("ping 192.168.000.000 > output.txt");
    fp = fopen("output.txt", "r");
    //Read text file and do comparison
    fclose(fp);
    return 0;
}

Upvotes: 1

Related Questions