0% found this document useful (0 votes)
2 views12 pages

FILE CONCEPTS Programs

A file is a collection of bytes stored on secondary storage devices, categorized into text and binary files. In C programming, basic file operations include opening, closing, reading, and writing files, with various modes for file access. The document also provides examples of file handling functions and programs demonstrating file operations in C.

Uploaded by

Prakash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views12 pages

FILE CONCEPTS Programs

A file is a collection of bytes stored on secondary storage devices, categorized into text and binary files. In C programming, basic file operations include opening, closing, reading, and writing files, with various modes for file access. The document also provides examples of file handling functions and programs demonstrating file operations in C.

Uploaded by

Prakash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

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,

1. Text files (ASCII)


2. Binary files
 Text files contain ASCII codes of digits, alphabetic and symbols.
 Binary file contains collection of bytes (0’s and 1’s). Binary files are compiled version of text files.

Basic file operations in C programming:


There are 4 basic operations that can be performed on any files in C programming language. They are,

1. Opening/Creating a file
2. Closing a file
3. Reading a file
4. Writing in a file

Let us see the syntax for each of the above operations in a table:

File operation Declaration & Description

Declaration: FILE *fopen (const char *filename, const char *mode)

fopen() function is used to open a file to perform operations such as reading, writing etc. In
a C program, we declare a file pointer and use fopen() as below. fopen() function creates a
new file if the mentioned file name does not exist.
fopen() – To FILE *fp;
open a file fp=fopen (“filename”, ”‘mode”);
Where,
fp – file pointer to the data type “FILE”.
filename – the actual file name with full path of the file.
mode – refers to the operation that will be performed on the file. Example: r, w, a, r+, w+
and a+. Please refer below the description for these mode of operations.
Declaration: int fclose(FILE *fp);
fclose() – To
close a file fclose() function closes the file that is being pointed by file pointer fp. In a C program, we
close a file as below.
fclose (fp);
Declaration: char *fgets(char *string, int n, FILE *fp)

fgets function is used to read a file line by line. In a C program, we use fgets function as
fgets() – To read below.
a file fgets (buffer, size, fp);
where,
buffer – buffer to put the data in.
size – size of the buffer
fp – file pointer
fprintf() – To Declaration:
write into a file int fprintf(FILE *fp, const char *format, …);fprintf() function writes string into a file
pointed by fp. In a C program, we write string into a file as below.
fprintf (fp, “some data”); or
fprintf (fp, “text %d”, variable_name);

Mode of operations performed on a file in C language:


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 couldn’t 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
can’t modify existing contents.

1. Example program for file open, file write and file close in C language:
C
/ * Open, write and close a file : */
# include <stdio.h>
# include <string.h>
int main( )
{
FILE *fp ;
char data[50];
// opening an existing file
printf( "Opening the file test.c in write mode" ) ;
fp = fopen("test.c", "w") ;
if ( fp == NULL )
{
printf( "Could not open file test.c" ) ;
return 1;
}
printf( "\n Enter some text from keyboard” \
“ to write in the file test.c" ) ;
// getting input from user
while ( strlen ( gets( data ) ) > 0 )
{
// writing in the file
fputs(data, fp) ;
fputs("\n", fp) ;
}
// closing the file
printf("Closing the file test.c") ;
fclose(fp) ;
return 0;
}
Output:
Opening the file test.c in write mode
Enter some text from keyboard to write in the file test.c
Hai, How are you?
Closing the file test.c

2. Example program for file open, file read and file close in C language:
This file handling C program illustrates how to read the contents of a file. Assume that, a file called “test.c”
contains the following data “Hai, How are you?”. Let’s read this data using following C program.
/* Open, Read and close a file: reading string by string */

# include <stdio.h>
int main( )
{
FILE *fp ;
char data[50] ;
printf( "Opening the file test.c in read mode" ) ;
fp = fopen( "test.c", "r" ) ;
if ( fp == NULL )
{
printf( "Could not open file test.c" ) ;
return 1;
}
printf( "Reading the file test.c" ) ;
while( fgets ( data, 50, fp ) != NULL )
printf( "%s" , data ) ;
printf("Closing the file test.c") ;
fclose(fp) ;
return 0;
}

Output:
Opening the file test.c in read mode
Reading the file test.c
Hai, How are you?
Closing the file test.c

Inbuilt functions for file handling in C language:


C programming language offers many inbuilt functions for handling files. They are given below. Please
click on each function name below to know more details, example programs, output for the respective file
handling function.

File handling functions Description


