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. fileSize is 11 under run-time and no errors is displayed.
//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
Hello World
your read loop is located after your: fseek(file, 0, SEEK_END); statement!!!
you are at the end of file when you call your fgetc function!
perhaps you can add fseek(file, 0, SEEK_SET); after the ftell call?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.