PDA

View Full Version : external application argument


macNewbie
2006.03.16, 04:08 AM
Hi,
I'm building cocoa application which launch external command line application.
The command line requires file as an input and output as a file as well.
In the command line will be: nfbtrans <inputFile.txt >outputFile.txt which means take input from inputFile and store the result in outputFile. It works fine.
In cocoa, part of my program is as follows:

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/usr/local/bin/nfbtrans"];

NSArray *arg;
NSString *inFileArgument = @"</inputFile.txt";
NSString *outFileArgument = @">/out.txt";
arg = [NSArray arrayWithObjects:inFileArgument,outFileArgument, nil];
[task setArguments:arg];
[task launch];

The command line application launched but it said that the inputFile.txt doesn't exist. However, when I check in the directory, the file does exist. I suspect that it has problem with "<" character. Is that any special way to handle special characters arguments?

Thank you in advance.

OneSadCookie
2006.03.16, 05:12 AM
The < is a shell redirection, which won't work directly with NSTask because your arguments are not being parsed by the shell.

If the command-line program is your own, you should rewrite it to accept the file paths in argv, rather than always reading from standard input and writing to standard output.

If it's not, you should look into NSPipe to communicate with it.

gilgoomesh
2006.03.19, 05:40 PM
If you really want to use shell redirection, you can send the whole command to /bin/sh.

[task setLaunchPath:@"/bin/sh"];

and make the first argument: "-c" (tell /bin/sh to execute the next argument as a script)
and make the second argument: "/usr/local/bin/nfbtrans < /inputFile.txt > /out.txt".

This is normally much slower than doing it OneSadCookie's way (starting sh can be slow and running a scripted shell is slower than running a command) and you have to deal with environment changes due to login scripts but it can be easier to write.

macNewbie
2006.03.21, 02:29 AM
Thank you for the replies :)
I used both approaches.
I know it is not an elegant way. Just desperately need my program to work at this moment :p
Thank you for the help.