views:

42

answers:

2

Hello!

I'm trying to execute "whois search domainname.tld". I'm currently using system("whois search domainname.tld"); however i need to get the output into a NSString variable to output to the user.

How can i do this?

+1  A: 

Use popen instead.

The system function call does not return any output so you can't get it with that.

You can use popen for example to pipe output of netstat -l:

#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
    FILE * fp;
    int status;
    const unsigned int sz = 1024;
    char buf[sz];

    string cmd;
    //cmd = "ls *";
    cmd = "netstat -l";
    fp = popen(cmd.c_str(), "r");
    if (fp == NULL) return 0;

    while (fgets(buf, sz, fp) != NULL)
        printf("%s", buf);

    status = pclose(fp);
    if (status == -1)
    {
        cout << "pclose failed" << endl;
    }

    return 1;
}

see man popen for more info.

It should be easy to incorporate the output into Objective-C since you can call C from Objective-c.

stefanB
very helpfull downvote, I assume it's because there's no Objective-c involved here ... I'm just showing how to get the output from C which can be then incorporated in Objective-c instead of the call to `system()`. Since there's no example code in question showing the call to system I'm not going to write the whole application, just showing the important part ...
stefanB
+1 If OP uses system() and needs to retrieve stdout, he should be aware of popen().
mouviciel
+2  A: 

If you want, you can alternatively use NSTask to accomplish the same goal. Now, I'm not usually one to do people's homework for them, but here is how you would do something like this with NSTask: pastie.org/1087887.

The idea is that you create an NSTask object to run @"/usr/bin/whois" (the location on disk where whois is run from) with the argument @"search domainname.tld". You then use an NSPipe object to read the output from the command, and return that to the user.

Note: this function is blocking (it'll wait until whois finishes running before finishing), which is not recommended, especially for network operations. Making this asynchronous is an exercise left to the reader.

itaiferber