stdio.h: input/outputgawronski/2019_pp/lecture_13.pdf · output operations always write data at the...

Post on 21-May-2020

12 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

stdio.h: input/output

Lecture 13

January 21, 2020

(Lecture 13) stdio.h: input/output January 21, 2020 1 / 21

Outline

fopen() - opening a filefclose() - closing a filefprintf() - write formatted data to streamfscanf() - read formatted data from streamfgetc() - get character from streamfputc() - write character to streamftell(), fseek() - file positioningfwrite() - write block of data to streamfread() - read block of data from stream

(Lecture 13) stdio.h: input/output January 21, 2020 2 / 21

fopen() - opening a file

Rediraction is too limited for many applications.

A program has no control over its files.Redirection doesn’t help of the program needs to read from two filesor write to two files at the same time.Opening a file for use as a stream requires a call of the fopenfunction.FILE *fopen (const char *fname, const char *mode); - opens thefile whose name is specified in the parameter fname and associates itwith a stream that can be identified in future operations by the FILEpointer returned.The operations that are allowed on the stream and how these areperformed are defined by the mode parameter.The returned stream is fully buffered by default.All opened files are automatically closed on normal programtermination.The running environment supports at least FOPEN MAX files opensimultaneously.

(Lecture 13) stdio.h: input/output January 21, 2020 3 / 21

fopen() - opening a file

Rediraction is too limited for many applications.A program has no control over its files.

Redirection doesn’t help of the program needs to read from two filesor write to two files at the same time.Opening a file for use as a stream requires a call of the fopenfunction.FILE *fopen (const char *fname, const char *mode); - opens thefile whose name is specified in the parameter fname and associates itwith a stream that can be identified in future operations by the FILEpointer returned.The operations that are allowed on the stream and how these areperformed are defined by the mode parameter.The returned stream is fully buffered by default.All opened files are automatically closed on normal programtermination.The running environment supports at least FOPEN MAX files opensimultaneously.

(Lecture 13) stdio.h: input/output January 21, 2020 3 / 21

fopen() - opening a file

Rediraction is too limited for many applications.A program has no control over its files.Redirection doesn’t help of the program needs to read from two filesor write to two files at the same time.

Opening a file for use as a stream requires a call of the fopenfunction.FILE *fopen (const char *fname, const char *mode); - opens thefile whose name is specified in the parameter fname and associates itwith a stream that can be identified in future operations by the FILEpointer returned.The operations that are allowed on the stream and how these areperformed are defined by the mode parameter.The returned stream is fully buffered by default.All opened files are automatically closed on normal programtermination.The running environment supports at least FOPEN MAX files opensimultaneously.

(Lecture 13) stdio.h: input/output January 21, 2020 3 / 21

fopen() - opening a file

Rediraction is too limited for many applications.A program has no control over its files.Redirection doesn’t help of the program needs to read from two filesor write to two files at the same time.Opening a file for use as a stream requires a call of the fopenfunction.

FILE *fopen (const char *fname, const char *mode); - opens thefile whose name is specified in the parameter fname and associates itwith a stream that can be identified in future operations by the FILEpointer returned.The operations that are allowed on the stream and how these areperformed are defined by the mode parameter.The returned stream is fully buffered by default.All opened files are automatically closed on normal programtermination.The running environment supports at least FOPEN MAX files opensimultaneously.

(Lecture 13) stdio.h: input/output January 21, 2020 3 / 21

fopen() - opening a file

Rediraction is too limited for many applications.A program has no control over its files.Redirection doesn’t help of the program needs to read from two filesor write to two files at the same time.Opening a file for use as a stream requires a call of the fopenfunction.FILE *fopen (const char *fname, const char *mode); - opens thefile whose name is specified in the parameter fname and associates itwith a stream that can be identified in future operations by the FILEpointer returned.

The operations that are allowed on the stream and how these areperformed are defined by the mode parameter.The returned stream is fully buffered by default.All opened files are automatically closed on normal programtermination.The running environment supports at least FOPEN MAX files opensimultaneously.

(Lecture 13) stdio.h: input/output January 21, 2020 3 / 21

fopen() - opening a file

Rediraction is too limited for many applications.A program has no control over its files.Redirection doesn’t help of the program needs to read from two filesor write to two files at the same time.Opening a file for use as a stream requires a call of the fopenfunction.FILE *fopen (const char *fname, const char *mode); - opens thefile whose name is specified in the parameter fname and associates itwith a stream that can be identified in future operations by the FILEpointer returned.The operations that are allowed on the stream and how these areperformed are defined by the mode parameter.

The returned stream is fully buffered by default.All opened files are automatically closed on normal programtermination.The running environment supports at least FOPEN MAX files opensimultaneously.

(Lecture 13) stdio.h: input/output January 21, 2020 3 / 21

fopen() - opening a file

Rediraction is too limited for many applications.A program has no control over its files.Redirection doesn’t help of the program needs to read from two filesor write to two files at the same time.Opening a file for use as a stream requires a call of the fopenfunction.FILE *fopen (const char *fname, const char *mode); - opens thefile whose name is specified in the parameter fname and associates itwith a stream that can be identified in future operations by the FILEpointer returned.The operations that are allowed on the stream and how these areperformed are defined by the mode parameter.The returned stream is fully buffered by default.

All opened files are automatically closed on normal programtermination.The running environment supports at least FOPEN MAX files opensimultaneously.

(Lecture 13) stdio.h: input/output January 21, 2020 3 / 21

fopen() - opening a file

Rediraction is too limited for many applications.A program has no control over its files.Redirection doesn’t help of the program needs to read from two filesor write to two files at the same time.Opening a file for use as a stream requires a call of the fopenfunction.FILE *fopen (const char *fname, const char *mode); - opens thefile whose name is specified in the parameter fname and associates itwith a stream that can be identified in future operations by the FILEpointer returned.The operations that are allowed on the stream and how these areperformed are defined by the mode parameter.The returned stream is fully buffered by default.All opened files are automatically closed on normal programtermination.

The running environment supports at least FOPEN MAX files opensimultaneously.

(Lecture 13) stdio.h: input/output January 21, 2020 3 / 21

fopen() - opening a file

Rediraction is too limited for many applications.A program has no control over its files.Redirection doesn’t help of the program needs to read from two filesor write to two files at the same time.Opening a file for use as a stream requires a call of the fopenfunction.FILE *fopen (const char *fname, const char *mode); - opens thefile whose name is specified in the parameter fname and associates itwith a stream that can be identified in future operations by the FILEpointer returned.The operations that are allowed on the stream and how these areperformed are defined by the mode parameter.The returned stream is fully buffered by default.All opened files are automatically closed on normal programtermination.The running environment supports at least FOPEN MAX files opensimultaneously.(Lecture 13) stdio.h: input/output January 21, 2020 3 / 21

fopen() - access modes

C string containing a file access mode:

”r” - read:

Open file for input operations.The file must exist.

”w” - write:

Create an empty file for output operations.If a file with the same name already exists, its contents are discardedand the file is treated as a new empty file.

”a” - append:

Open file for output at the end of a file.Output operations always write data at the end of the file, expanding it.The file is created if it does not exist.

”r+” - read/update:

Open a file for update (both for input and output).The file must exist.

(Lecture 13) stdio.h: input/output January 21, 2020 4 / 21

fopen() - access modes

C string containing a file access mode:”r” - read:

Open file for input operations.The file must exist.

”w” - write:

Create an empty file for output operations.If a file with the same name already exists, its contents are discardedand the file is treated as a new empty file.

”a” - append:

Open file for output at the end of a file.Output operations always write data at the end of the file, expanding it.The file is created if it does not exist.

”r+” - read/update:

Open a file for update (both for input and output).The file must exist.

(Lecture 13) stdio.h: input/output January 21, 2020 4 / 21

fopen() - access modes

C string containing a file access mode:”r” - read:

Open file for input operations.

The file must exist.

”w” - write:

Create an empty file for output operations.If a file with the same name already exists, its contents are discardedand the file is treated as a new empty file.

”a” - append:

Open file for output at the end of a file.Output operations always write data at the end of the file, expanding it.The file is created if it does not exist.

”r+” - read/update:

Open a file for update (both for input and output).The file must exist.

(Lecture 13) stdio.h: input/output January 21, 2020 4 / 21

fopen() - access modes

C string containing a file access mode:”r” - read:

Open file for input operations.The file must exist.

”w” - write:

Create an empty file for output operations.If a file with the same name already exists, its contents are discardedand the file is treated as a new empty file.

”a” - append:

Open file for output at the end of a file.Output operations always write data at the end of the file, expanding it.The file is created if it does not exist.

”r+” - read/update:

Open a file for update (both for input and output).The file must exist.

(Lecture 13) stdio.h: input/output January 21, 2020 4 / 21

fopen() - access modes

C string containing a file access mode:”r” - read:

Open file for input operations.The file must exist.

”w” - write:

Create an empty file for output operations.If a file with the same name already exists, its contents are discardedand the file is treated as a new empty file.

”a” - append:

Open file for output at the end of a file.Output operations always write data at the end of the file, expanding it.The file is created if it does not exist.

”r+” - read/update:

Open a file for update (both for input and output).The file must exist.

(Lecture 13) stdio.h: input/output January 21, 2020 4 / 21

fopen() - access modes

C string containing a file access mode:”r” - read:

Open file for input operations.The file must exist.

”w” - write:Create an empty file for output operations.

If a file with the same name already exists, its contents are discardedand the file is treated as a new empty file.

”a” - append:

Open file for output at the end of a file.Output operations always write data at the end of the file, expanding it.The file is created if it does not exist.

”r+” - read/update:

Open a file for update (both for input and output).The file must exist.

(Lecture 13) stdio.h: input/output January 21, 2020 4 / 21

fopen() - access modes

C string containing a file access mode:”r” - read:

Open file for input operations.The file must exist.

”w” - write:Create an empty file for output operations.If a file with the same name already exists, its contents are discardedand the file is treated as a new empty file.

”a” - append:

Open file for output at the end of a file.Output operations always write data at the end of the file, expanding it.The file is created if it does not exist.

”r+” - read/update:

Open a file for update (both for input and output).The file must exist.

(Lecture 13) stdio.h: input/output January 21, 2020 4 / 21

fopen() - access modes

C string containing a file access mode:”r” - read:

Open file for input operations.The file must exist.

”w” - write:Create an empty file for output operations.If a file with the same name already exists, its contents are discardedand the file is treated as a new empty file.

”a” - append:

Open file for output at the end of a file.Output operations always write data at the end of the file, expanding it.The file is created if it does not exist.

”r+” - read/update:

Open a file for update (both for input and output).The file must exist.

(Lecture 13) stdio.h: input/output January 21, 2020 4 / 21

fopen() - access modes

C string containing a file access mode:”r” - read:

Open file for input operations.The file must exist.

”w” - write:Create an empty file for output operations.If a file with the same name already exists, its contents are discardedand the file is treated as a new empty file.

”a” - append:Open file for output at the end of a file.

Output operations always write data at the end of the file, expanding it.The file is created if it does not exist.

”r+” - read/update:

Open a file for update (both for input and output).The file must exist.

(Lecture 13) stdio.h: input/output January 21, 2020 4 / 21

fopen() - access modes

C string containing a file access mode:”r” - read:

Open file for input operations.The file must exist.

”w” - write:Create an empty file for output operations.If a file with the same name already exists, its contents are discardedand the file is treated as a new empty file.

”a” - append:Open file for output at the end of a file.Output operations always write data at the end of the file, expanding it.

The file is created if it does not exist.

”r+” - read/update:

Open a file for update (both for input and output).The file must exist.

(Lecture 13) stdio.h: input/output January 21, 2020 4 / 21

fopen() - access modes

C string containing a file access mode:”r” - read:

Open file for input operations.The file must exist.

”w” - write:Create an empty file for output operations.If a file with the same name already exists, its contents are discardedand the file is treated as a new empty file.

”a” - append:Open file for output at the end of a file.Output operations always write data at the end of the file, expanding it.The file is created if it does not exist.

”r+” - read/update:

Open a file for update (both for input and output).The file must exist.

(Lecture 13) stdio.h: input/output January 21, 2020 4 / 21

fopen() - access modes

C string containing a file access mode:”r” - read:

Open file for input operations.The file must exist.

”w” - write:Create an empty file for output operations.If a file with the same name already exists, its contents are discardedand the file is treated as a new empty file.

”a” - append:Open file for output at the end of a file.Output operations always write data at the end of the file, expanding it.The file is created if it does not exist.

”r+” - read/update:

Open a file for update (both for input and output).The file must exist.

(Lecture 13) stdio.h: input/output January 21, 2020 4 / 21

fopen() - access modes

C string containing a file access mode:”r” - read:

Open file for input operations.The file must exist.

”w” - write:Create an empty file for output operations.If a file with the same name already exists, its contents are discardedand the file is treated as a new empty file.

