Majora320
Majora320

Reputation: 1351

C function to read entire file not working

I wrote this small program to read an entire file into a char*, which I could then parse more freely than from a file. However, when I run it none of the file seems to get copied into buf, because neither printing the string or the individual chars seems to work.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    FILE *fp = fopen("/home/<not shown>/.profile", "r");
    fseek(fp, 0, SEEK_END);
    char *buf = malloc(ftell(fp) + 1);
    fseek(fp, 0, SEEK_SET);
    while ((*buf++ = fgetc(fp)) != EOF) {}
    printf("%s\n", buf);
}

I'm pretty new to c, so could you help me find an answer to this conundrum?

Upvotes: 0

Views: 65

Answers (1)

Barmar
Barmar

Reputation: 781096

When you're done with the loop, buf points to the end of the buffer, not the beginning. You should use a separate variable during the loop.

fseek(fp, 0, SEEK_END);
char *buf = malloc(ftell(fp) + 1);
fseek(fp, 0, SEEK_SET);
char *p = buf;
while (*p++ = fgetc(fp)) != EOF) {}
// Replace EOF with null terminator          
*(p-1) = '\0';

Upvotes: 1

Related Questions