我试图从文本文件中一次读取一个字符,但 fgetc 从一开始就返回 -1,这意味着永远不会进入循环内部。运行时fileSize为11,没有显示错误。
//main.c
char *buffer = NULL;
char* readFile(const char *path) {
FILE *file;
file = fopen(path, "r");
if (file == NULL) {
perror(path);
printf("Error: %d \n", errno);
return "Error";
}
//get size of file.
fseek(file, 0, SEEK_END);
size_t fileSize = ftell(file);
//allocate sizeof file +1.
char *buffer = (char *)malloc((fileSize +1) * sizeof(char));
//read file into string
int c;
int i = 0;
while((c = fgetc(file)) != EOF) {
buffer[i] = (char)c;
++i;
}
buffer[i] = '\0';
fclose(file);
return buffer;
}
void freeMem(void) {
free(buffer);
}
int main(void) {
const char *path = "C:\\Programmering\\TestReader\\syntax\\file.txt";
char *cStr = readFile(path);
//freeMem();
system("pause");
return 0;
}
//文件.txt
世界你好
最佳答案
您的读取循环位于以下位置之后: fseek(文件, 0, SEEK_END); 声明!!!
当您调用 fgetc 函数时,您已到达文件末尾!
也许你可以添加 fseek(file, 0, SEEK_SET);在ftell 调用之后?
关于c - fgetc 总是返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33583696/