Reputation: 424
Hey guys I have been all over the internet and cannot seem to find a simple answer to this. What I want to do is let the user enter how many bytes they want to read (let's call it byteAmount). I want to open a file and read that many bytes from said file, then print it to console using printf. There has got to be an easy way to do this. Thanks in advance!
Upvotes: 2
Views: 19713
Reputation: 1420
Call a function with number of bytes you want to read. say read_file(byteAmount)
void read_file(int byteAmount)
{
int count = 0;
FILE *fp;
fp = fopen(file_name,"r"); //assuming file_name is global/appropriate as you requirements
if( fp == NULL )
{
perror("Error while opening the file.\n");
exit(0);
}
printf("The contents of %s file are :\n", file_name);
while( ( ch = fgetc(fp) ) != EOF || count < byteAmount)
{
Buffer[count++] = ch; // make Buffer global variable
printf("%c",ch);
}
fclose(fp);
}
Upvotes: 2
Reputation: 1917
See fread http://www.cplusplus.com/reference/cstdio/fread/
This lets you request n bytes of size m from a file stream.
Upvotes: 6