2016-12-02 20 views
-1

У меня есть проблема в этой строке:C: ЕОКП возвращает -1

int tok = getc(fp); 

ЕОКП возвращает -1. Зачем? Спасибо заранее.

#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; 
} 
+2

, что делает [человека] (стр https://msdn.microsoft.com/en-us/library/5231d02a.aspx) говорят о возвращаемом значении? И - файл все еще открыт? Вы закрыли его в 'getFileSize'. Но если вы * не * закроете файл, вы уже находитесь в EOF. –

+0

Это, вероятно, значение 'EOF', которое определяется реализацией, но обычно' -1'. –

+1

Положите это так: если вы откроете файл и переместите указатель файла в конец файла, какие данные, по вашему мнению, будут прочитаны из файла дальше? –

ответ

0

Я удалил Еореп и изменил метод для этого:

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; 
}