文件太大时,fscanf无法读取整个文件

时间:2018-11-02 17:31:57

标签: c scanf readfile memory-reallocation

我正在尝试使用C通过fscanf读取大型文本文件(例如,一万多个单词的小说),但是每次程序将读取直到某个点并且看似到达EOF时,远离文件结尾。 这是我的代码:

void putWordsInArray(){

        FILE* fileToRead;
        char words[1024];
        int singleSize = 0;

        singleWordArray = (char**)malloc(1024*sizeof(char*));
        indexArray1 = (int*)malloc(1024*sizeof(int));
        //read the temp file automatically generated
        fileToRead = fopen("temp.txt", "r");
        while(fscanf(fileToRead, "%s", words) != EOF){

            printf("%s\n", words);
            //the following if-else statement add the word read to the single word array
            //if they are not yet in the array, or increment its count by 1 isf its already there
            int result = -1;
            result = contains(words, singleWordArray, singleSize);
            if(result == -1){
                indexArray1 = (int*)realloc(indexArray1, (singleSize + 1) * sizeof(int));
                singleWordArray = (char**)realloc(singleWordArray, (singleSize + 1) * sizeof(char*));
                singleWordArray[singleSize] = (char*)calloc((strlen(words) + 1), 1024*sizeof(char));
                strcpy(singleWordArray[singleSize], words);
                indexArray1[singleSize] = 1;
                singleSize++;

            }
            else{
                indexArray1[result] += 1;
            }
            //check if the current list contains the incoming word or not
        }
    }

有人知道这里发生了什么吗?我相信我每次都分配了足够的内存。感谢任何人的帮助。

0 个答案:

没有答案