2016-12-03 82 views
0

第一次迭代后,我得到了奇怪的字符串。我怀疑这可能是因为字符串终止,但我不知道如何解决它。或者我可能会以错误的方式使用malloc。从文件中读取getc后在C中获取奇怪的字符串

我很高兴为任何提示。

#include <stdio.h> 
#include <memory.h> 
#include <malloc.h> 
#include <ctype.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. 
    */ 

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

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

    char* block = malloc(sizeof strcat("","")); 

    //Loop for blocks in list 
    while (globalByteCounter <= fileSize) { 

     blockByteCounter = 0; 
     char* word = malloc(sizeof(blockSize)); 

     //loop for each block 
     while(blockByteCounter<blockSize) { 
      char tok; 

      //Building a word 
      do { 
       strcat(word, tokPointer); 
       tok = (char) getc(fp); 
       tokPointer=&tok; 
       blockByteCounter++; 
      }while (isalpha(tok)); 

      //Does this word still fit the block? 
      if (blockByteCounter + strlen(word) < blockSize) { 
       strcat(block, word); 
       //Setze Wort zurück und füge Sonderzeicehen an 
       word = strcpy(word,tokPointer); 
      } else { 
       strcpy(block,word); 
      } 
     } 
     globalByteCounter += blockByteCounter; 
     LinkedList_append(list, block); 
     free(word); 
    } 
    LinkedList_append(list,block); 
    fclose(fp); 
    free(block); 
    free(tokPointer); 
    return list; 
} 
+0

你正在使用'sizeof'函数完全错误。你需要做一些实际工作的研究。 –

回答

1

代码存在多个问题。让我来对付他们几个:

sizeof(getc(fp))

这是一样的对getc返回类型应用sizeof。在你的情况下,你在这里做的是sizeof(int)。这不是你想要的。

假设您有一个文本文件,其中您想要读取的大小是一个ASCII码,您要查找的是旧的fscanf

此类似:

strcat("","") 

但实际上更糟。 strcat("a", "b")不返回"ab"。它试图连接"b""a"并返回地址a,这是非常糟糕的,因为它不仅不能做你想做的事情,而且还会尝试修改字符串"a"。你不能修改字符串文字。

blockByteCounter未初始化。

和你有你的直觉正确的:

char* word = malloc(sizeof(blockSize)); 

如果不初始化word为空字符串,当您尝试来连接到tokPointer它,你会通过非结尾的字符串运行。不仅如此,而且tokPointer未初始化

我也不确定你为什么试图用strcat来建立一个单词。你不需要所有这些指针。一旦你知道了缓冲区所需的大小,你可以1)简单地使用fscanf来读取一个单词;或2)使用fgetc和一个很好的旧简单计数器i将每个字母放入缓冲区阵列,然后在打印前用0终止。