”a” - append:Open file for output at the end of a file.Output operations always write data at the end of the file, expanding it.The file is created if it does not exist.

”r+” - read/update:Open a file for update (both for input and output).

The file must exist.

(Lecture 13) stdio.h: input/output January 21, 2020 4 / 21

fopen() - access modes

C string containing a file access mode:”r” - read:

Open file for input operations.The file must exist.

”w” - write:Create an empty file for output operations.If a file with the same name already exists, its contents are discardedand the file is treated as a new empty file.

”a” - append:Open file for output at the end of a file.Output operations always write data at the end of the file, expanding it.The file is created if it does not exist.

”r+” - read/update:Open a file for update (both for input and output).The file must exist.

(Lecture 13) stdio.h: input/output January 21, 2020 4 / 21

fopen() - access modes

”w+” - write/update:

Create an empty file and open it for update (both for input andoutput).If a file with the same name already exists its contents are discardedand the file is treated as a new empty file.

”a+” - append/update:

Open a file for update (both for input and output) with all outputoperations writing data at the end of the 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 beincluded in the mode string.

(Lecture 13) stdio.h: input/output January 21, 2020 5 / 21

fopen() - access modes

”w+” - write/update:Create an empty file and open it for update (both for input andoutput).

If a file with the same name already exists its contents are discardedand the file is treated as a new empty file.

”a+” - append/update:

Open a file for update (both for input and output) with all outputoperations writing data at the end of the 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 beincluded in the mode string.

(Lecture 13) stdio.h: input/output January 21, 2020 5 / 21

fopen() - access modes

”w+” - write/update:Create an empty file and open it for update (both for input andoutput).If a file with the same name already exists its contents are discardedand the file is treated as a new empty file.

”a+” - append/update:

Open a file for update (both for input and output) with all outputoperations writing data at the end of the 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 beincluded in the mode string.

(Lecture 13) stdio.h: input/output January 21, 2020 5 / 21

fopen() - access modes

”w+” - write/update:Create an empty file and open it for update (both for input andoutput).If a file with the same name already exists its contents are discardedand the file is treated as a new empty file.

”a+” - append/update:

Open a file for update (both for input and output) with all outputoperations writing data at the end of the 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 beincluded in the mode string.

(Lecture 13) stdio.h: input/output January 21, 2020 5 / 21

fopen() - access modes

”w+” - write/update:Create an empty file and open it for update (both for input andoutput).If a file with the same name already exists its contents are discardedand the file is treated as a new empty file.

”a+” - append/update:Open a file for update (both for input and output) with all outputoperations writing data at the end of the 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 beincluded in the mode string.

(Lecture 13) stdio.h: input/output January 21, 2020 5 / 21

fopen() - access modes

”w+” - write/update:Create an empty file and open it for update (both for input andoutput).If a file with the same name already exists its contents are discardedand the file is treated as a new empty file.

”a+” - append/update:Open a file for update (both for input and output) with all outputoperations writing data at the end of the 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 beincluded in the mode string.

(Lecture 13) stdio.h: input/output January 21, 2020 5 / 21

fopen() - access modes

”w+” - write/update:Create an empty file and open it for update (both for input andoutput).If a file with the same name already exists its contents are discardedand the file is treated as a new empty file.

”a+” - append/update:Open a file for update (both for input and output) with all outputoperations writing data at the end of the 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 beincluded in the mode string.

(Lecture 13) stdio.h: input/output January 21, 2020 5 / 21

fopen() - access modes

”w+” - write/update:Create an empty file and open it for update (both for input andoutput).If a file with the same name already exists its contents are discardedand the file is treated as a new empty file.

”a+” - append/update:Open a file for update (both for input and output) with all outputoperations writing data at the end of the 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 beincluded in the mode string.

(Lecture 13) stdio.h: input/output January 21, 2020 5 / 21

fopen() - access modes

This additional ”b” character can either be appended at the end ofthe string (”rb”, ”wb”, ”ab”, ”r+b”, ”w+b”, ”a+b”) or be insertedbetween the letter and the ”+” sign for the mixed modes (”rb+”,”wb+”, ”ab+”).

For files open for update (those which include a ”+” sign), on whichboth input and output operations are allowed, the stream shall beflushed (fflush) or repositioned (fseek, fsetpos, rewind) before areading operation that follows a writing operation.

The stream shall be repositioned (fseek, fsetpos, rewind) before awriting operation that follows a reading operation (whenever thatoperation did not reach the end-of-file).

(Lecture 13) stdio.h: input/output January 21, 2020 6 / 21

fopen() - access modes

This additional ”b” character can either be appended at the end ofthe string (”rb”, ”wb”, ”ab”, ”r+b”, ”w+b”, ”a+b”) or be insertedbetween the letter and the ”+” sign for the mixed modes (”rb+”,”wb+”, ”ab+”).

For files open for update (those which include a ”+” sign), on whichboth input and output operations are allowed, the stream shall beflushed (fflush) or repositioned (fseek, fsetpos, rewind) before areading operation that follows a writing operation.

The stream shall be repositioned (fseek, fsetpos, rewind) before awriting operation that follows a reading operation (whenever thatoperation did not reach the end-of-file).

(Lecture 13) stdio.h: input/output January 21, 2020 6 / 21

fopen() - access modes

This additional ”b” character can either be appended at the end ofthe string (”rb”, ”wb”, ”ab”, ”r+b”, ”w+b”, ”a+b”) or be insertedbetween the letter and the ”+” sign for the mixed modes (”rb+”,”wb+”, ”ab+”).

For files open for update (those which include a ”+” sign), on whichboth input and output operations are allowed, the stream shall beflushed (fflush) or repositioned (fseek, fsetpos, rewind) before areading operation that follows a writing operation.

The stream shall be repositioned (fseek, fsetpos, rewind) before awriting operation that follows a reading operation (whenever thatoperation did not reach the end-of-file).

(Lecture 13) stdio.h: input/output January 21, 2020 6 / 21

fopen() - opening a file

If the file is successfully opened, the function returns a pointer to aFILE object that can be used to identify the stream on futureoperations. Otherwise, a null pointer is returned.

A typical call of fopen

// opens test.dat for readingFILE *fp = fopen("test.dat", "r");if(!fp){

printf("Cannot open the file.\n");exit(EXIT_FAILURE);

}...// Closing the file.

Never assume that a file can be opened; always test the return valueof fopen to make it’s not a null pointer.When fopen can’t open a file, perhaps the file doesn’t exists, or it’sin the wrong place or we don’t have permissions to open it.

