Files in C
Files in C
A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for
permanent storage of data. It is a ready made structure.
FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following are the functions,
Function description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file
fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
ftell() gives current position in the file
rewind() set the position to the begining point
Opening a File or Creating a File
fp= fopen( file_name, file_mode)
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
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both reading and writing mode
ab+ opens a binary file in both reading and writing mode
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data");
while( (ch = getchar()) != '$') {
putc(ch,fp);
}
fclose(fp);
fp = fopen("one.txt", "r");
fclose(fp);
}
Note: This program will read the input character wise from user until a '$' is pressed. Then display the
contents of the file in console.
Reading and Writing from File using fwrite() and fread()
** C program to write all the members of an array of structures to a file using fwrite(). Read the array
from the file and display on the screen.
#include <stdio.h>
struct student
{
char name[50];
int height;
};
int main(){
struct student stud1[5], stud2[5];
FILE *fptr;
int i;
fptr = fopen("file.txt","wb");
for(i = 0; i < 5; ++i)
{
fflush(stdin);
printf("Enter name: ");
gets(stud1[i].name);