[ First ]  [ Previous ]  [ Next ]  [ Last ]  [ Manuals ]


fread

Read binary data from a stream.

Compatibility:

This function is compatible with the following targets:

ANSI

BeOS

EMB/RTOS

Mac OS

Palm OS

Win32


Prototype:
#include <stdio.h>
size_t fread(void *ptr, size_t size, 
   size_t nmemb, FILE *stream);
Parameters:

Parameters for this facility are:

ptr  
void *  
A pointer to the read destination  
size  
size_t  
The size of the array pointed to  
nmemb  
size_t  
Number of elements to be read  
stream  
FILE *  
A pointer to a FILE stream  

Remarks:

The fread() function reads a block of binary or text data and updates the file position indicator. The data read from stream are stored in the array pointed to by ptr. The size and nmemb arguments describe the size of each item and the number of items to read, respectively.

The fread() function reads nmemb items unless it reaches the end-of-file or a read error occurs.

If the file is opened in update mode (+) a file cannot be read from and then written to without repositioning the file using one of the file positioning functions (fseek(), fsetpos(), or rewind()) unless the last read or write reached the end-of-file.


NOTE

On embedded/ RTOS systems this function only is implemented for stdin, stdout and stderr files.

Return

fread() returns the number of items read successfully.

See Also:

"Wide Character and Byte Character Stream Orientation"

"fgets"

"fwrite"

Example of fread() usage.:
#include <stdio.h>
#include <stdlib.h>


// define the item size in bytes
#define BUFSIZE  40

int main(void)
{
	FILE *f;
	static char s[BUFSIZE] = "The quick brown fox";
	char target[BUFSIZE];
	
	// create a new file for output and input
	if (( f = fopen("foo", "w+")) == NULL) {	
		printf("Can't create file.\n");
		exit(1);
	}
	
	// output to the stream using fwrite()
	fwrite(s, sizeof(char), BUFSIZE, f);

	// move to the beginning of the file
	rewind(f);

	// now read from the stream using fread()
	fread(target, sizeof(char), BUFSIZE, f);
	
	// output the results to the console
	puts(s);
	puts(target);

	// close the file
	fclose(f);
	
	return 0;
}

Output:
The quick brown fox
The quick brown fox


[ First ]  [ Previous ]  [ Next ]  [ Last ]  [ Manuals ]

Visit the Metrowerks website at: http://www.metrowerks.com
For assistance contact Metrowerks Technical Support at: cw_support@metrowerks.com
Copyright © 2000, Metrowerks Corp. All rights reserved.

Last updated: August 16, 2000