fopen () fopen () function creates a new file or opens an existing file.
fclose () fclose () function closes an opened file.
getw () getw () function reads an integer from file.
putw () putw () functions writes an integer to file.
fgetc () fgetc () function reads a character from file.
fputc () fputc () functions write a character to file.
gets () gets () function reads line from keyboard.
puts () puts () function writes line to o/p screen.
fgets () fgets () function reads string from a file, one line at a time.
fputs () fputs () function writes string to a file.
feof () feof () function finds end of file.
fgetchar () fgetchar () function reads a character from keyboard.
fprintf () fprintf () function writes formatted data to a file.
fscanf () fscanf () function reads formatted data from a file.
fputchar () fputchar () function writes a character onto the output screen from keyboard input.
fseek () fseek () function moves file pointer position to given location.
SEEK_SET SEEK_SET moves file pointer position to the beginning of the file.
SEEK_CUR SEEK_CUR moves file pointer position to given location.
SEEK_END SEEK_END moves file pointer position to the end of file.
ftell () ftell () function gives current position of file pointer.
rewind () rewind () function moves file pointer position to the beginning of the file.
getc () getc () function reads character from file.
getch () getch () function reads character from keyboard.
getche () getche () function reads character from keyboard and echoes to o/p screen.
getchar () getchar () function reads character from keyboard.
putc () putc () function writes a character to file.
putchar () putchar () function writes a character to screen.
printf () printf () function writes formatted data to screen.
sprinf () sprinf () function writes formatted output to string.
scanf () scanf () function reads formatted data from keyboard.
sscanf () sscanf () function Reads formatted input from a string.
remove () remove () function deletes a file.
fflush () fflush () function flushes a file

It can be done easily with fscanf: Writing


#include <stdio.h>
int main()
{
FILE* f = fopen("test.txt", "r");
int number = 0;
int sum = 0; /* the sum of numbers in the file */

while( fscanf(f, "%d,", &number) > 0 ) // parse %d followed by ','


{
sum += number; // instead of sum you could put your numbers in an array
}

fclose(f);
}

#include <stdio.h>
main()
{

FILE *myFile;
myFile = fopen("somenumbers.txt", "r");

//read file into array


int numberArray[16];
int i;

for (i = 0; i < 16; i++)


{
fscanf(myFile, "%d", &numberArray[i]);
}

for (i = 0; i < 16; i++)


{
printf("Number is: %d\n\n", numberArray[i]);
}

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
FILE *fp;
int i;

/* open the file */


fp = fopen("results.dat", "w");
if (fp == NULL) {
printf("I couldn't open results.dat for writing.\n");
exit(0);
}

/* write to the file */


for (i=0; i<=10; ++i)
fprintf(fp, "%d, %d\n", i, i*i);

/* close the file */


fclose(fp);

return 0;
}

Program to Create a File & Write Data in it


In this program we will be creating a new file and will then store information in it.
#include<stdio.h>
#include<conio.h>

void main()
{
FILE *fptr;
char name[20];
int age;
float salary;

/* open for writing */


fptr = fopen("emp.txt", "w");

if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n", name);

printf("Enter the age\n");


scanf("%d", &age);
fprintf(fptr, "Age = %d\n", age);

printf("Enter the salary\n");


scanf("%f", &salary);
fprintf(fptr, "Salary = %.2f\n", salary);

fclose(fptr);
}

GETS and PUTS – Writing sentence in a text file


This program stores a sentence entered by user in a file.

#include <stdio.h>
#include <stdlib.h> /* For exit() function */
int main()
{
char sentence[1000];
FILE *fptr;

fptr = fopen("program.txt", "w");


if(fptr == NULL)
{
printf("Error!");
exit(1);
}

printf("Enter a sentence:\n");
gets(sentence);

fprintf(fptr,"%s", sentence);
fclose(fptr);

return 0;
}
Input/Output operation on File
In the above table we have discussed about various file I/O functions to perform reading and writing on file.
getc() and putc() are simplest functions used to read and write individual characters to a file.

#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data");
while( (ch = getchar()) != EOF) {
putc(ch,fp);
}
fclose(fp);
fp = fopen("one.txt", "r");

while( (ch = getc(fp)! = EOF)


printf("%c",ch);

fclose(fp);
}

Reading and Writing in a Binary File


A Binary file is similar to the text file, but it contains only large numerical data. The Opening modes are
mentioned in the table for opening modes above.
fread() and fwrite() functions are used to read and write is a binary file.

fwrite(data-element-to-be-written, size_of_elements,
number_of_elements, pointer-to-file);
fread() is also used in the same way, with the same arguments like fwrite() function. Below mentioned is a
simple example of writing into a binary file

const char *mytext = "The quick brown fox jumps over the lazy dog";
FILE *bfp= fopen("test.txt", "wb");
if (bfp) {
fwrite(mytext, sizeof(char), strlen(mytext), bfp) ;
fclose(bfp) ;
}

