Last active
March 14, 2016 19:07
-
-
Save stv0g/076d33783c66e736cfcc to your computer and use it in GitHub Desktop.
Using additional file descriptors for input/output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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