Skip to content

Commit

Permalink
Use stack memory for buf
Browse files Browse the repository at this point in the history
Also test on empty key files
  • Loading branch information
wlandau-lilly committed Jan 9, 2019
1 parent 474247f commit 73fb923
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
12 changes: 8 additions & 4 deletions src/storr.c
Expand Up @@ -3,19 +3,23 @@
#include <Rinternals.h>
#include <Rversion.h>

#define MAX_HASH_LENGTH 128

SEXP Cread_text_file(SEXP path, SEXP nchar) {
FILE *fp;
fp = fopen(CHAR(asChar(path)), "rb");
if (fp == NULL) {
Rf_error("File %s does not exist", path);
Rf_error("File %s does not exist.", path);
}
int n = asInteger(nchar) + 1; // Need an extra character for '\0'.
char *buf = (char*) malloc(n * sizeof(char));
fgets(buf, n, fp);
char buf[MAX_HASH_LENGTH + 1];
char *res = fgets(buf, n, fp);
if (res == NULL) {
Rf_error("File %s is empty.", path);
}
fclose(fp);
SEXP out = PROTECT(mkString(buf));
UNPROTECT(1);
free(buf);
return out;
}

Expand Down
13 changes: 11 additions & 2 deletions tests/testthat/test-util.R
Expand Up @@ -99,7 +99,16 @@ test_that("write_lines recovers on error", {

test_that("read_text_file() works", {
expect_false(file.exists("does_not_exist"))
expect_error(read_text_file("does_not_exist", 12))
expect_error(
read_text_file("does_not_exist", 12),
regexp = "does not exist"
)
file.create("empty_file")
on.exit(unlink("empty_file"))
expect_error(
read_text_file("empty_file", 12),
regexp = "is empty"
)
randstring <- function(n) {
paste(sample(letters, size = n, replace = TRUE), collapse = "")
}
Expand All @@ -110,5 +119,5 @@ test_that("read_text_file() works", {
on.exit(unlink(file))
expect_equal(read_text_file(file, n), string)
}
lapply(seq_len(200), test_read_text_file)
lapply(seq_len(127), test_read_text_file)
})

0 comments on commit 73fb923

Please sign in to comment.