Skip to content

Instantly share code, notes, and snippets.

@stv0g
Last active March 14, 2016 19:07
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 stv0g/076d33783c66e736cfcc to your computer and use it in GitHub Desktop.
Save stv0g/076d33783c66e736cfcc to your computer and use it in GitHub Desktop.
Using additional file descriptors for input/output
/**
* Compile: gcc fd.c -o fd_copy
* Usage: fd_copy 3< input_file 4> output_file
* Result: Copies contents of input_file to output_file
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
struct stat st;
if (!fstat(3, &st) && !fstat(4, &st)) {
char b;
FILE *input = fdopen(3, "r");
FILE *output = fdopen(4, "w");
while (!feof(input)) {
fread(&b, 1, 1, input);
fwrite(&b, 1, 1, output);
}
}
else
fprintf(stderr, "oh no, please give me fds!\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment