Files in C

 

Files in C

A file is a repository of data stored in permanent storage media, mainly in secondary memory. To work with files in C, we must know how to read from and write to files.

A key concept in C is the stream:

  • A stream is a logical interface to various devices, such as files.

  • A stream is linked to a file using the open operation.

  • A stream is disassociated from a file using the close operation.

  • The current location (or current position) is the location in a file where the next file access will occur.

There are two types of streams: text and binary.


Difference Between Text and Binary Files

FeatureText FileBinary File
ReadabilityHuman-readableNot human-readable (stored in 0s and 1s)
Newline handling\n converted to carriage return-linefeed on diskNo conversion occurs
End-of-file markerSpecial character (ASCII 26) marks EOFNo special character; EOF detected by software
Storage of dataCharacters stored 1 byte each; integers occupy more spaceData stored in memory format; integer occupies same size as in memory
Data formatUsually line-oriented; each line is a separate commandRequires matching software to read/write (e.g., MP3 player, Image Viewer)

Using Files in C

There are four steps to working with files in C:

  1. Declare a file pointer variable

  2. Open a file using fopen() function

  3. Process the file using suitable functions

  4. Close the file using fclose() function


1. Declaring a File Pointer Variable

To access a file, we need a pointer to the FILE structure:

FILE *fp;

A file pointer contains information such as:

  • File size

  • Current file position

  • Type of file

It allows the program to perform operations on the file.


2. Opening a File Using fopen()

The fopen() function opens a file in a specified mode.

Syntax:

fp = fopen(char *filename, char *mode);
  • filename — Name of the file to open

  • mode — Purpose of opening the file (read, write, append, etc.)

Behavior:

  • Returns a pointer to the file if it is opened successfully.

  • Returns NULL if the file cannot be opened.

Example: Open a text file for reading

#include <stdio.h> #include <stdlib.h> void main() { FILE *fp; // Open existing file in read mode fp = fopen("file1.txt", "r"); // Statement 1 if (fp == NULL) { printf("\nCan't open file or file doesn't exist."); exit(0); } // File successfully opened; further operations go here fclose(fp); // Always close the file after use }

Explanation:

  • fopen("file1.txt", "r") opens the file in read mode.

  • If the file does not exist, the program prints an error and exits.


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:

FILE *fp = fopen("data.txt", "w");

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

ScenarioResult
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:

  1. Flushes any unwritten data from memory.

  2. Discards any unread buffered input.

  3. Frees any automatically allocated buffer.

  4. Finally, closes the file.

Syntax

int fclose(FILE *fp);

Example

#include <stdio.h> #include <stdlib.h> void main() { FILE *fp; fp = fopen("file1.txt", "r"); // Open file in read mode if (fp == NULL) { printf("\nCan't open file or file doesn't exist."); exit(0); } // --- perform file operations here --- fclose(fp); // Close the file }

Notes

  • A stream’s buffer can be flushed without closing the file using the fflush() function.

  • flushall() can be used to flush all open streams.


Why Closing Files is Important

  1. File Descriptors/Handles:
    Keeping files open without closing them may exhaust the available file descriptors, causing future fopen() calls to fail.

  2. 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.

  3. 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

  • Purpose: Writes a single character to a specified stream.

  • Prototype:

int putc(int ch, FILE *fp);
  • Example:

char c = 'x'; FILE *fp = fopen("abc.txt", "w"); putc(c, fp); // or fputc(c, fp) // Character 'x' is written to the file abc.txt

2. fputs() Function

  • Purpose: Writes a string (line of characters) to a file.

  • Prototype:

int fputs(const char *str, FILE *fp);
  • Example:

char str[] = "cek"; FILE *fp = fopen("abc.txt", "w"); fputs(str, fp); // String "cek" is written to file abc.txt

3. getc() / fgetc() Function

  • Purpose: Reads a single character from a specified stream.

  • Note: getc() and fgetc() are identical and can be used interchangeably.

  • Prototype:

int getc(FILE *fp);
  • Example:

FILE *fp = fopen("abc.txt", "r"); int c; c = fgetc(fp); // Reads a single character from the file

4. fgets() Function

  • Purpose: Reads a line of text (up to a specified number of characters) from a file.

  • Prototype:

char *fgets(char *str, int n, FILE *fp);
  • Example:

FILE *fp = fopen("abc.txt", "r"); char line[60]; char *c; c = fgets(line, 60, fp); // Reads a line into 'line'

5. fprintf() and fscanf() Functions

  • These work like printf() and scanf(), but operate on files.

  • Prototypes:

int fprintf(FILE *fp, const char *format, ...); int fscanf(FILE *fp, const char *format, ...);
  • Examples:

FILE *fp = fopen("abc.txt", "w"); fprintf(fp, "%s", "cek"); // Writes string to file FILE *fp = fopen("abc.txt", "r"); int n; fscanf(fp, "%d", &n); // Reads integer from file

6. putw() and getw() Functions

putw()

  • Purpose: Writes an integer to a file.

  • Syntax:

putw(int number, FILE *fp);
  • Example:

int n = 42; putw(n, fp); // Writes integer 42 to file

getw()

  • Purpose: Reads an integer from a file.

  • Syntax:

int getw(FILE *fp);
  • Example:

int num; while ((num = getw(fp)) != EOF) { printf("\n%d", num); // Prints integers read from the file }

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

  • Direct I/O is used only with binary-mode files.

  • It allows blocks of data to be read or written directly between memory and disk.

  • For example:

    • A single direct-output function can write an entire array to disk.

    • A single direct-input function can read an entire array from disk into memory.


Functions for Direct I/O

The C file system provides two important functions for direct I/O:

1. fread()

Prototype:

size_t fread(void *buffer, size_t size, size_t num, FILE *fp);

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:

size_t fwrite(void *buffer, size_t size, size_t num, FILE *fp);

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:

FunctionPurpose
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:

  1. Create/Add Employees

  2. Append New Employee Data

  3. Delete Employee by Setting Salary to 0

  4. Update Gross Salary

  5. 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);


            }


      }























    fclose(fp);
}

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 

1.Create a file and perform the following
i) Write data to the file
ii) Read the data in a given file & display the file content on console
iii) append new data and display on console
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.
5.Read numbers from a file and separate even and odd numbers into two different files.
6.Create a structure employee with fields empid,name and salary.Write the structure into a file.
Read and display employee details from the file ( use fread and fwrite)
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

Popular posts from this blog

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Functions in C