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 505 views
1 answer 250 views
1 answer 325 views
1 answer 308 views
1 answer 236 views
5 answers 457 views
2 answers 253 views
...