file Handling

File Handling in C

Operation on Files

    1. Creating and Opening a data file 

The fopen() function is used to create a new file or open an existing file.

Syntax :

 *fp = FILE *fopen(const char *filename, const char *mode);

Here,
*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened or created file.
*filename is the name of the file to be opened or created file.
*mode specifies the purpose of opening the file.

Mode can be of following types.

Mode

Description

r

opens a text file in reading mode.

w

opens or create a text file in writing mode.

a

opens a text file in append mode.

r+

opens a text file in both reading and writing mode.

w+

opens a text file in both reading and writing mode.

a+

opens a text file in both reading and writing mode.

     2. Closing a data file

The fclose() function is used to close a file.

 Syntax :

int fclose( FILE *fp);

Here, fclose() function closes the file and returns zero on success or EOF if there is an error in closing the file.

 File I/O functions

  Read functions

  1. fscanf() : read set of characters from file.
  2. fgetc() : returns a single character from the file.
  3. fgets() : reads a line of characters from file

  Write functions

  1. fprintf() : write set of characters into file.
  2. fputc() : write a single character into file.
  3. fputs() : writes a line of characters into file.

Command line arguments

The arguments passed from command line are called command line arguments. These arguments are handled by main() function. It is mostly used when you need to control your program from outside.

   Syntax :

  int main(int argc, char *argv[ ])

 Here, argc refers to the number of arguments passed, and argv[ ] is a pointer array which points to each argument passed to the program.

 
This website was created for free with Own-Free-Website.com. Would you also like to have your own website?
Sign up for free