gpt4 book ai didi

c - 从文件读取 getc 后,C 中出现奇怪的字符串

转载 作者:行者123 更新时间:2023-11-30 15:02:45 24 4
gpt4 key购买 nike

第一次迭代后我得到了奇怪的字符串。我怀疑这可能是因为字符串终止,但我不知道如何修复它。或者我可能以错误的方式使用 malloc。

我很高兴收到任何提示。

#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(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 终止它.

关于c - 从文件读取 getc 后,C 中出现奇怪的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40950476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com