(Lecture 13) stdio.h: input/output January 21, 2020 7 / 21

fopen() - opening a file

If the file is successfully opened, the function returns a pointer to aFILE object that can be used to identify the stream on futureoperations. Otherwise, a null pointer is returned.A typical call of fopen

// opens test.dat for readingFILE *fp = fopen("test.dat", "r");if(!fp){

printf("Cannot open the file.\n");exit(EXIT_FAILURE);

}...// Closing the file.

Never assume that a file can be opened; always test the return valueof fopen to make it’s not a null pointer.When fopen can’t open a file, perhaps the file doesn’t exists, or it’sin the wrong place or we don’t have permissions to open it.

(Lecture 13) stdio.h: input/output January 21, 2020 7 / 21

fopen() - opening a file

If the file is successfully opened, the function returns a pointer to aFILE object that can be used to identify the stream on futureoperations. Otherwise, a null pointer is returned.A typical call of fopen

// opens test.dat for readingFILE *fp = fopen("test.dat", "r");if(!fp){

printf("Cannot open the file.\n");exit(EXIT_FAILURE);

}...// Closing the file.

Never assume that a file can be opened; always test the return valueof fopen to make it’s not a null pointer.

When fopen can’t open a file, perhaps the file doesn’t exists, or it’sin the wrong place or we don’t have permissions to open it.

(Lecture 13) stdio.h: input/output January 21, 2020 7 / 21

fopen() - opening a file

If the file is successfully opened, the function returns a pointer to aFILE object that can be used to identify the stream on futureoperations. Otherwise, a null pointer is returned.A typical call of fopen

// opens test.dat for readingFILE *fp = fopen("test.dat", "r");if(!fp){

printf("Cannot open the file.\n");exit(EXIT_FAILURE);

}...// Closing the file.

Never assume that a file can be opened; always test the return valueof fopen to make it’s not a null pointer.When fopen can’t open a file, perhaps the file doesn’t exists, or it’sin the wrong place or we don’t have permissions to open it.(Lecture 13) stdio.h: input/output January 21, 2020 7 / 21

fclose() - closing a file

The fclose function allows a program to close a file that it’s no longerusing.

int fclose(FILE *stream); - closes the file associated with thestream.All internal buffers associated with the stream are disassociated fromit and flushed:

the content of any unwritten output buffer is written,the content of any unread input buffer is discarded.

If the stream is successfully closed, a zero value is returned. Onfailure, EOF is returned.

Why do we need to close files?

If input/output operations are buffered and the fclose function is notcalled, this can lead to data loss.

(Lecture 13) stdio.h: input/output January 21, 2020 8 / 21

fclose() - closing a file

The fclose function allows a program to close a file that it’s no longerusing.

int fclose(FILE *stream); - closes the file associated with thestream.

All internal buffers associated with the stream are disassociated fromit and flushed:

the content of any unwritten output buffer is written,the content of any unread input buffer is discarded.

If the stream is successfully closed, a zero value is returned. Onfailure, EOF is returned.

Why do we need to close files?

If input/output operations are buffered and the fclose function is notcalled, this can lead to data loss.

(Lecture 13) stdio.h: input/output January 21, 2020 8 / 21

fclose() - closing a file

The fclose function allows a program to close a file that it’s no longerusing.

int fclose(FILE *stream); - closes the file associated with thestream.All internal buffers associated with the stream are disassociated fromit and flushed:

the content of any unwritten output buffer is written,the content of any unread input buffer is discarded.

If the stream is successfully closed, a zero value is returned. Onfailure, EOF is returned.

Why do we need to close files?

If input/output operations are buffered and the fclose function is notcalled, this can lead to data loss.

(Lecture 13) stdio.h: input/output January 21, 2020 8 / 21

fclose() - closing a file

The fclose function allows a program to close a file that it’s no longerusing.

int fclose(FILE *stream); - closes the file associated with thestream.All internal buffers associated with the stream are disassociated fromit and flushed:

the content of any unwritten output buffer is written,

the content of any unread input buffer is discarded.

If the stream is successfully closed, a zero value is returned. Onfailure, EOF is returned.

Why do we need to close files?

If input/output operations are buffered and the fclose function is notcalled, this can lead to data loss.

(Lecture 13) stdio.h: input/output January 21, 2020 8 / 21

fclose() - closing a file

The fclose function allows a program to close a file that it’s no longerusing.

int fclose(FILE *stream); - closes the file associated with thestream.All internal buffers associated with the stream are disassociated fromit and flushed:

the content of any unwritten output buffer is written,the content of any unread input buffer is discarded.

If the stream is successfully closed, a zero value is returned. Onfailure, EOF is returned.

Why do we need to close files?

If input/output operations are buffered and the fclose function is notcalled, this can lead to data loss.

(Lecture 13) stdio.h: input/output January 21, 2020 8 / 21

fclose() - closing a file

The fclose function allows a program to close a file that it’s no longerusing.

int fclose(FILE *stream); - closes the file associated with thestream.All internal buffers associated with the stream are disassociated fromit and flushed:

the content of any unwritten output buffer is written,the content of any unread input buffer is discarded.

If the stream is successfully closed, a zero value is returned. Onfailure, EOF is returned.

Why do we need to close files?

If input/output operations are buffered and the fclose function is notcalled, this can lead to data loss.

(Lecture 13) stdio.h: input/output January 21, 2020 8 / 21

fclose() - closing a file

The fclose function allows a program to close a file that it’s no longerusing.

int fclose(FILE *stream); - closes the file associated with thestream.All internal buffers associated with the stream are disassociated fromit and flushed:

the content of any unwritten output buffer is written,the content of any unread input buffer is discarded.

If the stream is successfully closed, a zero value is returned. Onfailure, EOF is returned.

Why do we need to close files?

If input/output operations are buffered and the fclose function is notcalled, this can lead to data loss.

(Lecture 13) stdio.h: input/output January 21, 2020 8 / 21

fclose() - closing a file

The fclose function allows a program to close a file that it’s no longerusing.

int fclose(FILE *stream); - closes the file associated with thestream.All internal buffers associated with the stream are disassociated fromit and flushed:

the content of any unwritten output buffer is written,the content of any unread input buffer is discarded.

If the stream is successfully closed, a zero value is returned. Onfailure, EOF is returned.

Why do we need to close files?

If input/output operations are buffered and the fclose function is notcalled, this can lead to data loss.

(Lecture 13) stdio.h: input/output January 21, 2020 8 / 21

fclose() - closing a file

Example:

