[英]fgetc always return -1
I'm trying to read one character at time from a text file but fgetc is returning -1 from start, which mean inside of loop is never entered.我试图从文本文件中一次读取一个字符,但 fgetc 从一开始就返回 -1,这意味着永远不会进入循环内部。 fileSize is 11 under run-time and no errors is displayed. fileSize 在运行时为 11,并且不会显示任何错误。
//main.c //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;
}
//file.txt //文件.txt
Hello World你好,世界
your read loop is located after your: fseek(file, 0, SEEK_END);您的读取循环位于您之后: fseek(file, 0, SEEK_END); statement!!!陈述!!!
you are at the end of file when you call your fgetc function!当您调用 fgetc 函数时,您处于文件末尾!
perhaps you can add fseek(file, 0, SEEK_SET);也许你可以添加 fseek(file, 0, SEEK_SET); after the ftell call?在 ftell 电话之后?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.