/* fread example: read a complete file */
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE * pFile;
long lSize;
char * buffer;
size_t result;
pFile = fopen ( "myfile.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
/* the whole file is now loaded in the memory buffer. */
// terminate
fclose (pFile);
free (buffer);
return 0;
}
FILE * fopen ( const char * filename, const char * mode );
Open file
Opens the file whose name is specified in the parameter filename and associates it with a stream that can be identified in future operations by the FILE object whose pointer is returned. The operations that are allowed on the stream and how these are performed are defined by the mode parameter.C string containing a file access modes. It can be:
"r" | Open a file for reading. The file must exist. |
"w" | Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. |
"a" | Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist. |
"r+" | Open a file for update both reading and writing. The file must exist. |
"w+" | Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. |
"a+" | Open a file for reading and appending. All writing operations are performed at the end of the file, protecting the previous content to be overwritten. You can reposition (fseek, rewind) the internal pointer to anywhere in the file for reading, but writing operations will move it back to the end of file. The file is created if it does not exist. |
With the mode specifiers above the file is open as a text file. In order to open a file as a binary file, a "b" character has to be included in the mode string.
fseek
int fseek ( FILE * stream, long int offset, int origin );
Reposition stream position indicator
Sets the position indicator associated with the stream to a new position defined by adding offset to a reference position specified by origin.The End-of-File internal indicator of the stream is cleared after a call to this function, and all effects from previous calls to ungetc are dropped.
When using fseek on text files with offset values other than zero or values retrieved with ftell, bear in mind that on some platforms some format transformations occur with text files which can lead to unexpected repositioning.
On streams open for update (read+write), a call to fseek allows to switch between reading and writing.
Parameters
-
stream
- Pointer to a FILE object that identifies the stream. offset
- Number of bytes to offset from origin. origin
-
Position from where
offset is added. It is specified by one of the following constants defined in
<cstdio>:
SEEK_SET Beginning of file SEEK_CUR Current position of the file pointer SEEK_END End of file
Return Value
If successful, the function returns a zero value.Otherwise, it returns nonzero value.
ftell
long int ftell ( FILE * stream );
Get current position in stream
Returns the current value of the position indicator of the stream.For binary streams, the value returned corresponds to the number of bytes from the beginning of the file.
For text streams, the value is not guaranteed to be the exact number of bytes from the beginning of the file, but the value returned can still be used to restore the position indicator to this position using fseek.
Parameters
-
stream
- Pointer to a FILE object that identifies the stream.
Return Value
On success, the current value of the position indicator is returned.If an error occurs, -1L is returned, and the global variable errno is set to a positive value. This value can be interpreted by perror.
rewind
void rewind ( FILE * stream );
Set position indicator to the beginning
Sets the position indicator associated with stream to the beginning of the file.A call to rewind is equivalent to:
fseek ( stream , 0L , SEEK_SET );
except that, unlike fseek, rewind clears the error indicator.
On streams open for update (read+write), a call to rewind allows to switch between reading and writing.
Parameters
-
stream
- Pointer to a FILE object that identifies the stream.
Return Value
none
malloc
void * malloc ( size_t size );
Allocate memory block
Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.
Parameters
-
size
- Size of the memory block, in bytes.
Return Value
On success, a pointer to the memory block allocated by the function.The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
If the function failed to allocate the requested block of memory, a null pointer is returned.
fread
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
Read block of data from stream
Reads an array of count elements, each one with a size of size bytes, from the stream and stores them in the block of memory specified by ptr.The postion indicator of the stream is advanced by the total amount of bytes read.
The total amount of bytes read if successful is ( size * count).
Parameters
-
ptr
- Pointer to a block of memory with a minimum size of ( size* count) bytes. size
- Size in bytes of each element to be read. count
- Number of elements, each one with a size of size bytes. stream
- Pointer to a FILE object that specifies an input stream.
Return Value
The total number of elements successfully read is returned as a size_t object, which is an integral data type.If this number differs from the count parameter, either an error occured or the End Of File was reached.
You can use either ferror or feof to check whether an error happened or the End-of-File was reached.