1

What I want to do

To run an executable "server" from my Cocoa app. The executable can already run perfectly when invoked in the terminal and will read a text file in the same directory.

What I've done

Put "server" and other files in the "Supporting Files" folder in Xcode. Use NSTask to run "server":

NSString *path = [[NSBundle mainBundle] pathForResource:@"server" ofType:nil];
NSArray *args = [[NSArray alloc] init];
[NSTask launchedTaskWithLaunchPath:path arguments:args];

The error

The executable couldn't open a text file. Specifically, a C function fopen("tradingbook_closing.txt", "r") in the source code failed to open the file. But the file was there and running the executable in the terminal directly goes flawless. And the app is not sandboxed. Could anyone find what went wrong?

Thanks a lot.

Khylnn Wu
  • 19
  • 5

1 Answers1

2

You are using a relative path for the file, "tradingbook_closing.txt", which relies on the current directory for the process to be the one containing that file. This is probably the cause of your error.

It is best not to hardwire relative paths into a program, but if you must you can set the current directory of the process launched by NSTask using the currentDirectoryPath property. You'll need to create an NSTask instance, rather than using the class method launchedTaskWithLaunchPath:arguments: and then set the launchPath, arguments and currentDirectoryPath properties before calling the launch method.

CRD
  • 52,522
  • 5
  • 70
  • 86