[R] filling a string buffer in a C routine

Dan Lipsitt danlipsitt at gmail.com
Thu Feb 3 23:51:51 CET 2005


I am trying to write a C function that reads lines from a file and
passes them back to R.

Here is a simplified version:

--- C code ---

#include <R.h>
void read_file(char **filename, char **buf, char **buflen) {
  FILE *infile;

  infile = fopen(*filename, "r");
  fgets(*buf, *buflen, infile);
  fclose(infile);
}

--- R code ---

buffer = "xxxxxxxxxx"            # kludge!

read.file <- function(filename) 
  .C("read_climate",
     as.character(filename),
     buf=buffer,
     buflen=as.integer(10))$buf

--- end code ---

This works okay, but the only way I could find to allocate a string
buffer of the size I want is to use a string literal as in the line
marked "kludge" above. It is impractical for large buffers, not to
mention uuuggly. I tried

 buffer = paste(rep('x', 10), sep="")

but it doesn't work. So my question is, how do I do one of the following:

- Allocate a character buffer of a desired size to pass to my C routine.
- Have the C routine allocate the buffer without causing a memory leak.
- Use .Call() instead

Thanks,
Dan




More information about the R-help mailing list