char fname []="test.dat";FILE *fp = fopen(fname , "w");if(!fp){

printf("Cannot open the file: %s\n", fname);exit(EXIT_FAILURE);

}...fclose(fp);

(Lecture 13) stdio.h: input/output January 21, 2020 9 / 21

fprintf() - write formatted data to streamint fprintf(FILE *stream, const char *format, ...); - writes thestring pointed by format to the stream.

fprintf require a format string containing ordinary characters and/orconversion specifications. A format specifier follows this prototype:

%[flags ][width][.precision][length]specifier

Writing array to stream

#define SIZE 10...double arr[SIZE];...FILE *pFile = fopen("myfile.txt", "w");if(pFile){

for(double *pt = arr; pt < arr+SIZE; pt++)fprintf(pFile , "%0.3lf\n", *pt);

fclose(pFile);}

(Lecture 13) stdio.h: input/output January 21, 2020 10 / 21

fprintf() - write formatted data to streamint fprintf(FILE *stream, const char *format, ...); - writes thestring pointed by format to the stream.fprintf require a format string containing ordinary characters and/orconversion specifications. A format specifier follows this prototype:

%[flags ][width][.precision][length]specifier

Writing array to stream

#define SIZE 10...double arr[SIZE];...FILE *pFile = fopen("myfile.txt", "w");if(pFile){

for(double *pt = arr; pt < arr+SIZE; pt++)fprintf(pFile , "%0.3lf\n", *pt);

fclose(pFile);}

(Lecture 13) stdio.h: input/output January 21, 2020 10 / 21

fprintf() - write formatted data to streamint fprintf(FILE *stream, const char *format, ...); - writes thestring pointed by format to the stream.fprintf require a format string containing ordinary characters and/orconversion specifications. A format specifier follows this prototype:

%[flags ][width][.precision][length]specifier

Writing array to stream

#define SIZE 10...double arr[SIZE];...FILE *pFile = fopen("myfile.txt", "w");if(pFile){

for(double *pt = arr; pt < arr+SIZE; pt++)fprintf(pFile , "%0.3lf\n", *pt);

fclose(pFile);}(Lecture 13) stdio.h: input/output January 21, 2020 10 / 21

fscanf() - read formatted data from stream

int fscanf(FILE *stream, const char *format, ...); - reads datafrom the stream and stores them according to the parameter formatinto the locations pointed by the additional arguments.

A format specifier for fscanf follows this prototype:

%[∗][width][length]specifier

String that contains a sequence of characters that control howcharacters extracted from the stream are treated:

Format specifiers is used to specify the type and format of the datato be retrieved from the stream and stored into the locations pointedby the additional arguments.Whitespace character: the function will read and ignore anywhitespace characters encountered before the next non-whitespacecharacter (whitespace characters include spaces, newline and tabcharacters).A single whitespace in the format string validates any quantity ofwhitespace characters extracted from the stream (including none).

(Lecture 13) stdio.h: input/output January 21, 2020 11 / 21

fscanf() - read formatted data from stream

int fscanf(FILE *stream, const char *format, ...); - reads datafrom the stream and stores them according to the parameter formatinto the locations pointed by the additional arguments.

A format specifier for fscanf follows this prototype:

%[∗][width][length]specifier

String that contains a sequence of characters that control howcharacters extracted from the stream are treated:

Format specifiers is used to specify the type and format of the datato be retrieved from the stream and stored into the locations pointedby the additional arguments.Whitespace character: the function will read and ignore anywhitespace characters encountered before the next non-whitespacecharacter (whitespace characters include spaces, newline and tabcharacters).A single whitespace in the format string validates any quantity ofwhitespace characters extracted from the stream (including none).

(Lecture 13) stdio.h: input/output January 21, 2020 11 / 21

fscanf() - read formatted data from stream

int fscanf(FILE *stream, const char *format, ...); - reads datafrom the stream and stores them according to the parameter formatinto the locations pointed by the additional arguments.

A format specifier for fscanf follows this prototype:

%[∗][width][length]specifier

String that contains a sequence of characters that control howcharacters extracted from the stream are treated:

Format specifiers is used to specify the type and format of the datato be retrieved from the stream and stored into the locations pointedby the additional arguments.Whitespace character: the function will read and ignore anywhitespace characters encountered before the next non-whitespacecharacter (whitespace characters include spaces, newline and tabcharacters).A single whitespace in the format string validates any quantity ofwhitespace characters extracted from the stream (including none).

(Lecture 13) stdio.h: input/output January 21, 2020 11 / 21

fscanf() - read formatted data from stream

int fscanf(FILE *stream, const char *format, ...); - reads datafrom the stream and stores them according to the parameter formatinto the locations pointed by the additional arguments.

A format specifier for fscanf follows this prototype:

%[∗][width][length]specifier

String that contains a sequence of characters that control howcharacters extracted from the stream are treated:

Format specifiers is used to specify the type and format of the datato be retrieved from the stream and stored into the locations pointedby the additional arguments.

Whitespace character: the function will read and ignore anywhitespace characters encountered before the next non-whitespacecharacter (whitespace characters include spaces, newline and tabcharacters).A single whitespace in the format string validates any quantity ofwhitespace characters extracted from the stream (including none).

(Lecture 13) stdio.h: input/output January 21, 2020 11 / 21

fscanf() - read formatted data from stream

int fscanf(FILE *stream, const char *format, ...); - reads datafrom the stream and stores them according to the parameter formatinto the locations pointed by the additional arguments.

A format specifier for fscanf follows this prototype:

%[∗][width][length]specifier

String that contains a sequence of characters that control howcharacters extracted from the stream are treated:

Format specifiers is used to specify the type and format of the datato be retrieved from the stream and stored into the locations pointedby the additional arguments.Whitespace character: the function will read and ignore anywhitespace characters encountered before the next non-whitespacecharacter (whitespace characters include spaces, newline and tabcharacters).

A single whitespace in the format string validates any quantity ofwhitespace characters extracted from the stream (including none).

(Lecture 13) stdio.h: input/output January 21, 2020 11 / 21

fscanf() - read formatted data from stream

int fscanf(FILE *stream, const char *format, ...); - reads datafrom the stream and stores them according to the parameter formatinto the locations pointed by the additional arguments.

A format specifier for fscanf follows this prototype:

%[∗][width][length]specifier

String that contains a sequence of characters that control howcharacters extracted from the stream are treated:

Format specifiers is used to specify the type and format of the datato be retrieved from the stream and stored into the locations pointedby the additional arguments.Whitespace character: the function will read and ignore anywhitespace characters encountered before the next non-whitespacecharacter (whitespace characters include spaces, newline and tabcharacters).A single whitespace in the format string validates any quantity ofwhitespace characters extracted from the stream (including none).

