cfopenfreadfseekrewind

Using rewind() returns an error, removing it allows code to run fine


Summary

I am trying to create a program that converts the contents of a file into a string.

I fseek to the end of the file then ftell to find the length in order to use the length for fread.

Problem is, I have to fseek back to the start of the file in order to read from the beginning, or else it will read starting from the end of the file, which is obviously a problem.

Problem is, using rewind() returns an error for some reason.

Note that removing the rewind() line from my code allows it to run without errors, but (null) is printed because its reading from the end of the file. This is why I'm assuming rewind() is the problem.

Code

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

int main(void) {
    FILE* dictionary = fopen("test.txt", "r");
    fseek(dictionary, 0, SEEK_END);
    int len = ftell(dictionary);
    rewind(dictionary);

    char* txt;
    fread(txt, len+1, 1, dictionary);
    printf("%s", txt);
}

Error Message

shell returned 139

Solution

  • Memory is needed in txt:

    Change:

     char* txt;
     fread(txt, len+1, 1, dictionary);
     printf("%s", txt);
    

    To

    char* txt = malloc(len+1);
    if(txt)
    {
        fread(txt, len, 1, dictionary);
        txt[len] = 0;//add terminating NULL
        printf("%s", txt);
        free(txt);
    }