Skip to content

Instantly share code, notes, and snippets.

@codebrainz
Created May 28, 2013 04:30
Show Gist options
  • Select an option

  • Save codebrainz/5660538 to your computer and use it in GitHub Desktop.

Select an option

Save codebrainz/5660538 to your computer and use it in GitHub Desktop.
Read a file into a C character array. Keep in mind the file may very well contain `nul` bytes in it.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(int argc, char *argv[])
{
FILE *fp;
long size;
char *buf;
fp = fopen("testread.c", "r");
if (fp == NULL)
{
perror("opening file");
exit(EXIT_FAILURE);
}
if (fseek(fp, 0, SEEK_END) != 0)
{
perror("seeking to end of file");
exit(EXIT_FAILURE);
}
size = ftell(fp);
if (size < 0)
{
perror("telling end of file offset");
exit(EXIT_FAILURE);
}
rewind(fp);
buf = malloc(size + 1);
if (buf == NULL)
{
perror("allocating buffer");
exit(EXIT_FAILURE);
}
if (fread(buf, sizeof(char), (size_t) size, fp) != (size_t) size)
{
fputs("didn't read as much as expected, buffer "
"may contain garbage\n", stderr);
}
buf[size] = '\0';
if (fclose(fp) != 0)
perror("closing file");
printf("Read Contents:\n%s\n", buf);
free(buf);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment