Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

FILE

Introduction
A collection of data which is stored on a secondary device like a hard disk is called as a file. A
file is generally used as real-life applications that contain a large amount of data. Therefore, the
file is a place on the disk where a group of related data is stored.
The programs that we executed so far accepts the input data from the keyboard at the time of
execution and writes output to the video display unit. This type of I/O is called console I/O. For
those operations, we have been using printf(), scanf(), getch(), getche(), getchar(), gets(), puts()
etc functions. Console I/O works fine as long as the amount of data in small. But in many reallife
problems involve a large volume of data, there are 2 problems.
 It is time-consuming and unmanageable for handling such huge amount of data.
 When the I/O terminal is used the entire data is lost if the program is terminated or the
computer is being turned off. So it is a compulsion for storing the data on a permanent
device.
Why files are needed?
 When a program is terminated, the entire data is lost. Storing in a file will preserve your
data even if the program terminates.
 If you have to enter a large number of data it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of
the file using few commands in C.
 You can easily move your data from one computer to another without any changes.

Files are divided into 2 parts.


1. Stream oriented(Text file)/Standard : They are standard or high-level files. They are easier
to work with than the system oriented data-files and are used more commonly.
High levels data files are sub-divided into 2 categories:
1. Text files
2. Binary files

1. Text files : A text file is a human readable sequence of characters and the words they form
that can be encoded into computer-readable formats such as ASCII. A text contains only textual
characters with no special formatting such as underlining or displaying characters in bold faces
or different fonts. There is no graphical information, sound or video files. A text file known as an
ASCII file and can be read by any word processor. Text files store information in consecutive
characters. These characters can be interpreted as individual data items or as a component of
strings or numbers. Text files are the normal .txt files that you can easily create using Notepad or
any simple text editors. When you open file, you will see all contents within file as plain text.
2. Binary files : Binary files are mostly the .bin files in your computer. Instead of storing data in
plain text, they store it in the binary form (0's and 1's). They can hold higher amount of data are
not readable easily and provides a better security than text files.
In contrast to ASCII files, which contains only characters (plain text), binary files contain
additional code information i.e., machine readable form. Binary files organize data into blocks
containing contagious bytes of information. These blocks represent more complex data
structures. Example : arrays and structures. A good example of binary file is the executed C
program files. Example : first.exe is a binary file.
To check given file is text or binary, open file in Turbo C/C++, if we can read file then it is text
otherwise binary. Other examples of binary files are sound, graphics, image file etc.

File Operations
In C, you can perform four major operations on the file, either text or binary:
1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file
5. Moving to a specific location in a file.

Working with files


When working with files, you need to declare a pointer of type file. This declaration is needed
for communication between the file and program.
example : FILE *fptr;

Opening a file - for creation and edit


Opening a file is performed using the library function in the "stdio.h" header file: fopen().
The syntax for opening a file in standard I/O is:
ptr = fopen("fileopen","mode")
For Example:
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");
 Let's suppose the file newrogram.txt doesn't exist in the location E:\\cprogram. The first
function creates a new file named newprogram.txt and opens it for writing as per the
mode 'w'.
The writing mode allows you to create and edit (overwrite) the contents of the file.
 Now let's suppose the second binary file oldprogram.bin exists in the location
E:\\cprogram. The second function opens the existing file for reading in binary mode 'rb'.
The reading mode only allows you to read the file, you cannot write into the file.
Opening Modes in Standard I/O

File
Meaning of Mode During Inexistence of file
Mode

r Open for reading. If the file does not exist, fopen() returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
If the file exists, its contents are overwritten. If
w Open for writing.
the file does not exist, it will be created.
If the file exists, its contents are overwritten. If
wb Open for writing in binary mode.
the file does not exist, it will be created.
Open for append. i.e, Data is added
a If the file does not exists, it will be created.
to end of file.
Open for append in binary mode. i.e,
ab If the file does not exists, it will be created.
Data is added to end of file.
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
Open for both reading and writing in
rb+ If the file does not exist, fopen() returns NULL.
binary mode.
If the file exists, its contents are overwritten. If
w+ Open for both reading and writing.
the file does not exist, it will be created.
Open for both reading and writing in If the file exists, its contents are overwritten. If
wb+
binary mode. the file does not exist, it will be created.
Open for both reading and
a+ If the file does not exists, it will be created.
appending.
Open for both reading and
ab+ If the file does not exists, it will be created.
appending in binary mode.

Before reading data(info.) from an existing file we need to open in read mode. That is, fopen()
performs following task. When we open the file in "r" mode.
Firstly, it searches on the disk to the specified path to open the files.
If it finds the file, it loads the file from the disk into the buffer and it sets up file pointer that
points the first character of the pointer.
Buffer : A section of RAM reserved for temporary storage of data waiting to be directed to a
device.
Reading and writing to a text file
For reading and writing to a text file, we use the functions fprintf() and fscanf(). They are just the
file versions of printf() and scanf(). The only difference is that, fprint and fscanf expects a
pointer to the structure FILE.
Example 1: Write to a text file using fprintf()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
This program takes a number from user and stores in the file program.txt.
After you compile and run this program, you can see a text file program.txt created in C drive of
your computer. When you open the file, you can see the integer you entered.

