1.  Opening a File: fopen()

To work with files in C, the fopen() function is used to open a file. It takes two parameters: the file name and the mode of operation (e.g., read, write, append).

FILE *filePointer = fopen(“filename.txt”, “mode”);

File Modes:

  • “r”: Opens a file for reading (fails if the file doesn’t exist).
  • `”w”`: Opens a file for writing (creates a new file or truncates an existing one).
  • `”a”`: Opens a file for appending (writes data at the end).
  • `”r+”`: Opens a file for both reading and

 

 

2.  Closing a File: fclose()

After operations are done, the file should be closed using the `fclose()` function to free the resources.

fclose(filePointer);

 

 

3.  Reading from a File: fscanf(), fgets(), and fgetc()

  • fscanf(): Similar to scanf(), but for

fscanf(filePointer, “%d”, &var);

  • fgets(): Reads a line from the file, ideal for reading

fgets(buffer, size, filePointer);

  • fgetc(): Reads a single character from the

char ch = fgetc(filePointer);

 

 

4.  Writing to a File: fprintf(), fputs(), and fputc()

  • fprintf(): Similar to printf(), but writes to a

fprintf(filePointer, “Data: %d”, value);

  • fputs(): Writes a string to a

fputs(“Hello, World!”, filePointer);

 

  • fputc(): Writes a single character to a

fputc(‘A’, filePointer);

 

 

5.  Checking for End-of-File (EOF): feof()

The feof() function checks if the end of the file is reached.

if (feof(filePointer)) {

printf(“End of file reached.\n”);

}

7.  File Positioning: ftell(), fseek(), and rewind()

  • ftell(): Returns the current position in the

long position = ftell(filePointer);

  • fseek(): Moves the file pointer to a specific

fseek(filePointer, offset, SEEK_SET);

  • SEEK_SET: Beginning of the
  • SEEK_CUR: Current
  • SEEK_END: End of the
  • rewind(): Moves the file pointer back to the

rewind(filePointer);

 

 

8.  Binary File Operations: fread() and fwrite()

Binary files store data in binary format (unlike text files). To handle binary files, C provides:

  • fread(): Reads binary data from a

fread(buffer, size, count, filePointer);

  • fwrite(): Writes binary data to a

fwrite(buffer, size, count, filePointer);

 

9.  Error Handling: perror() and ferror()

  • perror(): Displays an error message if file operations

perror(“Error opening file”);

  • ferror(): Checks if an error occurred during a file

if (ferror(filePointer)) { printf(“Error reading file.\n”);

}

 

 

10.  Removing and Renaming Files

  • remove(): Deletes a

remove(“filename.txt”);

  • rename(): Renames a

rename(“oldname.txt”, “newname.txt”);

 

Code 1: #include<stdio.h> int main()

{

FILE *fp;

char filename[]=”my_file.txt”;

 

 

fp=fopen(filename,”w”);

 

 

fprintf(fp,”We are learning file operations in c\n”); fprintf(fp,”Hello People\n”);

 

fclose(fp);

 

 

fp=fopen(filename,”a”); fprintf(fp,”Hello World\n”);

 

return 0;

}

Code 2:

//Writing to a file #include <stdio.h> #include <stdlib.h>

 

int main()

{

struct student

{

int age;

 

char name[30]; int CGPA;

}student1;

 

 

FILE *fptr;

 

 

// use appropriate location if you are using MacOS or Linux fptr = fopen(“program.txt”,”w”);

 

if(fptr == NULL)

{

printf(“Error!”); exit(1);

}

 

 

printf(“Enter Student’s name: “); scanf(“%s”,&student1.name);

 

printf(“Enter Student’s age: “); scanf(“%d”,&student1.age);

 

printf(“Enter Student’s CGPA: “); scanf(“%d”,&student1.CGPA);

 

fprintf(fptr,”%s\t %d\t %d\t”,student1.name,student1.age,student1.CGPA); fclose(fptr);

 

return 0;

}

 

Code 3:

//reading from a file #include <stdio.h> #include <stdlib.h>

 

int main()

{

char name[30];

char input_name[30]; int cmp_result;

FILE *fptr;

 

 

if ((fptr = fopen(“program.txt”,”r”)) == NULL){ printf(“Error! opening file”);

 

// Program exits if the file pointer returns NULL. exit(1);

}

scanf(“%s”,input_name); fscanf(fptr,”%s”, &name);

 

cmp_result=strcmp(input_name,name);

 

 

printf(“Value of comparing result is =%d”, cmp_result);

 

 

fclose(fptr);

 

 

return 0;

}

 

