Reading a text file in C -
i reading text file , trying display contents on console. here code:
#include "stdafx.h" #include <stdio.h> #include <string.h> #include <fstream> int main() { file* fp=null; char buff[100]; fp=fopen("myfile.txt","r"); if(fp==null) { printf("couldn't open file!!!\n"); } fseek(fp, 0, seek_end); size_t file_size = ftell(fp); fread(buff,file_size,1,fp); printf("data read [%s]",buff); fclose(fp); return 0; }
but redundant data being displayed on console; please point out mistake?
you need seek start of file before reading:
int main() { file* fp=null; char buff[100]; fp=fopen("myfile.txt","r"); if(fp==null) { printf("couldn't open file!!!\n"); exit(1); // <<< handle fopen failure } fseek(fp, 0, seek_end); size_t file_size = ftell(fp); fseek(fp, 0, seek_set); // <<< seek start of file fread(buff,file_size,1,fp); printf("data read [%s]",buff); fclose(fp); return 0; }
Comments
Post a Comment