Subash siwa
WHAT IS FILE?
File is a collection of bytes that is stored on secondary storage devices like disk. There are two kinds of
files in a system. They are,
Text files (ASCII)
Binary files
Text files contain ASCII codes of digits, alphabetic and symbols.
Binary file contains collection of bytes (0s and 1s). Binary files are compiled version of text files.
There are many modes in opening a file. Based on the mode of file, it can be opened for reading or
writing or appending the texts. They are listed below.
r Opens a file in read mode and sets pointer to the first character in the file. It returns null if file does not
exist.
w Opens a file in write mode. It returns null if file could not be opened. If file exists, data are
overwritten.
a Opens a file in append mode. It returns null if file couldnt be opened.
r+ Opens a file for read and write mode and sets pointer to the first character in the file.
w+ opens a file for read and write mode and sets pointer to the first character in the file.
a+ Opens a file for read and write mode and sets pointer to the first character in the file. But, it cant
modify existing contents.
1.Formatted input and output function
Output:
}
Notes on : File Handling and Programs M.Sc (IT):Mr.Subash siwa
Output:
3.fscanf()
Steps for reading the file
1.create a file pointer
2.open file in read(r) mode
3.read i/o results using following syntax:
fscanf(file_pointer,format specifier,&variable list );
4.display data as required.
5.close the file using fclose(file_pointer)
4.fclose() To close a file
Declaration: int fclose(FILE *fp);
fclose() function closes the file that is being pointed by file pointer fp.
Program:[ fopen(),fclose(),fscanf()]
#include<stdio.h>
main()
{
FILE*fp;
int age;
char name[20];
fp=fopen("first.txt","r");
fscanf(fp,"%s\n%d",name,&age);
printf("name=%s\n",name);
printf("age=%d",age);
fclose(fp);
}
Notes on : File Handling and Programs M.Sc (IT):Mr.Subash siwa
Output:
}
fclose(fp);
Output:
fgets(ch,17,fp);
puts(ch);
fclose(fp);
}Output:
printf("%d\t",no);
}
fclose(fp);
}
Output:
Output: