How to read an entire file in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

int main(void) {
    const char* filename = "d:\\data.txt";

    FILE* fp = fopen(filename, "r");
    if (!fp)
        exit(EXIT_FAILURE);

    struct stat sb;
    if (stat(filename, &sb) == -1) {
        perror("stat");
        exit(EXIT_FAILURE);
    }

    char* file_contents = malloc(sb.st_size);
    fread(file_contents, sb.st_size, 1, fp);

    printf("%s\n", file_contents);

    fclose(fp);
    free(file_contents);

    return 0;
}





/*
run

c c++ C#
NODEjs eXPRESS
jAVAsCRIPT php

*/

 



answered May 2, 2021 by avibootz

Related questions

1 answer 508 views
1 answer 253 views
1 answer 333 views
1 answer 315 views
1 answer 238 views
5 answers 460 views
2 answers 258 views
...