fseek(), ftell() and rewind() functions


 fseek() - It is used to move the reading control to different positions using fseek function.
 ftell() - It tells the byte location of current position of cursor in file pointer.
 rewind() - It moves the control to beginning of the file.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fptr1, *fptr2, *fptr3;
int n, i, num;
clrscr();
printf("Enter number of values : ");
scanf("%d", &n);
printf("\nEnter the values : ");
fptr1 = fopen("NUMBERS.DAT", "w");
for(i = 0 ; i < n ; i++)
{
scanf("%d", &num);
putw(num, fptr1);
}
fclose(fptr1);
fptr1 = fopen("NUMBERS.DAT", "r");
fptr2 = fopen("ODD.DAT", "w");
fptr3 = fopen("EVEN.DAT", "w");
while((num = getw(fptr1)) != EOF)
{
if(num % 2 == 0){
putw(num, fptr3) ;
} else{
putw(num, fptr2) ;
}
}
fclose(fptr1);
fclose(fptr2);
fclose(fptr3);
fptr2 = fopen("ODD.DAT", "r");
fptr3 = fopen("EVEN.DAT", "r");
printf("\nContents of ODD file is : ");
while((num = getw(fptr2)) != EOF){
printf("%d\t", num) ;
}
printf("\n\nContents of EVEN file is : ") ;
while((num = getw(fptr3)) != EOF){
printf("%d\t", num);
}
fclose(fptr2);
fclose(fptr3);
getch();
}

#include<stdio.h>
#include<conio.h>
void main()
{
char c;
FILE *fptr1;
clrscr();
printf("Enter the text to be stored in the file.\n");
printf("Use ^Z or F6 at the end of the text and press ENTER: \n\n");
fptr1 = fopen("COURSES.DAT","w");
while((c = getc(stdin)) != EOF){
fputc(c, fptr1);
}
fclose(fptr1);
printf("\nThe content of the file is : \n\n");
fptr1 = fopen("COURSES.DAT", "r");
do
{
c = fgetc(fptr1);
putchar(c);
} while(c != EOF);
fclose(fptr1);
getch();
}

Writing into and reading from a binary file in C


In previous example, you learn how to write and read a text file in C. If the number of fields in the structure
increase, writing structures using fprintf(), or reading them using fscanf(), becomes quite clumsy. The more
efficient way of writing records(structures) can be achieved by the use of two functions fread() and fwrite().
The fwrite() functions writes whole structures at a time and fread() function read all the fields at a time.
Writing into the binary file
The following code segment illustrates how to write data into file in binary format.

struct emp{
char name[20];
int age;
float bs;
};

struct emp e;

fp = fopen("EMP.DAT","wb");

if(fp == NULL){
puts("Cannot open file");
}

printf("Enter name, age and basic salary");


scanf("%s%d%f",e.name,&e.age,&e.bs);
fwrite(&e,sizeof(e),1,fp);
fclose(fp);
}

Reading from the binary file

The following code segment illustrates how to read data from file in binary format.

fp = fopen("EMP.DAT","rb");
while(fread(&e,sizeof(e),1,fp)==1){
printf("%s %d %f\n",e.name,e.age,e.bs);
}
fclose(fp);

Reading and Writing from File using fprintf() and fscanf()


#include<stdio.h>
#include<conio.h>
struct emp
{
char name[10];
int age;
};

void main()
{
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");

printf("Enter Name and Age");


scanf("%s %d", e.name, &e.age);

fprintf(p,"%s %d", e.name, e.age);


fclose(p);
do
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while( !feof(q) );
getch();
}

Program to Create a File & Write Data in it


In this program we will be creating a new file and will then store information in it.
#include<stdio.h>
#include<conio.h>

void main()
{
FILE *fptr;
char name[20];
int age;
float salary;

/* open for writing */


fptr = fopen("emp.txt", "w");

if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n", name);

printf("Enter the age\n");


scanf("%d", &age);
fprintf(fptr, "Age = %d\n", age);

printf("Enter the salary\n");


scanf("%f", &salary);
fprintf(fptr, "Salary = %.2f\n", salary);

fclose(fptr);
}
GETS and PUTS – Writing sentence in a text file
This program stores a sentence entered by user in a file.

#include <stdio.h>
#include <stdlib.h> /* For exit() function */
int main()
{
char sentence[1000];
FILE *fptr;

fptr = fopen("program.txt", "w");


if(fptr == NULL)
{
printf("Error!");
exit(1);
}

printf("Enter a sentence:\n");
gets(sentence);

fprintf(fptr,"%s", sentence);
fclose(fptr);

return 0;
}

You might also like