Example 2: Read from a text file using fscanf()


#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("C:\\program.txt","r")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}
This program reads the integer present in the program.txt file and prints it onto the screen.
If you successfully created the file from Example 1, running this program will get you the
integer you entered.
Other functions like fgetchar(), fputc() etc. can be used in similar way.
Reading and writing to a binary file
Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.
Writing to a binary file
To write into a binary file, you need to use the function fwrite(). The functions takes four
arguments: Address of data to be written in disk, Size of data to be written in disk, number of
such type of data and pointer to the file where you want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Example 3: Write to a binary file using fwrite()
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","wb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5*n;
num.n3 = 5*n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);
return 0;}
In this program, you create a new file program.bin in the C drive.
We declare a structure threeNum with three numbers - n1, n2 and n3 and define it in the main
function as num.
Now, inside the for loop, we store the value into the file using fwrite().
The first parameter takes the address of num and the second parameter takes the size of the
structure threeNum.
Since, we're only inserting one instance of num, the third parameter is 1. And, the last parameter
*fptr points to the file we're storing the data.
Finally, we close the file.
Reading from a binary file
Function fread() also take 4 arguments similar to fwrite() function as above.
fread(address_data,size_data,numbers_data,pointer_to_file);
Example 4: Read from a binary file using fread()
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","rb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
}
fclose(fptr);
return 0;
}
In this program, you read the same file program.bin and loop through the records one by one.
In simple terms, you read one threeNum record of threeNum size from the file pointed by
*fptr into the structure num.
Getting data using fseek()
If you have many records inside a file and need to access a record at a specific position, you need
to loop through all the records before it to get the record.
This will waste a lot of memory and operation time. An easier way to get to the required data can
be achieved using fseek().
As the name suggests, fseek() seeks the cursor to the given record in the file.
Syntax of fseek()
fseek(FILE * stream, long int offset, int whence)
The first parameter stream is the pointer to the file. The second parameter is the position of the
record to be found, and the third parameter specifies the location where the offset starts.
Different Whence in fseek

Whence Meaning

SEEK_SET Starts the offset from the beginning of the file.

SEEK_END Starts the offset from the end of the file.

SEEK_CUR Starts the offset from the current location of the cursor in the file.

Example 5: fseek()
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","rb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
// Moves the cursor to the end of the file
fseek(fptr, -sizeof(struct threeNum), SEEK_END);
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR);
}
fclose(fptr);
return 0;
}
This program will start reading the records from the file program.bin in the reverse order (last to
first) and prints it.
1. Write a C program to read name and marks of n number of students from user and
store them in a file.
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;
printf("Enter number of students: ");
scanf("%d", &num);
FILE *fptr;
fptr = (fopen("C:\\student.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
for(i = 0; i < num; ++i)
{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);
printf("Enter marks: ");
scanf("%d", &marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);
}
fclose(fptr);
return 0;
}
2. Write a C program to read name and marks of n number of students from user and
store them in a file. If the file previously exits, add the information of n students.
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;
printf("Enter number of students: ");
scanf("%d", &num);
FILE *fptr;
fptr = (fopen("C:\\student.txt", "a"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
for(i = 0; i < num; ++i)
{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);
printf("Enter marks: ");
scanf("%d", &marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);
}
fclose(fptr);
return 0;
}
3. Write a 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);
printf("Enter height: ");
scanf("%d", &stud1[i].height);
}
fwrite(stud1, sizeof(stud1), 1, fptr);
fclose(fptr);
fptr = fopen("file.txt", "rb");
fread(stud2, sizeof(stud2), 1, fptr);
for(i = 0; i < 5; ++i)
{
printf("Name: %s\nHeight: %d", stud2[i].name, stud2[i].height);
}
fclose(fptr);
}
Difference between Append and Write Mode
Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to
write in a file. In both the modes, new file is created if it doesn't exists already.
The only difference they have is, when you open a file in the write mode, the file is reset,
resulting in deletion of any data already present in the file. While in append mode this will not
happen. Append mode is used to append or add data to the existing data of file(if any). Hence,
when you open a file in Append(a) mode, the cursor is positioned at the end of the present data in
the file.

Error Handling in C
C language does not provide any direct support for error handling. However a few methods and
variables defined in error.h header file can be used to point out error using the return statement in
a function. In C language, a function returns -1 or NULL value in case of any error and a global
variable errno is set with the error code. So the return value can be used to check error while
programming.

