Skip to content

Instantly share code, notes, and snippets.

@jeremyheiler
Created September 4, 2013 05:05
Show Gist options
  • Save jeremyheiler/6432956 to your computer and use it in GitHub Desktop.
Save jeremyheiler/6432956 to your computer and use it in GitHub Desktop.
Print the contents of a file to stdout.
#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;
}
@jeremy-w
Copy link

jeremy-w commented Sep 4, 2013

Oh, and printf interprets that first arg as a format string, so if the file contains something like %d, you are in funland. Either use fputs or printf("%s", buf).

(Note that puts appends a newline after each call, unlike fputs, just to throw you. So puts(str) is actually basically fputs(str, stdout); putchar('\n');.)

@jeremy-w
Copy link

jeremy-w commented Sep 4, 2013

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! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment