need programming help: Cocoa and NSTask

Discussion in 'Mac Programming' started by Oats, Jun 7, 2007.

  1. Oats macrumors regular

    Jan 8, 2003
    New York
    I am trying to write a simple Cocoa / Objective-C app which allows the user to specify a Folder and a search term, and then searches in all files in the folder for the search term. Essentially, I am trying to make a GUI interface for the "grep" UNIX command and it's results.

    I am trying to use NSTask to create the shell command and return the results, but this is not working for whatever reason. I am able to get my search terms and directory strings just fine, but I get this message in my Run Log:

    grep: /Users/oats/Desktop/wordpress_22/*: No such file or directory
    This is the NSTask setup:
    	NSTask *task;
        task = [[NSTask alloc] init];
        [task setLaunchPath: @"/usr/bin/grep"];
        NSArray *arguments;
        arguments = [NSArray arrayWithObjects: @"-l", @"-r", searchText, filepathstr, nil];
        [task setArguments: arguments];
    Then I launch the task and try to read the results:
    	NSPipe *pipe;
        pipe = [NSPipe pipe];
        [task setStandardOutput: pipe];
        NSFileHandle *file;
        file = [pipe fileHandleForReading];
        [task launch];
        NSData *data;
        data = [file readDataToEndOfFile];
    This command works fine in the terminal, so why doesn't NSTask return anything? I've been a programmer for a long time (C++, Java), but Objective-C and Cocoa are rather new to me. Thanks!
  2. whooleytoo macrumors 603


    Aug 2, 2002
    Cork, Ireland.
    Just out of curiosity, have you tried using system() using the same parameters (in a C string), to see if that works?
  3. fimac macrumors member

    Jan 18, 2006
    use system()

    The shell (e.g. bash) is responsible for expanding wildcards, therefore grep is correctly reporting that the file "/Users/oats/Desktop/wordpress_22/*" does not exist.

    Using the system() call will work, since the string argument is passed to the shell for processing:

    #include <stdlib.h>
    int main(void)
      (void)system("grep unsigned *.c");
      return 0;
  4. semaja2 macrumors 6502a

    Dec 12, 2005
    or you can use the /bin/sh etc as your command and just tell it to run grep or whatever, thats how i do my NSTasks
  5. Oats thread starter macrumors regular

    Jan 8, 2003
    New York
    thank you all! i decided to go the route of using /bin/sh to execute my task, and that works great! much thanks!

    now i just have to figure out array controllers so i can display the results :rolleyes:
  6. AzMacNoob macrumors newbie

    May 25, 2007
    Phx, AZ

Share This Page