Message Boards Message Boards


Running external programs with Run[]

Posted 10 years ago
3 Replies
2 Total Likes
Hello everyone, 

I have a problem that I thought somebody here might be able to help me with:
I have an external program which writes some data to file. I want to invoke it from within a Mathematica function and then import the data from file.I have made the following minimal working example:
 #include <iostream>
 #include <fstream>
 using namespace std;
 int main(int argc, char *argv[]) {   
      ofstream myfile; ("example.txt");
      myfile << argv[1];
      return 0;
I compile it and run it from Mathematica using the following code:
directory = StringReplace[FileNameDrop[NotebookDirectory[], 3], " " -> "*"]
command = StringJoin["./", directory, "/test"]
argument = "hello"
Run[command, argument]
This returns 0 to Mathematica and writes the word "hello" to file.The result is equivalent to running the command "./test hello" from the command line, except that the output file is written to my home directory rather than the current directory.
Next I try the same with the program that I actually need to use:
directory = StringReplace[FileNameDrop[NotebookDirectory[], 3], " " -> "*"]
command = StringJoin["./", directory, "/triangle"]
argument = "-pQIeq20Aa0.0025 model.poly"
Run[command, argument]
This should be equivalent to running "./triangle -pQIeq20Aa0.0025 model.poly" from the command line, but I get error message 256 and the program produce no output. 
What could be the problem? Is my system somehow denying Mathematica permission to execute the program?I run Mathematica 9 in Mountain Lion.

I would appreciate any help!

Best regards,

POSTED BY: Andreas Hafver
3 Replies
I resolved my own problem: 
One of the arguments to the external program is the name of an input file, which is located in the same folder as the executable.
I thought that this file name should be specified relative to the location of the external program, but it turns out that I have to specify the full path. 
Now it works perfectly!

POSTED BY: Andreas Hafver
Maybe you want to run it as:
command <> " " <> argument
rather than separate commands?
POSTED BY: Sander Huisman
Thank you for you reply, Sander Huisman,  I tried your suggestion, but I get exactly the same error as before.
POSTED BY: Andreas Hafver
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract