Created
September 4, 2013 05:05
-
-
Save jeremyheiler/6432956 to your computer and use it in GitHub Desktop.
Print the contents of a file to stdout.
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
#include <stdio.h> | |
#include <errno.h> | |
int main(int argc, char **argv) | |
{ | |
if (argc == 1) return 0; | |
if (argc == 2) { | |
char *filename = argv[1]; | |
FILE *fp = fopen(filename, "r"); | |
if (!fp) { | |
perror(NULL); | |
return errno; | |
} | |
char buf[11]; | |
int read; | |
while ((read = fread(buf, sizeof(char), 10, fp)) != 0) { | |
buf[read] = '\0'; | |
printf(buf); | |
} | |
if (fp && fclose(fp) == EOF) { | |
perror(NULL); | |
return errno; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also: Once you have file reading, you can actually copy stdin to stdout by telling it to read from
/dev/fd/0
or/dev/stdin
. Fake device files are fun! :)