What is errno?
Whenever a function call is made in C language, a variable named errno is associated with it. It
is a global variable, which can be used to identify which type of error was encountered while
function execution, based on its value. Below we have the list of Error numbers and what does
they mean.
errno value Error

1 Operation not permitted

2 No such file or directory

3 No such process

4 Interrupted system call

5 I/O error

6 No such device or address

7 Argument list too long

8 Exec format error

9 Bad file number

10 No child processes

11 Try again

12 Out of memory

13 Permission denied
C language uses the following functions to represent error messages associated with errno:
perror(): returns the string passed to it along with the textual represention of the current errno
value.
strerror() is defined in string.h library. This method returns a pointer to the string representation
of the current errno value.
Time for an Example
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main ()
{
FILE *fp;
/*
If a file, which does not exists, is opened,
we will get an error
*/
fp = fopen("IWillReturnError.txt", "r");
printf("Value of errno: %d\n ", errno);
printf("The error message is : %s\n", strerror(errno));
perror("Message from perror");
return 0;
}
Value of errno: 2
The error message is: No such file or directory
Message from perror: No such file or directory

Other ways of Error Handling


We can also use Exit Status constants in the exit() function to inform the calling function about
the error. The two constant values available for use are EXIT_SUCCESS and EXIT_FAILURE.
These are nothing but macros defined stdlib.h header file.
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
extern int errno;
void main()
{
char *ptr = malloc( 1000000000UL); //requesting to allocate 1gb memory space
if (ptr == NULL) //if memory not available, it will return null
{
puts("malloc failed");
puts(strerror(errno));
exit(EXIT_FAILURE); //exit status failure
}
else
{
free( ptr);
exit(EXIT_SUCCESS); //exit status Success
}
}
Here exit function is used to indicate exit status. Its always a good practice to exit a program
with a exit status. EXIT_SUCCESS and EXIT_FAILURE are two macro used to show exit
status. In case of program coming out after a successful operation EXIT_SUCCESS is used to
show successful exit. It is defined as 0. EXIT_Failure is used in case of any failure in the
program. It is defined as -1.
Division by Zero
There are some situation where nothing can be done to handle the error. In C language one such
situation is division by zero. All you can do is avoid doing this, becasue if you do so, C language
is not able to understand what happened, and gives a runtime error.
Best way to avoid this is, to check the value of the divisor before using it in the division
operations. You can use if condition, and if it is found to be zero, just display a message and
return from the function.

Different I/O in files


Character I/O [fputc() & fgetc()]
A Simple C Program to open, read and close the file
#include <stdio.h>
int main()
{
/* Pointer to the file */
FILE *fp1;
/* Character variable to read the content of file */
char c;

/* Opening a file in r mode*/


fp1= fopen ("C:\\myfiles\\newfile.txt", "r");

/* Infinite loop –I have used break to come out of the loop*/


while(1)
{
c = fgetc(fp1);
if(c==EOF)
break;
else
printf("%c", c);
}
fclose(fp1);
return 0;
}
In the above program, we are opening a file newfile.txt in r mode, reading the content of the file
and displaying it on the console. lets understand the each operation in detail:

1. Opening a file
fopen() function is used for opening a file.
Syntax:
FILE pointer_name = fopen ("file_name", "Mode");
pointer_name can be anything of your choice.
file_name is the name of the file, which you want to open. Specify the full path here like
“C:\\myfiles\\newfile.txt”.
While opening a file, you need to specify the mode. The mode that we use to read a file is “r”
which is “read only mode”.
for example:
FILE *fp;
fp = fopen("C:\\myfiles\\newfile.txt", "r");
The address of the first character is stored in pointer fp.
How to check whether the file has opened successfully?
If file does not open successfully then the pointer will be assigned a NULL value, so you can
write the logic like this:
This code will check whether the file has opened successfully or not. If the file does not open,
this will display an error message to the user.
..
FILE fpr;
fpr = fopen("C:\\myfiles\\newfile.txt", "r");
if (fpr == NULL)
{
puts("Error while opening file");
exit();
}
2. Reading a File
To read the file, we must open it first using any of the mode, for example if you only want to
read the file then open it in “r” mode. Based on the mode selected during file opening, we are
allowed to perform certain operations on the file.
C Program to read a file
fgetc( ): This function reads the character from current pointer’s position and upon successful
read moves the pointer to next character in the file. Once the pointers reaches to the end of the
file, this function returns EOF (End of File). We have used EOF in our program to determine the
end of the file.
#include <stdio.h>
int main()
{
/* Pointer to the file */
FILE *fp1;
/* Character variable to read the content of file */
char c;

/* Opening a file in r mode*/


fp1= fopen ("C:\\myfiles\\newfile.txt", "r");

/* Infinite loop –I have used break to come out of the loop*/


while(1)
{
c = fgetc(fp1);
if(c==EOF)
break;
else
printf("%c", c);
}
fclose(fp1);
return 0;
}
3. Writing to a file
To write the file, we must open the file in a mode that supports writing. For example, if you open
a file in “r” mode, you won’t be able to write the file as “r” is read only mode that only allows
reading.
Example: C Program to write the file
This program asks the user to enter a character and writes that character at the end of the file. If
the file doesn’t exist then this program will create a file with the specified name and writes the
input character into the file.
#include <stdio.h>
int main()
{
char ch;
FILE *fpw;
fpw = fopen("C:\\newfile.txt","w");

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

printf("Enter any character: ");


scanf("%c",&ch);

/* You can also use fputc(ch, fpw);*/


fprintf(fpw,"%c",ch);
fclose(fpw);

return 0;
}
4. Closing a file
fclose(fp);
The fclose( ) function is used for closing an opened file. As an argument you must provide a
pointer to the file that you want to close.
An example to show Open, read, write and close operation in C
#include <stdio.h>
int main()
{
char ch;

/* Pointer for both the file*/


FILE *fpr, *fpw;
/* Opening file FILE1.C in “r” mode for reading */
fpr = fopen("C:\\file1.txt", "r");

/* Ensure FILE1.C opened successfully*/


if (fpr == NULL)
{
puts("Input file cannot be opened");
}

/* Opening file FILE2.C in “w” mode for writing*/


fpw= fopen("C:\\file2.txt", "w");

/* Ensure FILE2.C opened successfully*/


if (fpw == NULL)
{
puts("Output file cannot be opened");
}

/*Read & Write Logic*/


while(1)
{
ch = fgetc(fpr);
if (ch==EOF)
break;
else
fputc(ch, fpw);
}

/* Closing both the files */


fclose(fpr);
fclose(fpw);

return 0;
}

