Skip to content

Instantly share code, notes, and snippets.

@ahmadrosid
Last active April 10, 2020 09:02
Show Gist options
  • Select an option

  • Save ahmadrosid/e6474b56ddd7a7512b3993d2dc1355b3 to your computer and use it in GitHub Desktop.

Select an option

Save ahmadrosid/e6474b56ddd7a7512b3993d2dc1355b3 to your computer and use it in GitHub Desktop.

Read file to string

static char* readFile(const char* path) {
    FILE* file = fopen(path, "rb");
    if (file == NULL) {
        fprintf(stderr, "Could not open file \"%s\".\n", path);
        exit(74);
    }

    fseek(file, 0L, SEEK_END);
    size_t  fileSize = ftell(file);
    rewind(file);

    char* buffer = (char*)malloc(fileSize + 1);
    if (buffer == NULL) {
        fprintf(stderr, "Not enough memory to read \"%s\".\n", path);
        exit(74);
    }
    
    size_t bytesRead = fread(buffer, sizeof(char), fileSize, file));
    buffer[bytesRead] = '\0';

    fclose(file);
    return buffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment