I have written a program to practice using fread. I am passing a command to popen and reading the output using fread and storing into an uninitialised char array. Finally I am printing the contents of the array as well as writing it into another file. The print (output in the stdout) works fine but when I check the contents of the file, it has so many junk things after the actual output. Any reason why it works well in stdout?
Here is my code:
#include <stdio.h>
void fread_s(char *res, int res_size,char *cmd)
{
char *r;
int size;
FILE *fp=popen(cmd,"r");
if(fp==NULL)
return;
size=fread(res,res_size,1,fp);
pclose(fp);
}
int main()
{
char cmd[500];
fread_s(cmd,sizeof(cmd),"ls -lh i*");
puts(cmd);
FILE *fp=fopen("opfile","a+");
if(fp==NULL)
return;
fwrite(cmd,sizeof(cmd),1,fp);
}
fgetss->fread_s?fgets()wouldn't work iflsoutput has newlines in it.