Consider the following simple C program, which reads a file into a buffer and maps this buffer to the console:
#include<stdio.h> main() { FILE *file; char *buffer; unsigned long fileLen; //Open file file = fopen("HelloWorld.txt", "rb"); if (!file) { fprintf(stderr, "Unable to open file %s", "HelloWorld.txt"); return; } //Get file length fseek(file, 0, SEEK_END); fileLen=ftell(file); fseek(file, 0, SEEK_SET); //Allocate memory buffer=(char *)malloc(fileLen+1); if (!buffer) { fprintf(stderr, "Memory error!"); fclose(file); return; } //Read file contents into buffer fread(buffer, fileLen, 1, file); //Send buffer contents to stdout printf("%s\n",buffer); fclose(file); }
The file that he will read simply contains:
Hello World!
Output:
Hello World! ²²²²▌▌▌▌▌▌▌↔☺
Some time has passed since I did something meaningful in C / C ++, but usually I assume that the buffer is allocated more than necessary, but this does not seem to be the case.
fileLen ends at 12, which is accurate.
Now I think that I should just display the buffer incorrectly, but I'm not sure what I'm doing wrong.
Can someone tell me what I'm doing wrong?
c file-io
GEOCHET Nov 03 '08 at 22:43 2008-11-03 22:43
source share