It allows the program to perform operations on the file.
File opening modes
Mode | Meaning |
r | Open a text file for reading |
w | Create a text file for writing |
a | Append to a text file |
rb | Open a binary file for reading |
wb | Open a binary file for writing |
ab | Append to a binary file |
r+ | Open a text file for read/write |
w+ | Create a text file for read/write |
a+ | Append or create a text file for read/write |
r+b | Open a binary file for read/write |
w+b | Create a binary file for read/write |
a+b | Append a binary file for read/write |
Note: The complete path of the file must be specified, if the file is not in the current directory. Most of the functions prototype for file handling is mentioned in stdio.h.
Opening a file for writing
In C, this line:
opens a file for writing. The "w" mode has very specific and important implications.
1. If data.txt does not exist on the disk
-
A new file named data.txt is created.
-
The file is opened for writing.
-
The file pointer fp points to the beginning of the new file.
-
If the file cannot be created (e.g., permission issues), fopen returns NULL.
✔️ Result: File is created and ready for writing
2. If data.txt already exists on the disk
-
The existing file is opened for writing.
-
All existing contents are erased (truncated to zero length).
-
The file pointer fp is positioned at the beginning of the file.
-
Any previous data in data.txt is permanently lost.
⚠️ Result: File contents are deleted and replaced
Summary Table
| Scenario | Result |
|---|
| File does not exist | New file is created |
| File exists | File is truncated (emptied) |
| Failure (permissions, disk error) | fopen returns NULL |
Closing a File Using fclose() in C
After reading from or writing to a file, it is important to close the file properly using the fclose() function.
Tasks Performed by fclose()
The fclose() function does the following:
-
Flushes any unwritten data from memory.
-
Discards any unread buffered input.
-
Frees any automatically allocated buffer.
-
Finally, closes the file.
Syntax
Example
Notes
Why Closing Files is Important
-
File Descriptors/Handles:
Keeping files open without closing them may exhaust the available file descriptors, causing future fopen() calls to fail.
-
Exclusive File Locks:
On some platforms like Windows, open files may prevent other processes from opening, modifying, or deleting the file until it is closed.
-
Buffered Data:
-
Most file streams buffer data in memory before writing it to disk.
-
If the program exits normally (via exit() or returning from main()), the C runtime will flush the buffers automatically.
-
If the program exits abnormally (via abort(), signals, or exceptions), buffered data will not be written, potentially causing data loss.
Closing files properly ensures data integrity, prevents resource leaks, and avoids unexpected runtime errors.
Working with Text Files
The following functions provides facility for reading and writing files
Reading | Writing |
fgetc() | fputc() |
fgets() | fputs() |
fscanf() | fprintf() |
fread() | fwrite() |
Character Input and Output in C
Characters or lines (sequences of characters terminated by a newline) can be read from or written to a file using several standard library functions.
1. putc() / fputc() Function
2. fputs() Function
3. getc() / fgetc() Function
4. fgets() Function
5. fprintf() and fscanf() Functions
6. putw() and getw() Functions
putw()
getw()
Binary Files and Direct File I/O
The operations performed on binary files are similar to text files, as both can be considered as streams of bytes. In fact, the same functions are often used to access files in C.
-
When a file is opened, it must be designated as text or binary.
-
This designation is usually the only indication of the type of file being processed.
Direct File I/O
Functions for Direct I/O
The C file system provides two important functions for direct I/O:
1. fread()
Prototype:
Description:
-
Reads num number of objects, each of size bytes, from the file associated with fp.
-
Stores the read data into the memory pointed to by buffer.
2. fwrite()
Prototype:
Description:
-
Writes num number of objects, each of size bytes, from the memory pointed to by buffer.
-
Writes the data to the file associated with fp.
Summary:
| Function | Purpose |
|---|
fread | Read a block of data from a file into memory |
fwrite | Write a block of data from memory to a file |
Sample Programs
Write a c program snippet to open a file in write mode and check if the file opened successfully. if it fails , print an error message and terminate the program.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w"); // Open file in write mode
if (fp == NULL) {
printf("Error: Could not open file for writing.\n");
exit(1); // Terminate the program
}
printf("File opened successfully for writing.\n");
// You can now write to the file here...
fclose(fp); // Close the file
return 0;
}
Read and display a file character by character using getc/fgetc function
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int ch;
fp=fopen("a.txt","r");
if(fp==NULL)
{
printf("Error opening file..");
exit(1);
}
while((ch=getc(fp))!=EOF) // can use ch=fgetc(fp) also
{
putchar(ch);
}
fclose(fp);
}
vowels consonants digits and special characters in a file ( university question)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int ch,vowels=0,consonants=0,digits=0,specc=0,c=0;
fp=fopen("a.txt","r");
if(fp==NULL)
{
printf("Error opening file..");
exit(1);
}
while((ch=fgetc(fp))!=EOF)
{
if(ch=='a' || ch=='e' || ch=='i' ||
ch=='o' || ch=='u' || ch=='A' ||
ch=='E' || ch=='I' || ch=='O' ||
ch=='U')
{
++vowels;
}
else if((ch>='a'&& ch<='z') || (ch>='A'&& ch<='Z'))
{
++consonants;
}
else if(ch>='0' && ch<='9')
{
++digits;
}
else if (ch ==' ' || ch =='\n')
{
++specc;
}
c++;
}
printf("Vowels: %d",vowels);
printf("\nConsonants: %d",consonants);
printf("\nDigits: %d",digits);
printf("\nSpecial characters: %d\n", c-specc-vowels-consonants-digits);
fclose(fp);
}
Reading line by line from a file using fgets
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char * ch;
char line[80];
fp=fopen("a.txt","r");
if(fp==NULL)
{
printf("Error opening file..");
exit(1);
}
while((fgets(line,80,fp)!=NULL)
{
printf("%s",line);
}
fclose(fp);
}
Reading word by word using fscanf
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char t[100];
fp=fopen("a.txt","r");
if(fp==NULL)
{
printf("Error opening source file..");
exit(1);
}
while(fscanf(fp,"%s",t)==1)
{
printf("%s\n",t);
}
fclose(fp);
}
Write data to the file( char by char using putc/fputc function)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int ch;
fp=fopen("a.txt","w");
if(fp==NULL)
{
printf("Error opening file..");
exit(1);
}
do{
ch=getchar();
if (ch=='$') break;
putc(ch,fp); //fputc(ch,fp);
}
while(1);
fclose(fp);
}
Write data to the file( as strings using fputs function)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fp;
char t[80];
fp=fopen("a.txt","w");
if(fp==NULL)
{
printf("Error opening file..");
exit(1);
}
printf("Enter strings...type end to stop\n");
do{
fgets(t,80,stdin);
printf("%s\n",t);
if(strcmp(t,"end\n")==0 ) break;
fputs(t,fp);
}
while(1);
fclose(fp);
}
C Program to delete a specific line from a text file
#include <stdio.h>
int main()
{ FILE *fp1, *fp2; //consider 40 character string to store filename
char filename[40];
char c; int del_line, temp = 1;
//asks user for file name
printf("Enter file name: ");
//receives file name from user and stores in 'filename'
scanf("%s", filename);
//open file in read mode
fp1 = fopen(filename, "r");
c = getc(fp1); //until the last character of file is obtained
while (c != EOF)
{ printf("%c", c); //print current character and read next character
c = getc(fp1);
}
//rewind
rewind(fp1);
printf(" \n Enter line number of the line to be deleted:");
//accept number from user.
scanf("%d", &del_line);
//open new file in write mode
fp2 = fopen("copy.c", "w");
c = getc(fp1);
while (c != EOF)
{ c = getc(fp1);
if (c == '\n') temp++; //except the line to be deleted
if (temp != del_line) { //copy all lines in file copy.c putc(c, fp2); } } //close both the files. fclose(fp1);
fclose(fp2);
//remove original file
remove(filename);
//rename the file copy.c to original name
rename("copy.c", filename);
printf("\n The contents of file after being modified are as follows:\n");
fp1 = fopen(filename, "r");
c = getc(fp1);
while (c != EOF)
{ printf("%c", c);
c = getc(fp1);
}
fclose(fp1); return 0;
}
Write data to the file( as strings using fprintf)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
fp=fopen("a.txt","w");
if (fp==NULL)
{
printf("error opening file..\n");
exit(1);
}
else
{
fprintf(fp,"%s","Welcome\n");
fprintf(fp,"%s","to file handling in C\n");
}
fclose(fp);
}
Counting number of lines, characters and words in a file
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int ch;
int nl=0,nc=0,nw=0;
fp=fopen("a.txt","r");
if(fp==NULL)
{
printf("Error opening file..");
exit(1);
}
ch=getc(fp);
while(ch!=EOF)
{
if (ch=='\n') nl++;
if(ch==' ') nw++;
nc++;
ch=getc(fp);
}
fclose(fp);
printf("Number of lines=%d, Number of characters = %d,Number of words=%d\n",nl,nc,nw+nl);
}
Write a C program to read integers from a text file and count how many even and odd numbers are present. ( University question)
#include <stdio.h>
int main() {
FILE *file;
int num;
int evenCount = 0, oddCount = 0;
// Open the file in read mode
file = fopen("numbers.txt", "r");
// Check if file was opened successfully
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
// Read integers from the file until EOF
while (fscanf(file, "%d", &num) != EOF) {
if (num % 2 == 0)
evenCount++;
else
oddCount++;
}
// Close the file
fclose(file);
// Display the results
printf("Total even numbers: %d\n", evenCount);
printf("Total odd numbers : %d\n", oddCount);
return 0;
}
Write a C program to create a text file (input text through keyboard).Display the contents and size of the file created. ( University question)
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char filename[100], ch;
long size = 0;
printf("Enter the filename to create: ");
scanf("%s", filename);
getchar(); // To consume the newline after filename input
// Open file in write mode
fp = fopen(filename, "w");
if (fp == NULL) {
printf("Error creating file!\n");
return 1;
}
printf("Enter text (press Enter followed by Ctrl+D to stop):\n");
// Input text from keyboard and write to file
while ((ch = getchar()) != EOF) {
fputc(ch, fp);
}
fclose(fp);
// Reopen file in read mode to display contents and find size
fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error reading file!\n");
return 1;
}
printf("\nContents of the file '%s':\n\n", filename);
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
size++;
}
printf("\n\nSize of the file: %ld bytes\n", size);
fclose(fp);
return 0;
}
Cheking whether two files are identical or different
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1,*fp2;
int ca,cb;
char fname1[50],fname2[50];
printf("Enter the first file name...\n");
scanf("%s",fname1);
printf("Enter the second file name...\n");
scanf("%s",fname2);
fp1=fopen(fname1,"r");
fp2=fopen(fname2,"r");
if(fp1==NULL)
{
printf("Error opening file1..");
exit(1);
}
else if(fp2==NULL)
{
printf("Error opening file2..");
exit(1);
}
else
{
ca=getc(fp1);
cb=getc(fp2);
while(ca!=EOF && cb!=EOF && ca==cb)
{
ca=getc(fp1);
cb=getc(fp2);
}
fclose(fp1);
fclose(fp2);
if(ca==cb)
printf("Files are identical\n");
else if (ca!=cb)
printf("Files are different \n");
}
}
Copy one file to another character by character using getc and putc function( you can also use fgetc and fputc)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1,*fp2;
int ch;
char fname1[50],fname2[50];
printf("Enter the source file name...\n");
scanf("%s",fname1);
printf("Enter the destination file name...\n");
scanf("%s",fname2);
fp1=fopen(fname1,"r");
fp2=fopen(fname2,"w");
if(fp1==NULL)
{
printf("Error opening source file..");
exit(1);
}
else if(fp2==NULL)
{
printf("Error opening destination file..");
exit(1);
}
else
{
while((ch=fgetc(fp1))!=EOF)
{
fputc(ch,fp2);
}
}
fclose(fp1);
fclose(fp2);
printf("Files succesfully copied\n");
}
}
Copy one file to another after replacing lower case letters with corresponding uppercase letters.(university question)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1,*fp2;
int ch;
char fname1[50],fname2[50];
printf("Enter the source file name...\n");
scanf("%s",fname1);
printf("Enter the destination file name...\n");
scanf("%s",fname2);
fp1=fopen(fname1,"r");
fp2=fopen(fname2,"w");
if(fp1==NULL)
{
printf("Error opening source file..");
exit(1);
}
else if(fp2==NULL)
{
printf("Error opening destination file..");
exit(1);
}
else
{
while((ch=fgetc(fp1))!=EOF)
{
if(islower(ch)) ch=toupper(ch);
fputc(ch,fp2);
}
fclose(fp1);
fclose(fp2);
printf("Files succesfully copied\n");
}
}
Write a C program that: ( University question)
1. Creates a file named "output.txt".
2. Writes each character of the string "Learning C is fun!"
individually using the putc() function inside a loop.
3. Reopens the file in read mode and uses getc() to read each
character until the end of the file.
4. Ensure the file is properly closed after both operations.
#include <stdio.h>
int main() {
FILE *fp;
char str[] = "Learning C is fun!";
int i;
char ch;
/* 1. Create the file and write to it */
fp = fopen("output.txt", "w");
if (fp == NULL) {
printf("Error opening file for writing.\n");
return 1;
}
/* 2. Write each character individually using putc() */
for (i = 0; str[i] != '\0'; i++) {
putc(str[i], fp);
}
/* 4. Close the file after writing */
fclose(fp);
/* 3. Reopen the file in read mode */
fp = fopen("output.txt", "r");
if (fp == NULL) {
printf("Error opening file for reading.\n");
return 1;
}
/* Read each character until EOF using getc() */
while ((ch = getc(fp)) != EOF) {
putchar(ch); // display the character on screen
}
/* 4. Close the file after reading */
fclose(fp);
return 0;
}
Write a C program to replace vowels in a text file with character ‘x’.(university question)
#include <stdio.h>
#include <stdlib.h>
int isvowel(char ch)
{
ch=tolower(ch);
switch(ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return 1;
}
return 0;
}
int main()
{
FILE *fp1,*fp2;
int ch;
char fname1[50],fname2[50];
fp1=fopen("vow.dat","r");
fp2=fopen("x.dat","w");
if(fp1==NULL)
{
printf("Error opening source file..");
exit(1);
}
else if(fp2==NULL)
{
printf("Error opening destination file..");
exit(1);
}
else
{
while((ch=fgetc(fp1))!=EOF)
{
if(isvowel(ch)) ch='x';
fputc(ch,fp2);
}
fclose(fp1);
fclose(fp2);
//remove the original file
remove("vow.dat");
//rename the file temp file x.dat to original name
rename("x.dat", "vow.dat");
printf("Files successfully copied\n");
}
}
Copy one file to another line by line using fgets and fputs function
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1,*fp2;
int ch;
char fname1[50],fname2[50],t[80];
printf("Enter the source file name...\n");
scanf("%s",fname1);
printf("Enter the destination file name...\n");
scanf("%s",fname2);
fp1=fopen(fname1,"r");
fp2=fopen(fname2,"w");
if(fp1==NULL)
{
printf("Error opening source file..");
exit(1);
}
else if(fp2==NULL)
{
printf("Error opening destination file..");
exit(1);
}
else
{
while((fgets(t,sizeof(t),fp1)!=NULL))
{
fputs(t,fp2);
}
fclose(fp1);
fclose(fp2);
printf("Files succesfully copied\n");
}
}
Merging the contents of two files into a third file(university question)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1,*fp2,*fp3;
char t[100];
fp1=fopen("first.txt","r");
fp2=fopen("second.txt","r");
fp3=fopen("third.txt","w");
if(fp1==NULL||fp2==NULL)
{
printf("Error opening source file..");
exit(1);
}
else if(fp3==NULL)
{
printf("Error opening destination file..");
exit(1);
}
else
{
while((fgets(t,sizeof(t),fp1)!=NULL))
{
fputs(t,fp3);
}
while((fgets(t,sizeof(t),fp2)!=NULL))
{
fputs(t,fp3);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
printf("Files succesfully merged\n");
}
}
Reading numbers from a file and separating even and odd numbers into two different files(uq)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp,*fpe,*fpo;
int n;
fp=fopen("num.dat","r");
fpe=fopen("enum.dat","w");
fpo=fopen("onum.dat","w");
if (fp==NULL||fpe==NULL||fpo==NULL)
{
printf("error opening file..\n");
exit(1);
}
else
{
while(fscanf(fp,"%d",&n)==1)
{
if ( n%2==0)
fprintf(fpe,"%d\n",n);
else
fprintf(fpo,"%d\n",n);
}
fclose(fp);
fclose(fpe);
fclose(fpo);
}
}
Note: this program can also be written using putw() getw() function
Write Palindrome words from a file to a new file
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int palindrome(char str[50])
{
int i,j;
for(i=0,j=strlen(str)-1;i<j;i++,j--)
if(str[i]!=str[j]) return 0;
return 1;
}
int main()
{
FILE *fp1,*fp2;
char word[50];
fp1=fopen("words.txt","r");
fp2=fopen("palwords.txt","w");
while((fscanf(fp1,"%s",word))!=EOF)
{
if(palindrome(word)) fprintf(fp2,"%s\n",word);
}
fclose(fp1);
fclose(fp2);
}
Reading an array and writing to a file using fwrite and reading the file using fread
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int main()
{
int i,a[SIZE],b[SIZE];
FILE *fp;
printf("Enter 10 elements in array a...\n");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
fp=fopen("num.dat","w");
if(fp==NULL)
{
printf("error opening file..\n");
exit(1);
}
fwrite(a,sizeof(int),SIZE,fp);
fclose(fp);
/*opening the file and reading to array b*/
fp=fopen("num.dat","r");
if(fp==NULL)
{
printf("error opening file..\n");
exit(1);
}
fread(b,sizeof(int),SIZE,fp);
printf("array b is...\n");
for(i=0;i<10;i++)
printf("%d\n",b[i]);
fclose(fp);
}
Program for writing struct to file using fwrite
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person
{
int id;
char fname[20];
char lname[20];
};
int main ()
{
FILE *outfile;
// open file for writing
outfile = fopen ("person.dat", "w");
if (outfile == NULL)
{
fprintf(stderr, "\nError opend file\n");
exit (1);
}
struct person input1 = {1, "rohit", "sharma"};
struct person input2 = {2, "mahendra", "dhoni"};
// write struct to file
fwrite (&input1, sizeof(struct person), 1, outfile);
fwrite (&input2, sizeof(struct person), 1, outfile);
if(fwrite != 0)
printf("contents to file written successfully !\n");
else
printf("error writing file !\n");
return 0;
}
Write a C program to create a file and store information about a person, in terms of his name, age and salary.(university question)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person
{
char name[50];
int age;
int salary;
};
int main ()
{
FILE *outfile;
// open file for writing
outfile = fopen ("person.dat", "w");
if (outfile == NULL)
{
fprintf(stderr, "\nError opend file\n");
exit (1);
}
struct person input1 = {"rohit",45,20000};
struct person input2 = {"mahendra",25,15000};
// write struct to file
fwrite (&input1, sizeof(struct person), 1, outfile);
fwrite (&input2, sizeof(struct person), 1, outfile);
if(fwrite != 0)
printf("contents to file written successfully !\n");
else
printf("error writing file !\n");
return 0;
}
Program for reading struct using fread
This program will read the file person.dat file in the previous program.
#include <stdio.h>
#include <stdlib.h>
// struct person with 3 fields
struct person
{
int id;
char fname[20];
char lname[20];
};
int main ()
{
FILE *infile;
struct person input;
// Open person.dat for reading
infile = fopen ("person.dat", "r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening file\n");
exit (1);
}
// read file contents till end of file
while(fread(&input, sizeof(struct person), 1, infile))
printf ("id = %d name = %s %s\n", input.id,
input.fname, input.lname);
return 0;
}
A stock file contains item_code, item_name, quantity and reorder_level.Write a C program to create a stock file of N items. Write a function to list items with quantity less than reorder_level.
( University Question)
#include <stdio.h>
#include <stdlib.h>
// Define the structure for item
struct Item {
int item_code;
char item_name[50];
int quantity;
int reorder_level;
};
// Function to display items that need reordering
void displayReorderItems(const char *filename) {
FILE *fp;
struct Item it;
fp = fopen(filename, "r"); // Open the file in read mode
if (fp == NULL) {
printf("Error opening file!\n");
return;
}
printf("\nItems that need reordering:\n");
printf("----------------------------------------\n");
printf("Code\tName\t\tQty\tReorder Level\n");
while (fscanf(fp, "%d %s %d %d", &it.item_code, it.item_name, &it.quantity, &it.reorder_level) != EOF) {
// Display the item if quantity is less than reorder level
if (it.quantity < it.reorder_level) {
printf("%d\t%-15s\t%d\t%d\n", it.item_code, it.item_name, it.quantity, it.reorder_level);
}
}
fclose(fp); // Close the file
}
int main() {
FILE *fp;
struct Item it;
int n, i;
char filename[] = "stock.txt"; // Text file for storing stock data
fp = fopen(filename, "w"); // Open the file in write mode
if (fp == NULL) {
printf("Error creating file!\n");
return 1;
}
printf("Enter number of items: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("\nEnter details of item %d\n", i + 1);
printf("Item Code: ");
scanf("%d", &it.item_code);
printf("Item Name: ");
scanf(" %[^\n]", it.item_name); // Read string with spaces
printf("Quantity: ");
scanf("%d", &it.quantity);
printf("Reorder Level: ");
scanf("%d", &it.reorder_level);
// Write item details to the file
fprintf(fp, "%d %s %d %d\n", it.item_code, it.item_name, it.quantity, it.reorder_level);
}
fclose(fp); // Close the file after writing data
// Call function to display items that need reordering
displayReorderItems(filename);
return 0;
}
In a small firm, employee numbers are given in serial numerical order, that is 1, 2, 3, etc. − Create a file of employee data with following information: employee number, name, sex, gross salary. − If more employees join, append their data to the file. − If an employee with serial number 25 (say) leaves, delete the record by making gross salary 0. − If some employee’s gross salary increases, retrieve the record and update the salary. Write a program to implement the above operations.
Here's a full C program using structures and file handling to manage a basic employee database with the following operations:
-
Create/Add Employees
-
Append New Employee Data
-
Delete Employee by Setting Salary to 0
-
Update Gross Salary
-
Display All Records
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILENAME "employees.dat"
struct Employee {
int emp_no;
char name[50];
char sex;
float gross_salary;
};
void addEmployees(int count) {
FILE *fp = fopen(FILENAME, "ab"); // append binary
struct Employee emp;
if (!fp) {
printf("Error opening file!\n");
return;
}
for (int i = 0; i < count; i++) {
printf("\nEnter details for employee %d:\n", i + 1);
printf("Employee No: ");
scanf("%d", &emp.emp_no);
printf("Name: ");
scanf(" %[^\n]", emp.name);
printf("Sex (M/F): ");
scanf(" %c", &emp.sex);
printf("Gross Salary: ");
scanf("%f", &emp.gross_salary);
fwrite(&emp, sizeof(emp), 1, fp);
}
fclose(fp);
}
void deleteEmployee(int emp_no) {
FILE *fp = fopen(FILENAME, "rb+");
struct Employee emp;
if (!fp) {
printf("Error opening file!\n");
return;
}
while (fread(&emp, sizeof(emp), 1, fp)) {
if (emp.emp_no == emp_no) {
emp.gross_salary = 0;
fseek(fp, -sizeof(emp), SEEK_CUR);
fwrite(&emp, sizeof(emp), 1, fp);
printf("Employee %d marked as deleted (salary set to 0).\n", emp_no);
fclose(fp);
return;
}
}
printf("Employee not found.\n");
fclose(fp);
}
void updateSalary(int emp_no, float new_salary) {
FILE *fp = fopen(FILENAME, "rb+");
struct Employee emp;
if (!fp) {
printf("Error opening file!\n");
return;
}
while (fread(&emp, sizeof(emp), 1, fp)) {
if (emp.emp_no == emp_no) {
emp.gross_salary = new_salary;
fseek(fp, -sizeof(emp), SEEK_CUR);
fwrite(&emp, sizeof(emp), 1, fp);
printf("Salary updated for employee %d.\n", emp_no);
fclose(fp);
return;
}
}
printf("Employee not found.\n");
fclose(fp);
}
void displayEmployees() {
FILE *fp = fopen(FILENAME, "rb");
struct Employee emp;
if (!fp) {
printf("Error opening file!\n");
return;
}
printf("\nEmployee Records:\n");
printf("%-10s %-20s %-5s %-10s\n", "EmpNo", "Name", "Sex", "Salary");
while (fread(&emp, sizeof(emp), 1, fp)) {
if (emp.gross_salary > 0)
printf("%-10d %-20s %-5c %-10.2f\n", emp.emp_no, emp.name, emp.sex, emp.gross_salary);
}
fclose(fp);
}
int main() {
int choice, emp_no, count;
float new_salary;
do {
printf("\nEmployee Management Menu:\n");
printf("1. Add Employees\n");
printf("2. Delete Employee (Set Salary to 0)\n");
printf("3. Update Salary\n");
printf("4. Display Employees\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("How many employees to add? ");
scanf("%d", &count);
addEmployees(count);
break;
case 2:
printf("Enter employee number to delete: ");
scanf("%d", &emp_no);
deleteEmployee(emp_no);
break;
case 3:
printf("Enter employee number to update: ");
scanf("%d", &emp_no);
printf("Enter new gross salary: ");
scanf("%f", &new_salary);
updateSalary(emp_no, new_salary);
break;
case 4:
displayEmployees();
break;
case 5:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
} while (choice != 5);
return 0;
}
Random Access To File
There is no need to read each record sequentially, if we want to access a particular record. C supports these functions for random access file processing.
fseek()
ftell()
rewind()
fseek()This function is used for seeking the pointer position in the file at the specified byte.
Syntax:fseek(FILE *fp,long offset,int position)
Where
fp-file pointer ---- It is the pointer which points to the file.
offset -displacement ---- It is positive or negative.This is the number of bytes which are skipped backward (if negative) or forward( if positive) from the current position.This is attached with L because this is a long integer.
Pointer position:
This sets the pointer position in the file.
Value Pointer position
0 Beginning of file.
1 Current position
2 End of file
Ex:
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file,from this statement pointer position is skipped 10 bytes from the beginning of the file.
2)fseek( p,5L,1)
1 means current position of the pointer position.From this statement pointer position is skipped 5 bytes forward from the current position.
3)fseek(p,-5L,1)
From this statement pointer position is skipped 5 bytes backward from the current position.
ftell()
This function returns the value of the current pointer position in the file.The value is count from the beginning of the file.
Syntax: long ftell(FILE *fptr);
Where fptr is a file pointer.
rewind()
This function is used to move the file pointer to the beginning of the given file.
Syntax:
void rewind(FILE *fptr);
Where fptr is a file pointer.
Example program for fseek():Write a program to read last ‘n’ characters of the file using appropriate file functions(Here we need fseek() and fgetc()).
| #include<stdio.h> |
|
| #include<conio.h> |
|
| void main() |
|
| { |
|
| FILE *fp; |
|
| char ch; |
|
| clrscr(); |
|
| fp=fopen("file1.c", "r"); |
|
| if(fp==NULL) |
|
| printf("file cannot be opened"); |
|
| else |
|
| { |
|
| printf("Enter value of n to read last ‘n’ characters"); |
| scanf("%d",&n); |
|
| fseek(fp,-n,2); |
|
| while((ch=fgetc(fp))!=EOF) |
|
| { |
|
| printf("%c\t",ch); |
|
| } |
|
| } |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
Two persons want to access a file "sample.txt". First person want to read the data from the file. The second person want to read and write the data from and to the file simultaneously. Can you help them to do so by writing the corresponding programming codes?
first person
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fp = fopen("sample.txt", "r"); // Open in read-only mode
if (fp == NULL) {
printf("Error: Cannot open file for reading.\n");
return 1;
}
printf("Contents of the file:\n");
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
return 0;
}
second person
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fp = fopen("sample.txt", "r+"); // Open in read + write mode
if (fp == NULL) {
printf("Error: Cannot open file for read/write.\n");
return 1;
}
printf("Reading current contents:\n");
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
// Move file pointer to the end to write
fseek(fp, 0, SEEK_END);
fprintf(fp, "\nThis is a new line added by the second person.\n");
printf("\nNew line written to the file.\n");
fclose(fp);
return 0;
}
Programs to try 2.Open a text input file and count number of characters, words and lines in it; and store the results
in an output file.
3.Copy one file to another.
4.Merge the content of two files and copy to the other.
6.Create a structure employee with fields empid,name and salary.Write the structure into a file.
7.Write an integer array into a file.Read and display the array elements in reverse order.
8.Read last n characters from a file.
9.Find the palindrome words from a file and write it into a new file.
10.Write a C program to create a text file (input text through keyboard).Display the contents and size of the file created.
Comments
Post a Comment