Code 4:

#include<stdio.h> struct student

{

int rollno;

char name[30]; float mark;

}stud;

//    FUNCTION TO INSERT RECORDS TO THE FILE

void insert()

{

FILE *fp;

fp = fopen(“Record.txt”, “a”); printf(“Enter the Roll no :”); scanf(“%d”, &stud.rollno); printf(“Enter the Name      :”); scanf(“%s”, &stud.name); printf(“Enter the mark                                         :”); scanf(“%f”, &stud.mark);

//fwrite(&stud, sizeof(stud), 1, fp);

fprintf(fp,”%d %s %.1f\n”,stud.rollno,stud.name,stud.mark); fclose(fp);

}

//    FUNCTION TO DISPLAY RECORDS

void disp()

{

FILE *fp1;

fp1 = fopen(“Record.txt”, “r”); printf(“\nRoll Number\tName\tMark\n\n”); while (fread(&stud, sizeof(stud), 1, fp1))

 

printf(” %d\t\t%s\t%.2f\n”, stud.rollno, stud.name, stud.mark); fclose(fp1);

}

//    FUNCTION TO SEARCH THE GIVEN RECORD

void search()

{

FILE *fp2; int r, s, avl;

printf(“\nEnter the Roll no you want to search :”); scanf(“%d”, &r);

avl = avlrollno(r); if (avl == 0)

printf(“Roll No %d is not available in the file\n”,r); else

{

fp2 = fopen(“Record.txt”, “r”);

while (fread(&stud, sizeof(stud), 1, fp2))

{

s = stud.rollno; if (s == r)

{

printf(“\nRoll no = %d”, stud.rollno); printf(“\nName                            = %s”, stud.name); printf(“\nMark                          = %.2f\n”, stud.mark);

}

}

fclose(fp2);

}

}

//    FUNCTION TO DELETE A RECORD

 

 

void deletefile()

{

FILE *fpo; FILE *fpt; int r, s;

printf(“Enter the Roll no you want to delete :”); scanf(“%d”, &r);

if (avlrollno(r) == 0)

printf(“Roll no %d is not available in the file\n”, r); else

{

fpo = fopen(“Record.txt”, “r”); fpt = fopen(“TempFile.txt”, “w”);

while (fread(&stud, sizeof(stud), 1, fpo))

{

s = stud.rollno; if (s != r)

fwrite(&stud, sizeof(stud), 1, fpt);

}

fclose(fpo); fclose(fpt);

fpo = fopen(“Record.txt”, “w”); fpt = fopen(“TempFile.txt”, “r”);

while (fread(&stud, sizeof(stud), 1, fpt)) fwrite(&stud, sizeof(stud), 1, fpo); printf(“\nRECORD DELETED\n”); fclose(fpo);

fclose(fpt);

 

}

 

 

}

//    FUNCTION TO UPDATE THE RECORD

void update()

{

int avl; FILE *fpt; FILE *fpo; int s, r, ch;

printf(“Enter roll number to update:”); scanf(“%d”, &r);

avl = avlrollno(r); if (avl == 0)

{

printf(“Roll number %d is not Available in the file”, r);

}

else

{

fpo = fopen(“Record.txt”, “r”); fpt = fopen(“TempFile.txt”, “w”);

while (fread(&stud, sizeof(stud), 1, fpo))

{

s = stud.rollno; if (s != r)

fwrite(&stud, sizeof(stud), 1, fpt); else

{

printf(“\n\t1. Update Name of Roll Number %d”, r); printf(“\n\t2. Update Mark of Roll Number %d”, r);

 

printf(“\n\t3. Update both Name and Mark of Roll Number %d”, r); printf(“\nEnter your choice:”);

scanf(“%d”, &ch); switch (ch)

{

case 1:

printf(“Enter Name:”); scanf(“%s”, &stud.name); break;

case 2:

printf(“Enter Mark : “); scanf(“%f”, &stud.mark); break;

case 3:

printf(“Enter Name: “); scanf(“%s”, &stud.name); printf(“Enter Mark: “); scanf(“%f”, &stud.mark); break;

default:

printf(“Invalid Selection”); break;

}

fwrite(&stud, sizeof(stud), 1, fpt);

}

}

fclose(fpo); fclose(fpt);

fpo = fopen(“Record.txt”, “w”); fpt = fopen(“TempFile.txt”, “r”);

 

while (fread(&stud, sizeof(stud), 1, fpt))

{

fwrite(&stud, sizeof(stud), 1, fpo);

}

fclose(fpo); fclose(fpt);

printf(“RECORD UPDATED”);

}

}

