Rapidturtle
Rapidturtle

Reputation: 237

How to use fread() to read the entire file in a loop?

I want to transfer a file via a socket in linux system. I know how to use fgetc() and EOF to do so, or first get the length of file. Is there any other option?

Upvotes: 3

Views: 17548

Answers (2)

Dulaj Chathuranga
Dulaj Chathuranga

Reputation: 1

Function fread() reads data from the given data stream(4th parameter) to an array pointed in to by a pointer(1st parameter)

fread (pointer to the block of memory, size of an element, number of elements, pointer to the input file)

fread() reads from where it left off last time and returns the number of elements successfully read. So if u do as below fread() will not go beyond that.

*You have to edit the number of elements according to the input file.

// Open input file
FILE *inptr = fopen (infile, "r");
//Check for a valid file
if (inptr == NULL)
{
    fprintf (stderr, "Could notopen %s", infile);
    return 1;
}

// Memory allocation for buffer
int *buffer = malloc(512);

// Read input file
while (fread (&buffer, 1, 512, inptr) == 512)
{
      // DO WHAT YOU NEED HERE
}

// Free memory from buffer
free(buffer);

// close infile
fclose(inptr);

return 0;

Upvotes: -2

timrau
timrau

Reputation: 23058

Check for the return value of fread(). If the return value is not equal to the 3rd parameter passed into fread(), either error happens or EOF is reached.

Upvotes: 5

Related Questions