How to read/ write (I/O) Strings in Files – fgets & fputs


Here we will discuss how to read and write strings into a file.
char *fgets(char *s, int rec_len, FILE *fpr)
s:Array of characters to store strings.
rec_len: Length of the input record.
fpr: Pointer to the input file.
Lets take an example:
Example to read the strings from a file in C programming
#include <stdio.h>
int main()
{
FILE *fpr;
/*Char array to store string */
char str[100];
/*Opening the file in "r" mode*/
fpr = fopen("C:\\mynewtextfile.txt", "r");

/*Error handling for file open*/


if (fpr == NULL)
{
puts("Issue in opening the input file");
}

/*Loop for reading the file till end*/


while(1)
{
if(fgets(str, 10, fpr) ==NULL)
break;
else
printf("%s", str);
}
/*Closing the input file after reading*/
fclose(fpr);
return 0;
}
In the above example we have used fgets function like this:
fgets(str, 10, fpr)
Here str represents the string (array of char) in which you are storing the string after reading it
from file.
10 is the length of the string that needs to be read every time.
fpr is pointer to file, which is going to be read.
Why I used if(fgets(str, 10, fpr)==NULL as a logic to determine end of the file?
In the above examples, we have used ch==EOF to get to know the end of the file. Here we have
used this logic because fgets returns NULL when there is no more records are available to be
read.
C Program – Writing string to a file
int fputs ( const char * s, FILE * fpw );
char*s –Array_of_char.
FILE *fpw – Pointer (of FILE type) to the file, which is going to be written.
#include <stdio.h>
int main()
{
FILE *fpw;

/*Char array to store strings */


char str[100];

/*Opening the file FILEW.TXT in "w" mode for writing*/


fpw = fopen("C:\\mynewtextfile2.txt", "w");
/*Error handling for output file*/
if (fpw== NULL)
{
puts("Issue in opening the Output file");
}

printf("Enter your string:");

/*Stored the input string into array – str*/


gets(str);

/* Copied the content of str into file –


* mynewtextfile2.txt using pointer – fpw
*/
fputs(str, fpw);

/*Closing the Output file after successful writing*/


fclose(fpw);
return 0;
}
fputs takes two arguments –
fputs(str, fpw)
str – str represents the array, in which string is stored.
fpw – FILE pointer to the output file, in which record needs to be written.
Point to note about fputs:
fputs by default doesn’t add new line after writing each record, in order to do that manually –
you can have the following statement after each write to the file.
fputs("\n", fpw);

Standard I/O devices

Q. WAP to read the information of a file named "data.txt" and write its contents to
another file "record.txt".
#include <stdio.h>
#include <stdlib.h> // For exit()
#include<conio.h>
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
// Open one file for reading
fptr1 = fopen(filename, "w+");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
getch();
return 0;
}

Q. List different types of standard I/O used in C. WAP to write name, roll no and age of five students into a
disk file name "STUDENT.DAT".
#include <stdio.h>
#include<conio.h>
struct STUDENT
{
char name[20];
int rollno;
int age;
};
int main( )
{
struct STUDENT std[5];
int i;
FILE *fp;
fp = fopen("STUDENT.dat", "w");
for(i=0; i<5; i++)
{
printf("Name: ");
scanf("%s",std[i].name);
printf( "Roll: ");
scanf("%d", &std[i].rollno);
printf("Age: ");
scanf("%d", &std[i].age);
fprintf(fp,"Name : %d\tRoll : %d\tAge : %d\n",std[i].name, std[i].rollno, std[i].age);
}
fclose(fp);
getch();
return 0;
}