(Lecture 13) stdio.h: input/output January 21, 2020 11 / 21

fscanf() - read formatted data from stream

Non-whitespace character, except format specifier (%): Anycharacter that is not either a whitespace character or part of a formatspecifier causes the function to read the next character from thestream, compare it to this non-whitespace character and if it matches,it is discarded and the function continues with the next character offormat.

If the character does not match, the function fails, returning andleaving subsequent characters of the stream unread.

(Lecture 13) stdio.h: input/output January 21, 2020 12 / 21

fscanf() - read formatted data from stream

Non-whitespace character, except format specifier (%): Anycharacter that is not either a whitespace character or part of a formatspecifier causes the function to read the next character from thestream, compare it to this non-whitespace character and if it matches,it is discarded and the function continues with the next character offormat.If the character does not match, the function fails, returning andleaving subsequent characters of the stream unread.

(Lecture 13) stdio.h: input/output January 21, 2020 12 / 21

fscanf() - read formatted data from stream

Reading array from stream

#define SIZE 10...double arr[SIZE];...FILE *pFile = fopen("myfile.txt", "r");if(pFile){

for(double *pt = arr; pt < arr+SIZE; pt++)fscanf(pFile , "%lf", pt);

fclose (pFile);}

(Lecture 13) stdio.h: input/output January 21, 2020 13 / 21

fgetc() - get character from stream

int fgetc(FILE *stream); - returns the character currently pointedby the internal file position indicator of the specified stream. Theinternal file position indicator is then advanced to the next character.

If the stream is at the end-of-file when called, the function returnsEOF.

FILE *pFile = fopen("myfile.txt","r");if(! pFile) perror("Error opening file");else{

int c;do{

c = fgetc(pFile);...

}while(c != EOF);fclose(pFile);}

(Lecture 13) stdio.h: input/output January 21, 2020 14 / 21

fgetc() - get character from stream

int fgetc(FILE *stream); - returns the character currently pointedby the internal file position indicator of the specified stream. Theinternal file position indicator is then advanced to the next character.

If the stream is at the end-of-file when called, the function returnsEOF.

FILE *pFile = fopen("myfile.txt","r");if(! pFile) perror("Error opening file");else{

int c;do{

c = fgetc(pFile);...

}while(c != EOF);fclose(pFile);}

(Lecture 13) stdio.h: input/output January 21, 2020 14 / 21

fgetc() - get character from stream

int fgetc(FILE *stream); - returns the character currently pointedby the internal file position indicator of the specified stream. Theinternal file position indicator is then advanced to the next character.

If the stream is at the end-of-file when called, the function returnsEOF.

FILE *pFile = fopen("myfile.txt","r");if(! pFile) perror("Error opening file");else{

int c;do{

c = fgetc(pFile);...

}while(c != EOF);fclose(pFile);}

(Lecture 13) stdio.h: input/output January 21, 2020 14 / 21

perror() - print error message

void perror ( const char * str ); - interprets the value of errno asan error message, and prints it to stderr (the standard error outputstream, usually the console), optionally preceding it with the custommessage specified in str.

errno is an integral variable whose value describes the error conditionor diagnostic information produced by a call to a library function.

Any function of the C standard library may set a value for errno.

Idiom - to read characters from a file, one by one, until end-of-fileoccurs.

while( ( c = fgetc(pFile) ) != EOF){...}

(Lecture 13) stdio.h: input/output January 21, 2020 15 / 21

perror() - print error message

void perror ( const char * str ); - interprets the value of errno asan error message, and prints it to stderr (the standard error outputstream, usually the console), optionally preceding it with the custommessage specified in str.

errno is an integral variable whose value describes the error conditionor diagnostic information produced by a call to a library function.

Any function of the C standard library may set a value for errno.

Idiom - to read characters from a file, one by one, until end-of-fileoccurs.

while( ( c = fgetc(pFile) ) != EOF){...}

(Lecture 13) stdio.h: input/output January 21, 2020 15 / 21

perror() - print error message

void perror ( const char * str ); - interprets the value of errno asan error message, and prints it to stderr (the standard error outputstream, usually the console), optionally preceding it with the custommessage specified in str.

errno is an integral variable whose value describes the error conditionor diagnostic information produced by a call to a library function.

Any function of the C standard library may set a value for errno.

Idiom - to read characters from a file, one by one, until end-of-fileoccurs.

while( ( c = fgetc(pFile) ) != EOF){...}

(Lecture 13) stdio.h: input/output January 21, 2020 15 / 21

perror() - print error message

void perror ( const char * str ); - interprets the value of errno asan error message, and prints it to stderr (the standard error outputstream, usually the console), optionally preceding it with the custommessage specified in str.

errno is an integral variable whose value describes the error conditionor diagnostic information produced by a call to a library function.

Any function of the C standard library may set a value for errno.

Idiom - to read characters from a file, one by one, until end-of-fileoccurs.

while( ( c = fgetc(pFile) ) != EOF){...}

(Lecture 13) stdio.h: input/output January 21, 2020 15 / 21

fputc() - write character to stream

int fputc(int character, FILE *stream); - writes a character to thestream and advances the position indicator.

Copying a file:

FILE *in = fopen(argv[1], "rb");if(!in) exit(EXIT_FAILURE);

FILE *out = fopen(argv[2], "wb");if(!out){

fclose(in);exit(EXIT_FAILURE);

}int ch;while( (ch = fgetc(in)) != EOF)

fputc(ch, out);fclose(in);fclose(out);

(Lecture 13) stdio.h: input/output January 21, 2020 16 / 21

fputc() - write character to stream

int fputc(int character, FILE *stream); - writes a character to thestream and advances the position indicator.Copying a file:

FILE *in = fopen(argv[1], "rb");if(!in) exit(EXIT_FAILURE);

FILE *out = fopen(argv[2], "wb");if(!out){

fclose(in);exit(EXIT_FAILURE);

}int ch;while( (ch = fgetc(in)) != EOF)

fputc(ch, out);fclose(in);fclose(out);

(Lecture 13) stdio.h: input/output January 21, 2020 16 / 21

ftell(), fseek() - file positioning

Every stream has an associated file position.

