Skip to content

Instantly share code, notes, and snippets.

@max-kamps
Created March 14, 2019 23:50
Show Gist options
  • Select an option

  • Save max-kamps/a653cc6e7a1129c5576b956ea578474d to your computer and use it in GitHub Desktop.

Select an option

Save max-kamps/a653cc6e7a1129c5576b956ea578474d to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include "lang1.h"
char * read_entire_file(char const *path);
int main(int argc, char const *argv[]);
char * read_entire_file(char const *path)
{
FILE *f = fopen(path, "rb");
if (f == NULL)
goto error;
if (fseek(f, 0, SEEK_END) != 0)
goto error_after_open;
long length = ftell(f);
if (length < 0)
goto error_after_open;
rewind(f);
char *buffer = malloc(((unsigned long) length) + 1);
if (buffer == NULL)
goto error_after_malloc;
buffer[length] = '\0';
if (length == 0)
return buffer;
else if (fread(buffer, ((unsigned long) length), 1, f) != 1)
goto error_after_malloc;
fclose(f);
return buffer;
error_after_malloc:
free(buffer);
error_after_open:
fclose(f);
error:
return NULL;
}
int main(int argc, char const *argv[])
{
if (argc != 2)
goto print_usage;
char const *program_source = read_entire_file(argv[1]);
if (program_source == NULL)
{
printf("Error while reading the input file (%s):\n ", argv[1]);
fflush(stdout);
perror("");
}
else if (program_source[0] == '\0')
{
printf("Error: The input file (%s) is empty!\n", argv[1]);
}
return 0;
print_usage:
printf("Usage: %s <file>\n", (argv[0][0] != '\0') ? argv[0] : "lang1");
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment