Reputation: 23
i've got a Textfile of Unknown Size and have to send it via Sockets from my Server to the Client in Chunks of a certain (variable Size).
How can i use Fread for that Task? I read alot about Fread but im Struggeling with the kind of Pointer i should pass that function in my Case?
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
Upvotes: 2
Views: 1398
Reputation:
To read file as chunks and send them to socket you'll have to decide a size of the chunk.
For example: 4096
is perfect size that's not too big or not too small!
We choose 4096
bytes as the chunk size. It's btw customizable.
Send the chunk data to the Client when received from file.
#include <stdio.h>
int main(ssize_t argc, char** argv)
{
// We're going to use "rb" because in (WINDOWS) you need it!
FILE* fp = fopen(argv[1], "rb");
char byte_buffer[4096];
size_t bytes_read = 0;
while(( bytes_read = fread(&byte_buffer, 4096, 1, fp) )> 0)
send_data_chunk_to_client_somehow(/* your parameters here */);
}
The text file should be read in chunks and send them to the Client.
fread(3)
― Binary stream I/O
fread(3)
is compatible with both text and binary streams, it's a part of ANSI C. The POSIXread(3)
is a equivalent to the function and faster than it.size_t fread(void* ptr, size_t size, size_t nmemb, FILE* fp);
Upvotes: -1
Reputation: 73366
How can i use fread for that task?
Simply keep sending chunks (of fixed size) from the Server to the Client, until there is nothing else to be sent by the Serve.
What kind of pointer I should pass that function in my case?
Anything.
Check fread()
's example, where the buffer
that is passed in fread()
is of type char
, and fread()
simply allows for it, since the first argument of that function is:
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
So just pass the array you are using to store the data (the chunks) to the function.
Upvotes: 0