When a file is opened, the file position is set at the beginning of thefile.When a read or write operation is performed, the fiels positionadvances automatically, allowing us to move through the file in asequential manner.int ftell(FILE *stream); - returns the current value of the positionindicator of the stream.For binary streams, this is the number of bytes from the beginning ofthe file.For text streams, the numerical value may not be meaningful but canstill be used to restore the position to the same position later usingfseek.int fseek(FILE *stream, long int offset, int origin); - sets theposition indicator associated with the stream to a new position.For streams open in binary mode, the new position is defined byadding offset to a reference position specified by origin.

(Lecture 13) stdio.h: input/output January 21, 2020 17 / 21

ftell(), fseek() - file positioning

Every stream has an associated file position.When a file is opened, the file position is set at the beginning of thefile.

When a read or write operation is performed, the fiels positionadvances automatically, allowing us to move through the file in asequential manner.int ftell(FILE *stream); - returns the current value of the positionindicator of the stream.For binary streams, this is the number of bytes from the beginning ofthe file.For text streams, the numerical value may not be meaningful but canstill be used to restore the position to the same position later usingfseek.int fseek(FILE *stream, long int offset, int origin); - sets theposition indicator associated with the stream to a new position.For streams open in binary mode, the new position is defined byadding offset to a reference position specified by origin.

(Lecture 13) stdio.h: input/output January 21, 2020 17 / 21

ftell(), fseek() - file positioning

Every stream has an associated file position.When a file is opened, the file position is set at the beginning of thefile.When a read or write operation is performed, the fiels positionadvances automatically, allowing us to move through the file in asequential manner.

int ftell(FILE *stream); - returns the current value of the positionindicator of the stream.For binary streams, this is the number of bytes from the beginning ofthe file.For text streams, the numerical value may not be meaningful but canstill be used to restore the position to the same position later usingfseek.int fseek(FILE *stream, long int offset, int origin); - sets theposition indicator associated with the stream to a new position.For streams open in binary mode, the new position is defined byadding offset to a reference position specified by origin.

(Lecture 13) stdio.h: input/output January 21, 2020 17 / 21

ftell(), fseek() - file positioning

Every stream has an associated file position.When a file is opened, the file position is set at the beginning of thefile.When a read or write operation is performed, the fiels positionadvances automatically, allowing us to move through the file in asequential manner.int ftell(FILE *stream); - returns the current value of the positionindicator of the stream.

For binary streams, this is the number of bytes from the beginning ofthe file.For text streams, the numerical value may not be meaningful but canstill be used to restore the position to the same position later usingfseek.int fseek(FILE *stream, long int offset, int origin); - sets theposition indicator associated with the stream to a new position.For streams open in binary mode, the new position is defined byadding offset to a reference position specified by origin.

(Lecture 13) stdio.h: input/output January 21, 2020 17 / 21

ftell(), fseek() - file positioning

Every stream has an associated file position.When a file is opened, the file position is set at the beginning of thefile.When a read or write operation is performed, the fiels positionadvances automatically, allowing us to move through the file in asequential manner.int ftell(FILE *stream); - returns the current value of the positionindicator of the stream.For binary streams, this is the number of bytes from the beginning ofthe file.

For text streams, the numerical value may not be meaningful but canstill be used to restore the position to the same position later usingfseek.int fseek(FILE *stream, long int offset, int origin); - sets theposition indicator associated with the stream to a new position.For streams open in binary mode, the new position is defined byadding offset to a reference position specified by origin.

(Lecture 13) stdio.h: input/output January 21, 2020 17 / 21

ftell(), fseek() - file positioning

Every stream has an associated file position.When a file is opened, the file position is set at the beginning of thefile.When a read or write operation is performed, the fiels positionadvances automatically, allowing us to move through the file in asequential manner.int ftell(FILE *stream); - returns the current value of the positionindicator of the stream.For binary streams, this is the number of bytes from the beginning ofthe file.For text streams, the numerical value may not be meaningful but canstill be used to restore the position to the same position later usingfseek.

int fseek(FILE *stream, long int offset, int origin); - sets theposition indicator associated with the stream to a new position.For streams open in binary mode, the new position is defined byadding offset to a reference position specified by origin.

(Lecture 13) stdio.h: input/output January 21, 2020 17 / 21

ftell(), fseek() - file positioning

Every stream has an associated file position.When a file is opened, the file position is set at the beginning of thefile.When a read or write operation is performed, the fiels positionadvances automatically, allowing us to move through the file in asequential manner.int ftell(FILE *stream); - returns the current value of the positionindicator of the stream.For binary streams, this is the number of bytes from the beginning ofthe file.For text streams, the numerical value may not be meaningful but canstill be used to restore the position to the same position later usingfseek.int fseek(FILE *stream, long int offset, int origin); - sets theposition indicator associated with the stream to a new position.

For streams open in binary mode, the new position is defined byadding offset to a reference position specified by origin.

(Lecture 13) stdio.h: input/output January 21, 2020 17 / 21

ftell(), fseek() - file positioning

Every stream has an associated file position.When a file is opened, the file position is set at the beginning of thefile.When a read or write operation is performed, the fiels positionadvances automatically, allowing us to move through the file in asequential manner.int ftell(FILE *stream); - returns the current value of the positionindicator of the stream.For binary streams, this is the number of bytes from the beginning ofthe file.For text streams, the numerical value may not be meaningful but canstill be used to restore the position to the same position later usingfseek.int fseek(FILE *stream, long int offset, int origin); - sets theposition indicator associated with the stream to a new position.For streams open in binary mode, the new position is defined byadding offset to a reference position specified by origin.(Lecture 13) stdio.h: input/output January 21, 2020 17 / 21

ftell(), fseek() - file positioning

For streams open in text mode, offset shall either be zero or a valuereturned by a previous call to ftell, and origin shall necessarily beSEEK SET.

Position used as reference for the offset:

SEEK SET - Beginning of file,SEEK CUR - Current position of the file pointer,SEEK END - End of file.

The value returned by ftell may be saved and later supplied to a callof fseek, making it possible to return to a previous file position:

// saves current positionlong file_pos = ftell(pFile);...// returns to old positionfseek(pFile , file_pos , SEEK_SET);

(Lecture 13) stdio.h: input/output January 21, 2020 18 / 21

ftell(), fseek() - file positioning

For streams open in text mode, offset shall either be zero or a valuereturned by a previous call to ftell, and origin shall necessarily beSEEK SET.Position used as reference for the offset:

SEEK SET - Beginning of file,SEEK CUR - Current position of the file pointer,SEEK END - End of file.

The value returned by ftell may be saved and later supplied to a callof fseek, making it possible to return to a previous file position:

// saves current positionlong file_pos = ftell(pFile);...// returns to old positionfseek(pFile , file_pos , SEEK_SET);

(Lecture 13) stdio.h: input/output January 21, 2020 18 / 21

ftell(), fseek() - file positioning

For streams open in text mode, offset shall either be zero or a valuereturned by a previous call to ftell, and origin shall necessarily beSEEK SET.Position used as reference for the offset:

SEEK SET - Beginning of file,

SEEK CUR - Current position of the file pointer,SEEK END - End of file.

The value returned by ftell may be saved and later supplied to a callof fseek, making it possible to return to a previous file position:

// saves current positionlong file_pos = ftell(pFile);...// returns to old positionfseek(pFile , file_pos , SEEK_SET);

(Lecture 13) stdio.h: input/output January 21, 2020 18 / 21

ftell(), fseek() - file positioning

For streams open in text mode, offset shall either be zero or a valuereturned by a previous call to ftell, and origin shall necessarily beSEEK SET.Position used as reference for the offset:

SEEK SET - Beginning of file,SEEK CUR - Current position of the file pointer,

SEEK END - End of file.

The value returned by ftell may be saved and later supplied to a callof fseek, making it possible to return to a previous file position:

// saves current positionlong file_pos = ftell(pFile);...// returns to old positionfseek(pFile , file_pos , SEEK_SET);

(Lecture 13) stdio.h: input/output January 21, 2020 18 / 21

ftell(), fseek() - file positioning

For streams open in text mode, offset shall either be zero or a valuereturned by a previous call to ftell, and origin shall necessarily beSEEK SET.Position used as reference for the offset:

SEEK SET - Beginning of file,SEEK CUR - Current position of the file pointer,SEEK END - End of file.

The value returned by ftell may be saved and later supplied to a callof fseek, making it possible to return to a previous file position:

// saves current positionlong file_pos = ftell(pFile);...// returns to old positionfseek(pFile , file_pos , SEEK_SET);

(Lecture 13) stdio.h: input/output January 21, 2020 18 / 21

ftell(), fseek() - file positioning

For streams open in text mode, offset shall either be zero or a valuereturned by a previous call to ftell, and origin shall necessarily beSEEK SET.Position used as reference for the offset:

SEEK SET - Beginning of file,SEEK CUR - Current position of the file pointer,SEEK END - End of file.

The value returned by ftell may be saved and later supplied to a callof fseek, making it possible to return to a previous file position:

// saves current positionlong file_pos = ftell(pFile);...// returns to old positionfseek(pFile , file_pos , SEEK_SET);

(Lecture 13) stdio.h: input/output January 21, 2020 18 / 21

ftell(), fseek() - file positioning

Getting size of a file:

FILE *pFile = fopen(argv[1], "rb");if(! pFile) perror("Error opening file");else{

fseek(pFile , 0, SEEK_END);int s = ftell(pFile);fclose(pFile);printf("Size of %s: %d bytes.\n",argv[1],s);

}

(Lecture 13) stdio.h: input/output January 21, 2020 19 / 21

fwrite() - write block of data to stream

size t fwrite(const void *ptr, size t size, size t count, FILE*stream ); - writes an array of count elements, each one with a sizeof size bytes, from the block of memory pointed by ptr to the currentposition in the stream.

Internally, the function interprets the block pointed by ptr as if it wasan array of (size*count) elements of type unsigned char, and writesthem sequentially to stream.

float arr [56];...FILE *pFile = fopen("myfile.bin", "wb");if(pFile){

fwrite(arr , sizeof(float), sizeof(arr)/sizeof (*arr), pFile);

fclose(pFile);}

(Lecture 13) stdio.h: input/output January 21, 2020 20 / 21

fwrite() - write block of data to stream

size t fwrite(const void *ptr, size t size, size t count, FILE*stream ); - writes an array of count elements, each one with a sizeof size bytes, from the block of memory pointed by ptr to the currentposition in the stream.

Internally, the function interprets the block pointed by ptr as if it wasan array of (size*count) elements of type unsigned char, and writesthem sequentially to stream.

float arr [56];...FILE *pFile = fopen("myfile.bin", "wb");if(pFile){

fwrite(arr , sizeof(float), sizeof(arr)/sizeof (*arr), pFile);

fclose(pFile);}

(Lecture 13) stdio.h: input/output January 21, 2020 20 / 21

fwrite() - write block of data to stream

size t fwrite(const void *ptr, size t size, size t count, FILE*stream ); - writes an array of count elements, each one with a sizeof size bytes, from the block of memory pointed by ptr to the currentposition in the stream.

Internally, the function interprets the block pointed by ptr as if it wasan array of (size*count) elements of type unsigned char, and writesthem sequentially to stream.

float arr [56];...FILE *pFile = fopen("myfile.bin", "wb");if(pFile){

fwrite(arr , sizeof(float), sizeof(arr)/sizeof (*arr), pFile);

fclose(pFile);}

(Lecture 13) stdio.h: input/output January 21, 2020 20 / 21

fread() - read block of data from stream

size t fread(void *ptr, size t size, size t count, FILE *stream );- reads an array of count elements, each one with a size of sizebytes, from the stream and stores them in the block of memoryspecified by ptr.

The total amount of bytes read if successful is (size*count).

float arr [56];...FILE *pFile = fopen("myfile.bin", "rb");if(pFile){

fread(arr , sizeof (*arr), sizeof(arr)/sizeof(*arr), pFile);

fclose(pFile);}

(Lecture 13) stdio.h: input/output January 21, 2020 21 / 21

fread() - read block of data from stream

size t fread(void *ptr, size t size, size t count, FILE *stream );- reads an array of count elements, each one with a size of sizebytes, from the stream and stores them in the block of memoryspecified by ptr.

The total amount of bytes read if successful is (size*count).

float arr [56];...FILE *pFile = fopen("myfile.bin", "rb");if(pFile){

fread(arr , sizeof (*arr), sizeof(arr)/sizeof(*arr), pFile);

fclose(pFile);}

(Lecture 13) stdio.h: input/output January 21, 2020 21 / 21

fread() - read block of data from stream

size t fread(void *ptr, size t size, size t count, FILE *stream );- reads an array of count elements, each one with a size of sizebytes, from the stream and stores them in the block of memoryspecified by ptr.

The total amount of bytes read if successful is (size*count).

float arr [56];...FILE *pFile = fopen("myfile.bin", "rb");if(pFile){

fread(arr , sizeof (*arr), sizeof(arr)/sizeof(*arr), pFile);

fclose(pFile);}

(Lecture 13) stdio.h: input/output January 21, 2020 21 / 21

top related