开发者

NSTask problem with 'cat' command

I try concatenating files using the cat command. When I use this in the terminal, everything works fine :

cat /Users/Home/Desktop/test.mp3* > test.mp3

Trying to reproduce this using an NSTask, gives me the error below :开发者_如何学Go

Code :

NSArray *Args = [NSArray arrayWithObjects:[NSString stringWithFormat:@"%@*",[TAFileName stringByDeletingPathExtension]],@">",[TAFileName stringByDeletingPathExtension],nil];
NSLog(@"%@",Args);
NSString *LaunchPath = [[NSBundle mainBundle] pathForResource:@"cat" ofType:@""];
[self startTaskWithLaunchPath:LaunchPath andArguments:Args showingProcess:NO];

NSLog output :

(
"/Users/Home/Desktop/test.mp3*",
">",
"/Users/Home/Desktop/test.mp3"
)

Error :

cat: /Users/Home/Desktop/test.mp3*: No such file or directory
cat: >: No such file or directory
cat: /Users/Home/Desktop/test.mp3: No such file or directory

The "startTaskWithLaunchPath: andArguments: showingProcess:" works fine with lots of other terminal commands, I'm 100% sure that's not the problem.


The problem is input redirection and globbing, which is handled by the shell (typically #!/bin/bash) and not by the cat command. So starting a task with an argument to expand "test.mp3*" into a real MP3 name and then redirect it to a different location is not something that a task can do.

I would recommend seeing if you can call a shell script directly, perhaps even dynamically create it in your app - and then call it as an argument to the bash application. Then it should do what you need.


I managed to solve the problem using "/bin/sh". This parses a command into a shell and runs it like that. Using this method still outputted "No such file", but I solved that by altering the task initial working directory.

Code for launching the task :

NSArray *Args = [NSArray arrayWithObjects:@"-c",[NSString stringWithFormat:@"cat %@.* >> %@",[[TAFileName lastPathComponent] stringByDeletingPathExtension],[[TAFileName lastPathComponent] stringByDeletingPathExtension]],nil];
NSString *LaunchPath = @"/bin/sh";
[self startTaskWithLaunchPath:LaunchPath andArguments:Args showingProcess:NO];

Code to change the directory :

[TATask setCurrentDirectoryPath:[NSString stringWithFormat:@"%@/",[TAFileName stringByDeletingLastPathComponent]]];

That solved everything. Thanks, Michael, for your help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