Q. WAP to continuously read name, age and salary of a worker and write it into a file until user confirms to
end. Then read n from user and display the nth record in the file. Details of worker must be represented by a
structure.
#include <stdio.h>
#include<conio.h>
struct WORKER
{
char name[20];
int age;
float salary;
};
int main( )
{
struct WORKER emp;
char next[3],line[200];
int n, i=1;
FILE *fp;
fp = fopen("WORKER.txt", "w");
do
{
printf("Name: ");
scanf("%s",emp.name);
printf( "Age: ");
scanf("%d", &emp.age);
printf("Salary: ");
scanf("%f", &emp.salary);
fprintf(fp,"Name : %s\tAge : %d\tSalary : %f\n",emp.name, emp.age, emp.salary);
printf("If you don't want to enter more data , please confirm 'yes': ");
scanf("%s", next);
}while(strcmp(next, "yes")!=0);
fclose(fp);
fp=fopen("WORKER.txt","r");
printf("Enter record number you want to display : ");
scanf("%d", &n);
while (fgets(line, sizeof(line), fp))
{
if(i == n )
{
printf("%s", line);
}
i++;
}
fclose(fp);
getch();
return 0;
}

Q. WAP to store employee details in a text file. Read data from the text file, sort them in ascending order of
salary and store the sorted record to a binary file. Display the details and rank of employee given by the user.
#include <stdio.h>
#include<conio.h>
struct WORKER
{
char name[20];
int age;
float salary;
};
int main( )
{
struct WORKER emp;
char next[3],line[200];
int n, i=1;
FILE *fp;
fp = fopen("WORKER.txt", "w");
do
{
printf("Name: ");
scanf("%s",emp.name);
printf( "Age: ");
scanf("%d", &emp.age);
printf("Salary: ");
scanf("%f", &emp.salary);
fprintf(fp,"Name : %s\tAge : %d\tSalary : %f\n",emp.name, emp.age, emp.salary);
printf("If you don't want to enter more data , please confirm 'yes': ");
scanf("%s", next);
}while(strcmp(next, "yes")!=0);
fclose(fp);
fp=fopen("WORKER.txt","r");
printf("Enter record number you want to display : ");
scanf("%d", &n);
while (fgets(line, sizeof(line), fp))
{
if(i == n )
{
printf("%s", line);
}
i++;
}
fclose(fp);
getch();
return 0;
}

Q. C Program to merge contents of two files into a third file


#include <stdio.h>
#include <stdlib.h>
int main()
{
// Open two files to be merged
FILE *fp1 = fopen("file1.txt", "r");
FILE *fp2 = fopen("file2.txt", "r");

// Open file to store the result


FILE *fp3 = fopen("file3.txt", "w");
char c;
if (fp1 == NULL || fp2 == NULL || fp3 == NULL)
{
puts("Could not open files");
exit(0);
}
// Copy contents of first file to file3.txt
while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);
// Copy contents of second file to file3.txt
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);
printf("Merged file1.txt and file2.txt into file3.txt");
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}

C program to delete a file


#include<stdio.h>
int main()
{
if (remove("abc.txt") == 0)
printf("Deleted successfully");
else
printf("Unable to delete the file");
return 0;
}

Q. Program to count number of characters, words and line in a text file.


#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fptr;
char path[100];
char ch;
int characters, words, lines;
printf("Enter source file path : ");
scanf("%s", path);
file=fopen(path,"r");
if(file==NULL)
{
printf("\nUnable to open file.\n");
printf(''Please check if file exists and you have read privilage.\n");
}
characters = words = lines = 0;
while((ch = fgetc(file)) ! = EOF)
{
characters++;
if(ch=='\n' || ch== '\0')
{
lines++;
}
if(ch==' ' || ch==\\t\ || ch=='\n' || ch=='\0')
{
words++;
}
}
if(characters>0)
{
words++;
lines++;
}
printf("\n");
printf("Total characters : %d\n", characters);
printf("Total words : %d\n", words);
printf("Total lines : %d\n", lines);
fclose(file);
return 0;
}

Q. C Program for Lower Case to Uppercase and vice-versa in a file


