The use of fread and fwrite in the C language

fread() and fwrite() are C file direct input/output functions defined in stdio.h library. fread() use to read from a file and fwrite() use to write to a file.

fread()

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

fread (ptr, size, n, inptr)

ptr - pointer to a block of memory (store what reads from inptr)

size - size of an element

n - number of elements to read

inptr - pointer to the input file

fread() reads from where it left off last time and returns the number of elements (n) successfully read.

This is a part of a program use fread().

// 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;
fwrite()

Function fwrite() write data to the given file pointed by 4th parameter, from data pointed by 1st parameter.

fwrite (ptr, size, n, outptr)

ptr - pointer to a block of memory (contains data that write to outptr)

size - size of an element

n - number of elements to write

outptr - pointer to the output file

References:

C library function fread() C library function fwrite() C file input/output - Wikipedia

An Algorithm - View of an Amateur

There are various views on the definition of an “algorithm”. Going through some most common conception I concluded a definition to clarify what is an algorithm (still open to adjustments).

“Concise and precise, finite number of steps that can perform by a Turing machine effectively”

I used Knuths list of 5 properties that are widely accepted as the requirements of an algorithm which are finiteness, definiteness, input, output, effectiveness. [1]

Minsky[2], Savage and Gurevich[3] assert the thesis that “an algorithm can be considered to be any sequence of operations that can be simulated by a Turing-complete system”.

Thomas H. Cormen simply describe an algorithm in his book Algorithm Unlocked[4] as:

.. computer algorithm is a set of steps to accomplish a task that is described precisely enough that a computer can run it.

Footnotes:

[1]Knuth 1968, 1973

[2]Minsky 1967

[3]Gurevich 2000

[4]Cormen, Thomas H. (2013)