/* FUNCTION TO SORT THE RECORD */

void sort()

{

int a[20], count = 0, i, j, t, c; FILE *fpo;

fpo = fopen(“Record.txt”, “r”);

while (fread(&stud, sizeof(stud), 1, fpo))

{

a[count] = stud.rollno; count++;

}

c = count;

for (i = 0; i<count – 1; i++)

{

for (j = i + 1; j<count; j++)

{

if (a[i]>a[j])

{

t = a[i]; a[i] = a[j]; a[j] = t;

 

}

}

}

printf(“Roll No.\tName\t\tMark\n\n”); count = c;

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

{

rewind(fpo);

while (fread(&stud, sizeof(stud), 1, fpo))

{

if (a[i] == stud.rollno)

printf(“\n %d\t\t %s \t\t %2f”,stud.rollno, stud.name, stud.mark);

}

 

 

}

}

//    FUNCTION TO CHECK GIVEN ROLL NO IS AVAILABLE //

int avlrollno(int rno)

{

FILE *fp; int c = 0;

fp = fopen(“Record.txt”, “r”); while (!feof(fp))

{

fread(&stud, sizeof(stud), 1, fp);

 

 

if (rno == stud.rollno)

{

fclose(fp); return 1;

 

}

}

fclose(fp); return 0;

}

//FUNCTION TO CHECK THE FILE IS EMPTY OR NOT

int empty()

{

int c = 0; FILE *fp;

fp = fopen(“Record.txt”, “r”);

while (fread(&stud, sizeof(stud), 1, fp)) c = 1;

fclose(fp); return c;

}

// MAIN PROGRAM

void main()

{

int c, emp; do

{

printf(“\n\t—Select your choice——– \n”);

printf(“\n\t1. INSERT\n\t2. DISPLAY\n\t3. SEARCH”); printf(“\n\t4. DELETE\n\t5. UPDATE\n\t6. SORT”); printf(“\n\t7. EXIT”);

printf(“\n\n                                                   \n”);

printf(“\nEnter your choice:”); scanf(“%d”, &c);

printf(“\n”);

 

switch (c)

{

case 1:

insert(); break; case 2:

emp = empty(); if (emp == 0)

printf(“\nThe file is EMPTY\n”); else

disp(); break; case 3:

search(); break; case 4:

deletefile(); break;

case 5:

update(); break; case 6:

emp = empty(); if (emp == 0)

printf(“\n The file is EMPTY\n”); else

sort(); break; case 7: exit(1);

 

break; default:

printf(“\nYour choice is wrong\nPlease try again…\n”); break;

 

}

} while (c != 7);

}

Code 5:

// C program to illustrate fgetc() function

//fgetc() is used to obtain input from a file single character at a time. #include <stdio.h>

 

int main ()

{

// open the file

FILE *fp = fopen(“test.txt”,”r”);

 

 

// Return if could not open file if (fp == NULL)

return 0;

 

 

do

{

// Taking input single character at a time char c = fgetc(fp);

 

// Checking for end of file if (feof(fp))

break ;

 

printf(“%c”, c);

} while(1);

 

 

fclose(fp); return(0);

}

Code 6:

// C program to illustrate fputc() function #include<stdio.h>

int main()

{

int i = 0;

FILE *fp = fopen(“output.txt”,”w”);

 

 

// Return if could not open file if (fp == NULL)

return 0;

 

 

char string[] = “good bye”, received_string[20];

 

 

for (i = 0; string[i]!=’\0′; i++)

 

 

// Input string into the file

// single character at a time fputc(string[i], fp);

 

fclose(fp);

fp = fopen(“output.txt”,”r”);

 

// Reading the string from file fgets(received_string,20,fp);

 

printf(“%s”, received_string);

 

 

fclose(fp); return 0;

}

By Md Jakaria Nur

Software Engineer

Leave a Reply

Your email address will not be published. Required fields are marked *