Skip to content

Instantly share code, notes, and snippets.

@traversc
Created July 24, 2019 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save traversc/b531a4932e87cca2aa324c6a015c80a4 to your computer and use it in GitHub Desktop.
Save traversc/b531a4932e87cca2aa324c6a015c80a4 to your computer and use it in GitHub Desktop.
#include <sys/types.h>
#include <sys/stat.h>
#include <io.h>
#include <fcntl.h>
#include <string.h>
#include <array>
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::export]]
int makeFdForWrite(std::string filename) {
int fd = open(filename.c_str(), _O_WRONLY | _O_CREAT | _O_BINARY, _S_IWRITE);
if(fd == -1) Rcpp::stop("somthing went wrong :(");
return fd;
}
// [[Rcpp::export]]
void writeToFd(int fd) {
std::array<unsigned char, 17> mydata =
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
int bytes_written = write(fd, mydata.data(), mydata.size());
if(bytes_written != mydata.size()) Rcpp::stop("somthing went wrong :(");
close(fd);
}
// [[Rcpp::export]]
int makeFdForRead(std::string filename) {
int fd = open(filename.c_str(), O_RDONLY | _O_BINARY);
if(fd == -1) Rcpp::stop("somthing went wrong :(");
return fd;
}
// [[Rcpp::export]]
std::vector<unsigned char> readFromFd(int fd) {
std::vector<unsigned char> output;
std::array<unsigned char, 4> temp = {0,0,0,0};
int bytes_read;
while( (bytes_read = read(fd, temp.data(), 4)) > 0 ) {
output.insert(std::end(output), std::begin(temp), std::begin(temp) + bytes_read);
}
close(fd);
return output;
}
/*** R
setwd("N:/")
write_fd <- makeFdForWrite("fdtest_windows.bin")
writeToFd(write_fd)
readBin("fdtest_windows.bin", what="raw", n=1e9)
read_fd <- makeFdForRead("fdtest_windows.bin")
readFromFd(read_fd)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment