Try the code. give the input filename as second argument.
#include<stdio.h>
#include<fcntl.h>
#define MAX_BUF_SIZE 512
int main(int argc, char **argv)
{
int fd;
int count,value;
char buf[MAX_BUF_SIZE];
if(argc < 2)
fprintf(stderr, "Usage: a.out filename\n");
else
{
fd = open(argv[1], O_RDONLY);
if(fd < 0 )
fprintf(stderr, "Error In Opening File\n");
else
{
fprintf(stdout, "Enter No of bytes to read from file %s\n",argv[1]);
fscanf(stdin,"%d",&value);
printf("value %d\n",value);
count = read(fd,buf,value);
buf[count]='\0';
if(count <=0)
fprintf(stderr, "Error In Reading from file\n");
else if(count < value)
fprintf(stdout, "Partial read data is %s\n",buf);
else if(count == value)
fprintf(stdout, "Data is: \n%s\n",buf);
else
fprintf(stderr,"Error in read.");
close(fd);
}
}
return 0;
}
The '\0' is added to buffer to avoid any garbage value with the output.
Note: fopen,fread are library fn where open, read are system call