第一次迭代后,我得到了奇怪的字符串。我怀疑这可能是因为字符串终止,但我不知道如何解决它。或者我可能会以错误的方式使用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;
}
你正在使用'sizeof'函数完全错误。你需要做一些实际工作的研究。 –