cstdiogetc

C: getc returns -1


The problem I have is in this line:

int tok = getc(fp);

getc returns -1. Why? Thanks in advance.

#include <stdio.h>
#include <memory.h>
#include "file_reader.h"

/**
 * Opens a text file and reads the file. The text of the file is stored
 * in memory in blocks of size blockSize. The linked list with the text is
 * returned by the function. Each block should contain only complete words.
 * If a word is split by the end of the block, the last letters should be
 * moved into the next text block. Each text block must be NULL-terminated.
 * If the reading of the file fails, the program should return a meaningful
 * error message.
 */

LinkedList *read_text_file(const char* filename, int blockSize) {
    int globalByteCounter = 0;
    char *startPointer;
    LinkedList* list = LinkedList_create();
    int blockByteCounter;
    FILE* fp = fopen(filename,"r");
    int fileSize = getFileSize(fp);

    while (globalByteCounter <= fileSize){

        char* data="";
        for (blockByteCounter = 0;blockByteCounter<blockSize;blockByteCounter++){

            int tok = getc(fp);
            printf("Tok: %d",tok);
            strcat(data,(char*)tok);
        }

        LinkedList_append(list,data);
        globalByteCounter+=blockByteCounter;
    }

    return list;

}

int getFileSize(FILE* file) {
    fseek(file, 0, SEEK_END);
    long int size = ftell(file);
    fclose(file);
    return (int) size;
}

Solution

  • I removed fopen and changed the method to this:

    int getFileSize(FILE* file) {
        FILE* endOfFile = file;
        fseek(endOfFile, 0, SEEK_END);
        long int size = ftell(file);
        fseek(file, 0, SEEK_SET);
        return (int) size;
    }