A File can be used to store a large volume of persistent data. Like many other languages ‘C’ provides following file management functions,
- Creation of a file
- Opening a file
- Reading a file
- Writing to a file
- Closing a file
Creating and Opening Files
The fopen( ) function
to create a new file or to open an existing file. This call will initialize an
object of the type FILE,
which contains all the information necessary to control the stream. The
prototype of this function call is as follows –
FILE *fopen( const char *
filename, const char * mode );
Following are the list of functions which are used for
reading a file:
Functions |
Syntax |
Description |
fscanf( ) |
int fscanf (FILE *stream, const char *format,....); |
It is used for reading the formatted data from the stream. |
fgets( ) |
char *fgets(char *str, int size, FILE *stream); |
It stands for file get string. It is used for getting the
string from a stream. |
fgetc( ) |
int fgetc (FILE *stream); |
It will return the next character from the stream from the
end of the file or an error. |
fread( ) |
int fread(void *str, size_t size, size_t num, FILE
*stream); |
It is used for reading data from a file. |
Following are the list of functions which are used for
writing a file:
Functions |
Syntax |
Description |
fprintf() |
int fprintf (FILE *stream, const char * format,...); |
It is used for writing the formatted output of the stream. |
fputs() |
int fputs(const char *str, FILE *stream); |
It is used for writing a line to a file. |
fputc() |
int fputc(int c, FILE *stream); |
It is opposite to fgetc() and is used for writing a
character to the stream. |
fwrite() |
int fwrite(const void *str, size_t size, size_t count, file
*stream); |
It is used for writing data to a file. |
Following are the functions which are used for detecting the
errors:
Functions |
Syntax |
Description |
clearerr() |
void clearerr(FILE *stream); |
It is used for clearing the end-of-file and error
indicators for the stream. |
perror() |
void perror(char *msg); |
It stands for the print error. |
Closing a file :
After every successful file operation, always close a file.
For closing a file, fclose function is used.
Ex:
filePointer= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(filePointer)
No comments:
Post a Comment