Read certain number of bytes from file and print to console in C
14,731
Solution 1
See fread http://www.cplusplus.com/reference/cstdio/fread/
This lets you request n bytes of size m from a file stream.
Solution 2
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);
}
Related videos on Youtube
Author by
Twisterz
Updated on June 04, 2022Comments
-
Twisterz almost 2 years
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!