#include <stdio.h>
#include <stdlib.h>
void toggleCase(FILE *fptr, const char *path);
int main()
{
/* File pointer to hold reference of input file */
FILE *fPtr;
char path[100];
printf("Enter path of source file: ");
scanf("%s", path);
fPtr = fopen(path, "r");
/* fopen() return NULL if unable to open file in given mode. */
if (fPtr == NULL)
{
/* Unable to open file hence exit */
printf("\nUnable to open file.\n");
printf("Please check whether file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
toggleCase(fPtr, path);
printf("\nSuccessfully converted characters in file from uppercase to lowercase and vice versa.\n");
return 0;
}
/**
* Function to convert lowercase characters to uppercase
* and uppercase to lowercase in a file.
*/
void toggleCase(FILE *fptr, const char *path)
{
FILE *dest;
char ch
// Temporary file to store result
dest = fopen("toggle.tmp", "w");
// If unable to create temporary file
if (dest == NULL)
{
printf("Unable to toggle case.");
fclose(fptr);
exit(EXIT_FAILURE);
}
/* Repeat till end of file. */
while ( (ch = fgetc(fptr)) != EOF)
{
/*
* If current character is uppercase then toggle
* it to lowercase and vice versa.
*/
if (isupper(ch))
ch = tolower(ch);
else if (islower(ch))
ch = toupper(ch);
// Print toggled character to destination file.
fputc(ch, dest);
}
/* Close all files to release resource */
fclose(fptr);
fclose(dest);
/* Delete original source file */
remove(path);
/* Rename temporary file as original file */
rename("toggle.tmp", path);
}
Q. C program to print source code of itself as output
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fPtr;
char ch;
/*
* __FILE__ is a macro that contains path of current file.
* Open current program in read mode.
*/
fPtr = fopen(__FILE__, "r");
/* fopen() return NULL if unable to open file in given mode. */
if (fPtr == NULL)
{
/* Unable to open file hence exit */
printf("\nUnable to open file.\n");
printf("Please check whether file exists and you have read privilege.\n");
exit(EXIT_SUCCESS);
}
/* Read file character by character */
while ((ch = fgetc(fPtr)) != EOF)
{
printf("%c", ch);
}
/* Close files to release resources */
fclose(fPtr);
return 0;
}

Q. C program to replace a specific line with another in a file.


#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1000
int main()
{
/* File pointer to hold reference of input file */
FILE * fPtr;
FILE * fTemp;
char path[100];
char buffer[BUFFER_SIZE];
char newline[BUFFER_SIZE];
int line, count;
printf("Enter path of source file: ");
scanf("%s", path);
printf("Enter line number to replace: ");
scanf("%d", &line);
/* Remove extra new line character from stdin */
fflush(stdin);
printf("Replace '%d' line with: ", line);
fgets(newline, BUFFER_SIZE, stdin);
/* Open all required files */
fPtr = fopen(path, "r");
fTemp = fopen("replace.tmp", "w");
/* fopen() return NULL if unable to open file in given mode. */
if (fPtr == NULL || fTemp == NULL)
{
/* Unable to open file hence exit */
printf("\nUnable to open file.\n");
printf("Please check whether file exists and you have read/write privilege.\n");
exit(EXIT_SUCCESS);
}
/*
* Read line from source file and write to destination
* file after replacing given line.
*/
count = 0;
while ((fgets(buffer, BUFFER_SIZE, fPtr)) != NULL)
{
count++;
/* If current line is line to replace */
if (count == line)
fputs(newline, fTemp);
else
fputs(buffer, fTemp);
}
/* Close all files to release resource */
fclose(fPtr);
fclose(fTemp);
/* Delete original source file */
remove(path);
/* Rename temporary file as original file */
rename("replace.tmp", path);
printf("\nSuccessfully replaced '%d' line with '%s'.", line, newline);
return 0;
}
Q. C program to find and replace all occurrences of a word in file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
/* Function declaration */
void replaceAll(char *str, const char *oldWord, const char *newWord);
int main()
{
/* File pointer to hold reference of input file */
FILE * fPtr;
FILE * fTemp;
char path[100];
char buffer[BUFFER_SIZE];
char oldWord[100], newWord[100];
printf("Enter path of source file: ");
scanf("%s", path);
printf("Enter word to replace: ");
scanf("%s", oldWord);
printf("Replace '%s' with: ");
scanf("%s", newWord);
/* Open all required files */
fPtr = fopen(path, "r");
fTemp = fopen("replace.tmp", "w");
/* fopen() return NULL if unable to open file in given mode. */
if (fPtr == NULL || fTemp == NULL)
{
/* Unable to open file hence exit */
printf("\nUnable to open file.\n");
printf("Please check whether file exists and you have read/write privilege.\n");
exit(EXIT_SUCCESS);
}
/*
* Read line from source file and write to destination
* file after replacing given word.
*/
while ((fgets(buffer, BUFFER_SIZE, fPtr)) != NULL)
{
// Replace all occurrence of word from current line
replaceAll(buffer, oldWord, newWord);
// After replacing write it to temp file.
fputs(buffer, fTemp);}
/* Close all files to release resource */
fclose(fPtr);
fclose(fTemp);
/* Delete original source file */
remove(path);
/* Rename temp file as original file */
rename("replace.tmp", path);
printf("\nSuccessfully replaced all occurrences of '%s' with '%s'.", oldWord, newWord);
return 0;
}
/**
* Replace all occurrences of a given a word in string.
*/
void replaceAll(char *str, const char *oldWord, const char *newWord)
{
char *pos, temp[BUFFER_SIZE];
int index = 0;
int owlen;
owlen = strlen(oldWord);
/*
* Repeat till all occurrences are replaced.
*/
while ((pos = strstr(str, oldWord)) != NULL)
{
// Bakup current line
strcpy(temp, str);
// Index of current found word
index = pos - str;
// Terminate str after word found index
str[index] = '\0';
// Concatenate str with new word
strcat(str, newWord);
// Concatenate str with remaining words after
// oldword found index.
strcat(str, temp + index + owlen);
}
}
Q. C program to count occurrences of all words in a file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_WORDS 1000
int main()
{
FILE *fptr;
char path[100];
int i, len, index, isUnique;

// List of distinct words


char words[MAX_WORDS][50];
char word[50];
// Count of distinct words
int count[MAX_WORDS];
/* Input file path */
printf("Enter file path: ");
scanf("%s", path);
/* Try to open file */
fptr = fopen(path, "r");
/* Exit if file not opened successfully */
if (fptr == NULL)
{
printf("Unable to open file.\n");
printf("Please check you have read previleges.\n");
exit(EXIT_FAILURE);
}
// Initialize words count to 0
for (i=0; i<MAX_WORDS; i++)
count[i] = 0;
index = 0;
while (fscanf(fptr, "%s", word) != EOF)
{
// Convert word to lowercase
strlwr(word);
// Remove last punctuation character
len = strlen(word);
if (ispunct(word[len - 1]))
word[len - 1] = '\0';
// Check if word exits in list of all distinct words
isUnique = 1;
for (i=0; i<index && isUnique; i++)
{
if (strcmp(words[i], word) == 0)
isUnique = 0;
}
// If word is unique then add it to distinct words list
// and increment index. Otherwise increment occurrence
// count of current word.
if (isUnique)
{
strcpy(words[index], word);
count[index]++;
index++;
}
else
{
count[i - 1]++;
}
}
// Close file
fclose(fptr);
/*
* Print occurrences of all words in file.
*/
printf("\nOccurrences of all distinct words in file: \n");
for (i=0; i<index; i++)
{
/*
* %-15s prints string in 15 character width.
* - is used to print string left align inside
* 15 character width space.
*/
printf("%-15s => %d\n", words[i], count[i]);
}
return 0;
}
Q. C program to count occurrences of a word in file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
/* Function declarations */
int countOccurrences(FILE *fptr, const char *word);
int main()
{
FILE *fptr;
char path[100];
char word[50];
int wCount;
/* Input file path */
printf("Enter file path: ");
scanf("%s", path);
/* Input word to search in file */
printf("Enter word to search in file: ");
scanf("%s", word);
/* Try to open file */
fptr = fopen(path, "r");
/* Exit if file not opened successfully */
if (fptr == NULL)
{
printf("Unable to open file.\n");
printf("Please check you have read/write previleges.\n");
exit(EXIT_FAILURE);
}
// Call function to count all occurrence of word
wCount = countOccurrences(fptr, word);
printf("'%s' is found %d times in file.", word, wCount);
// Close file
fclose(fptr);
return 0;
}
/**
* Returns total occurrences of a word in given file.
*/
int countOccurrences(FILE *fptr, const char *word)
{
char str[BUFFER_SIZE];
char *pos;
int index, count;
count = 0;
// Read line from file till end of file.
while ((fgets(str, BUFFER_SIZE, fptr)) != NULL)
{
index = 0;
// Find next occurrence of word in str
while ((pos = strstr(str + index, word)) != NULL)
{
// Index of word in str is
// Memory address of pos - memory
// address of str.
index = (pos - str) + 1;
count++;
}
}
return count;
}
Q. C program to delete specific line from a file.
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1000
/* Function declarations */
void deleteLine(FILE *srcFile, FILE *tempFile, const int line);
void printFile(FILE *fptr);
int main()
{
FILE *srcFile;
FILE *tempFile;
char path[100];
int line;
/* Input file path and line number */
printf("Enter file path: ");
scanf("%s", path);
printf("Enter line number to remove: ");
scanf("%d", &line);
/* Try to open file */
srcFile = fopen(path, "r");
tempFile = fopen("delete-line.tmp", "w");
/* Exit if file not opened successfully */
if (srcFile == NULL || tempFile == NULL)
{
printf("Unable to open file.\n");
printf("Please check you have read/write previleges.\n");
exit(EXIT_FAILURE);
}
printf("\nFile contents before removing line.\n\n");
printFile(srcFile);
// Move src file pointer to beginning
rewind(srcFile);
// Delete given line from file.
deleteLine(srcFile, tempFile, line);
/* Close all open files */
fclose(srcFile);
fclose(tempFile);
/* Delete src file and rename temp file as src */
remove(path);
rename("delete-line.tmp", path);
printf("\n\n\nFile contents after removing %d line.\n\n", line);
// Open source file and print its contents
srcFile = fopen(path, "r");
printFile(srcFile);
fclose(srcFile);
return 0;
}
/**
* Print contents of a file.
*/
void printFile(FILE *fptr)
{
char ch;
while((ch = fgetc(fptr)) != EOF)
putchar(ch);
}
/**
* Function to delete a given line from file.
*/
void deleteLine(FILE *srcFile, FILE *tempFile, const int line)
{
char buffer[BUFFER_SIZE];
int count = 1;
while ((fgets(buffer, BUFFER_SIZE, srcFile)) != NULL)
{
/* If current line is not the line user wanted to remove */
if (line != count)
fputs(buffer, tempFile);
count++;}}
Q. C program to delete a word from file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
void removeAll(char * str, const char * toRemove);
int main()
{
FILE * fPtr;
FILE * fTemp;
char path[100];
char toRemove[100];
char buffer[1000];
/* Input source file path path */
printf("Enter path of source file: ");
scanf("%s", path);
printf("Enter word to remove: ");
scanf("%s", toRemove);
/* Open files */
fPtr = fopen(path, "r");
fTemp = fopen("delete.tmp", "w");
/* fopen() return NULL if unable to open file in given mode. */
if (fPtr == NULL || fTemp == NULL)
{
/* Unable to open file hence exit */
printf("\nUnable to open file.\n");
printf("Please check whether file exists and you have read/write privilege.\n");
exit(EXIT_SUCCESS);
}
/*
* Read line from source file and write to destination
* file after removing given word.
*/
while ((fgets(buffer, BUFFER_SIZE, fPtr)) != NULL)
{
// Remove all occurrence of word from current line
removeAll(buffer, toRemove);
// Write to temp file
fputs(buffer, fTemp);
}
/* Close all files to release resource */
fclose(fPtr);
fclose(fTemp);
/* Delete original source file */
remove(path);
/* Rename temp file as original file */
rename("delete.tmp", path);
printf("\nAll occurrence of '%s' removed successfully.", toRemove);
return 0;
}
/**
* Remove all occurrences of a given word in string.
*/
void removeAll(char * str, const char * toRemove)
{
int i, j, stringLen, toRemoveLen;
int found;
stringLen = strlen(str); // Length of string
toRemoveLen = strlen(toRemove); // Length of word to remove
for(i=0; i <= stringLen - toRemoveLen; i++)
{
/* Match word with string */
found = 1;
for(j=0; j < toRemoveLen; j++)
{
if(str[i + j] != toRemove[j])
{
found = 0;
break;
}
}
/* If it is not a word */
if(str[i + j] != ' ' && str[i + j] != '\t' && str[i + j] != '\n' && str[i + j] != '\0')
{
found = 0;
}
/*
* If word is found then shift all characters to left
* and decrement the string length
*/
if(found == 1)
{
for(j=i; j <= stringLen - toRemoveLen; j++)
{
str[j] = str[j + toRemoveLen];
}
stringLen = stringLen - toRemoveLen;
// We will match next occurrence of word from current index.
i--;
}
}
}

Q. Write a C program to read numbers from a file and write even, odd and prime numbers in separate files.
#include <stdio.h>
int main() {
FILE *fp1, *fp2, *fp3, *fp4;
int n, i, num, flag = 0;
/* open data.txt in read mode */
fp1 = fopen("data.txt", "w");
printf("Enter the value for n:");
scanf("%d", &n);
for (i = 0; i <= n; i++)
fprintf(fp1, "%d ", i);
fprintf(fp1, "\n");
fclose(fp1);
/* open files to write even, odd and prime nos separately */
fp1 = fopen("data.txt", "r");
fp2 = fopen("even.txt", "w");
fp3 = fopen("odd.txt", "w");
fp4 = fopen("prime.txt", "w");
fprintf(fp2, "Even Numbers:\n");
fprintf(fp3, "Odd Numbers:\n");
fprintf(fp4, "Prime Numbers:\n");
/* print even, odd and prime numbers in separate files */
while (!feof(fp1)) {
fscanf(fp1, "%d", &num);
if (num % 2 == 0) {
fprintf(fp2, "%d ", num);
} else {
if (num > 1) {
for (i = 2; i < num; i++) {
if (num % i == 0) {
flag = 1;
break;
}
}
if (!flag) {
fprintf(fp4, "%d ", num);
}
}
fprintf(fp3, "%d ", num);
flag = 0;
}
}
/* close all opened files */
fclose(fp1);
fclose(fp2);
fclose(fp3);
fclose(fp4);
return 0;
}

You might also like