gpt4 book ai didi

C: getc 返回-1

转载 作者:行者123 更新时间:2023-11-30 19:36:21 26 4
gpt4 key购买 nike

我遇到的问题是在这一行:

int tok = getc(fp);

getc 返回 -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;
}

最佳答案

我删除了 fopen 并将方法更改为:

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

关于C: getc 返回-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40937573/

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