I would like to execute the Applescript command tell application "Finder" to open POSIX file */path/to/somefilename*
from a C++ program. It looks like I might want to use OSACompileExecute
, but I haven't been able to find an example of how to use it. I keep finding examples of how to use the OSACompile
Terminal command. Can someone provide an example or a link to an example?
Asked
Active
Viewed 3,933 times
5

SSteve
- 10,550
- 5
- 46
- 72
2 Answers
6
Ok, the trick was to not bother trying to compile and execute the Applescript but to simply use the osascript
system command:
sprintf(cmd, "osascript -e 'tell app \"Finder\" to open POSIX file \"%s/%s\"'", getcwd(path, MAXPATHLEN), file);
system(cmd);
path
and file
are both char[] variables.
I got the clue from this excerpt from Applescript: The Definitive Guide.

SSteve
- 10,550
- 5
- 46
- 72
1
Here's an example C function for reading a Get Info comment from the finder using AppleScript.
You could modify it for what you want.
NSString * readFinderCommentsForFile(NSString * theFile){
/* Need to use AppleScript to read or write Finder Get Info Comments */
/* Convert POSIX file path to hfs path */
NSURL * urlWithPOSIXPath = [NSURL fileURLWithPath:theFile];
NSString * hfsStylePathString =
(__bridge_transfer NSString *)CFURLCopyFileSystemPath((__bridge CFURLRef) urlWithPOSIXPath, kCFURLHFSPathStyle);
/* Build an AppleScript string */
NSString *appleScriptString = @"tell application \"Finder\"\r get comment of file ";
appleScriptString = [appleScriptString stringByAppendingString:@"\""];
appleScriptString = [appleScriptString stringByAppendingString:hfsStylePathString];
appleScriptString = [appleScriptString stringByAppendingString:@"\""];
appleScriptString = [appleScriptString stringByAppendingString:@"\r end tell\r"];
NSString *finderComment;
NSAppleScript *theScript = [[NSAppleScript alloc] initWithSource:appleScriptString];
NSDictionary *theError = nil;
finderComment = [[theScript executeAndReturnError: &theError] stringValue];
NSLog(@"Finder comment is %@.\n", finderComment);
return finderComment;

Jim Merkel
- 352
- 2
- 9
-
1It is Objective-C code example using an NSAppleScript object and can't be used in C++ – dj bazzie wazzie Feb 01 '12 at 19:40
-
For this project I'm hoping to avoid Cocoa and Objective-C if possible. – SSteve Feb 01 '12 at 19:40
-
Presumably objective-c as c doesn't use `[`, `]`, `@`, or `:` in the ways exhibited here. – dmckee --- ex-moderator kitten Feb 01 '12 at 19:40
-
It's a C function using Objective-C methods. – Jim Merkel Feb 01 '12 at 19:42
-
2Try running that though vanilla c compiler. That simply *isn't* c syntax. – dmckee --- ex-moderator kitten Feb 01 '12 at 20:00