Skip to content
Prev 32329 / 398513 Next

Calling R in BATCH mode from C programm

Dear, Prof. Repley,

thank you for the help,
of course, you are right. 

Redirection of stdin, stdout, stderr does the job.

If R script saves and reloads apprpriate workspaces,
then this method may be used instead of calling R functions from
C/C++ directly, wich is currently a problem, as I understand.

Here is C code that calls R in BATCH mode with arguments.
Then R runs script args.R wich reads the input arguments with Sys.getenv()
function and prints output to args.out and err.out files.

May be someone will find it usefull :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


char emsg[] = "can't redirect %s to %s\n";

void main ()
{
	int result, i;
	char buf[5120];

	if (!freopen( "args.R", "r", stdin )) {
		fprintf( stderr, emsg, "stdin", "args.R" );
		exit( 1 );
	}
	if (!freopen( "args.out", "w", stdout )) {
		fprintf( stderr, emsg, "stdout", "args.out" );
		exit( 1 );
	}
	if (!freopen( "err.out", "a", stderr )) {
		fprintf( stderr, emsg, "stderr", "err.out" );
		exit( 1 );
	}

	strcpy( buf, "Rterm --slave --no-save --no-restore ARG1=1 ARG2=2" );

	if (result = system( buf ))
		fprintf( stderr, "exit code = %d, errno = %d\n", result, 
errno );
}





Quoting Prof Brian Ripley <ripley at stats.ox.ac.uk>: