Are you getting junk characters at the end of the buffer like Íýýýý««««««««þîþ or ²²²²½½½½½½½½ε■ε■ ? recently i wanted to read flat file using C while i was reading the file i was getting some junk at the end as said above as i am new to C programming as my main domain DotNet i was very much puzzled and after R&D i came to know what was the problem and fixed it...
FILE *fp;
long len;
char *buff;
fp=fopen("output.txt","rb");
fseek(fp,0,SEEK_END);
len=ftell(fp);
rewind(fp);
buff = NULL;
buff=(char *)malloc(len+1);
fread(buff,len,1,fp);
printf("Output is : %s",buff);
free(buff);
fclose(fp);
When we copy or read data from a file to char buffer it does not copy the terminating null so when you display the buffer, the display will continue forever running through memory until a \0 is encountered.
so easy fix is to add buff[len] = '\0'; at the end
FILE *fp;
long len;
char *buff;
fp=fopen("output.txt","rb");
fseek(fp,0,SEEK_END);
len=ftell(fp);
rewind(fp);
buff = NULL;
buff=(char *)malloc(len+1);
buff[len] = '\0';
fread(buff,len,1,fp);
printf("Output is : %s",buff);
free(buff);
fclose(fp);
The above code will copy the contents of the file to a single string buffer, so any comments on above code welcomed.
FILE *fp;
long len;
char *buff;
fp=fopen("output.txt","rb");
fseek(fp,0,SEEK_END);
len=ftell(fp);
rewind(fp);
buff = NULL;
buff=(char *)malloc(len+1);
fread(buff,len,1,fp);
printf("Output is : %s",buff);
free(buff);
fclose(fp);
When we copy or read data from a file to char buffer it does not copy the terminating null so when you display the buffer, the display will continue forever running through memory until a \0 is encountered.
so easy fix is to add buff[len] = '\0'; at the end
FILE *fp;
long len;
char *buff;
fp=fopen("output.txt","rb");
fseek(fp,0,SEEK_END);
len=ftell(fp);
rewind(fp);
buff = NULL;
buff=(char *)malloc(len+1);
buff[len] = '\0';
fread(buff,len,1,fp);
printf("Output is : %s",buff);
free(buff);
fclose(fp);
The above code will copy the contents of the file to a single string buffer, so any comments on above code welcomed.
1 comments:
Glad you solved your problem dude.
A little tip though. If you get the length of the buffer you need first and then create your char array:
char *buff = new char [len];
memset(&buff, 0, len);
//use buffer here...
delete [] buff;
The code is a little more succinct and nice C++.
Further, if you don't mind having a little spare room in your buffer for reading into, then you could just declare a static array. It's not as good a way as I've mentioned above, but it is good to know creation and initialization of the buffer can be done in a single line:
char buff[1024] = "";
This is a cool site for all things C++ - http://www.cplusplus.com/.
Post a Comment