Files :

File is a collection of numbers, symbols and text placed on the disk. file can be read and modified as per the user requirement, thus file allow us to store information permanently in the disk.

The file object contain all information about stream like current position, pointer to any buffer, error and EOF (end of file).

Type of file :

  1.  Sequential File :  In this type of file data are kept sequentially. if we want to read the last record of file. we need to read all the records before that record.

2. Random Access File : Data can be read and modified randomly. if we want to read the last records of file, we can make it directly.

Steps for file operation :

  1. Opening of file
  2. Reading or writing file
  3. closing file

1. Opening a file:

Opening of file create a link between the operating system and file functions. We have to specify the name of the file and it’s mode.

fopen() is only function to open a file.

Syntax for opening the file:
File *fp;
fp = fopen("file name", "mode");

example:

File *fp = fopen(“data.txt”, “r”);

Notes:

fopen() perfoms following task:

1. It searches the disk for opening file.

2. In case file exists, it loads the file from the disk into memory.

3. If file is not existing, this function returns a NULL.

4. It locates a character pointer, which points the first character of the file.

2. Reading a file:

Example :

File *fp = fopen("data.txt", "r");
while(c != EOF){   
   c= fgetc(fp);
   printf("%c", c);
}

 3. Closing of file:

The file that is opened from fopen() should be closed after the work is over.

Syntax :

fclose(<file-pointer>);

 

Leave a Reply

Your email address will not be published. Required fields are marked *