0

I'm developing a Cocoa app that has to execute some terminal commands. One of these looks like:

printf "\xc5\x20\x00\x00" >> aFile.txt

I tried with NSTask (but I'm not sure how to split the arguments):

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/printf"];
[task setArguments:[NSArray arrayWithObjects:@"\"\\xc5\\x20\\x00\\x00\"",
                                             @">>",
                                             @"aFile.txt", nil]];
[task launch];

All I get is:

printf: missing format character

So I think that ">>" is not a printf argument but an internal terminal command.

How can I simulate that command in Objective C?

Oneiros
  • 4,328
  • 6
  • 40
  • 69

2 Answers2

4

You may be interested in NSTask method:

- (void)setStandardOutput:(id)file

and in NSFileHandle methods:

+ (id)fileHandleForWritingAtPath:(NSString *)path
- (unsigned long long)seekToEndOfFile
mouviciel
  • 66,855
  • 13
  • 106
  • 140
  • Thank you very much, it works. But... there's a problem: i get "xc5x20x00x00" in the txt file instead of "√&", that i get if i run that command in the terminal – Oneiros Nov 07 '11 at 14:43
1

You're right, the >> token is a shell feature, not an argument to printf.

In this example, I'd probably not use the shell to do this, rather I would write the code to do it in Cocoa or plain C (with stdio.h).

However, to use the shell >> command, you can send the line to a shell process, which will interpret >> correctly.

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/bash"];
[task setArguments:[NSArray arrayWithObjects:@"-c",
                                             @"printf \"\xc5\x20\x00\x00\" >> aFile.txt",
                                             nil]];
[task launch];
joerick
  • 16,078
  • 4
  • 53
  • 57