-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;
}
Yuehai
  • 1,165
  • 1
  • 10
  • 20
  • 2
    What does the [man page](https://msdn.microsoft.com/en-us/library/5231d02a.aspx) say about the return value? And - is the file still open? You closed it in `getFileSize`. But if you *don't* close the file you are now at EOF already. – Weather Vane Dec 02 '16 at 17:15
  • It is probably the `EOF` value, which is implementation-defined, but is commonly `-1`. – Ian Abbott Dec 02 '16 at 17:20
  • 1
    Put it this way: if you open a file and move the file pointer to the end of the file, what data do you think will be read from the file next? – Weather Vane Dec 02 '16 at 17:25
  • `strcat(data,(char*)tok);` is doomed to fail anyway, a) because `data` is pointing to a 1-byte string literal which is both too small and not writable, and b) casting an `int` to a `char *` is nonsense. – Weather Vane Dec 02 '16 at 17:28

1 Answers1

0

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;
}
Yuehai
  • 1,165
  • 1
  • 10
  • 20