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
openoperation. -
A stream is disassociated from a file using the
closeoperation. -
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
| Feature | Text File | Binary File |
|---|---|---|
| Readability | Human-readable | Not human-readable (stored in 0s and 1s) |
| Newline handling | \n converted to carriage return-linefeed on disk | No conversion occurs |
| End-of-file marker | Special character (ASCII 26) marks EOF | No special character; EOF detected by software |
| Storage of data | Characters stored 1 byte each; integers occupy more space | Data stored in memory format; integer occupies same size as in memory |
| Data format | Usually line-oriented; each line is a separate command | Requires 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:
-
Declare a file pointer variable
-
Open a file using
fopen()function -
Process the file using suitable functions
-
Close the file using
fclose()function
1. Declaring a File Pointer Variable
To access a file, we need a pointer to the FILE structure:
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:
-
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
NULLif the file cannot be opened.
Example: Open a text file for reading
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 |
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.txtis created. -
The file is opened for writing.
-
The file pointer
fppoints to the beginning of the new file. -
If the file cannot be created (e.g., permission issues),
fopenreturnsNULL.
✔️ 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
fpis positioned at the beginning of the file. -
Any previous data in
data.txtis 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
-
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
-
File Descriptors/Handles:
Keeping files open without closing them may exhaust the available file descriptors, causing futurefopen()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 frommain()), 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
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:
-
Example:
2. fputs() Function
-
Purpose: Writes a string (line of characters) to a file.
-
Prototype:
-
Example:
3. getc() / fgetc() Function
-
Purpose: Reads a single character from a specified stream.
-
Note:
getc()andfgetc()are identical and can be used interchangeably. -
Prototype:
-
Example:
4. fgets() Function
-
Purpose: Reads a line of text (up to a specified number of characters) from a file.
-
Prototype:
-
Example:
5. fprintf() and fscanf() Functions
-
These work like
printf()andscanf(), but operate on files. -
Prototypes:
-
Examples:
6. putw() and getw() Functions
putw()
-
Purpose: Writes an integer to a file.
-
Syntax:
-
Example:
getw()
-
Purpose: Reads an integer from a file.
-
Syntax:
-
Example:
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:
Description:
-
Reads
numnumber of objects, each ofsizebytes, from the file associated withfp. -
Stores the read data into the memory pointed to by
buffer.
2. fwrite()
Prototype:
Description:
-
Writes
numnumber of objects, each ofsizebytes, from the memory pointed to bybuffer. -
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.
Read and display a file character by character using getc/fgetc function
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
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>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);
}
Write a C program to open an existing file 'notes.txt' in append mode. Add a new line of text entered by the user and close the file after writing
int main() {
FILE *fp;
char text[200];
// Open notes.txt in append mode
fp = fopen("notes.txt", "a");
// Check if file opened successfully
if (fp == NULL) {
printf("Unable to open file.\n");
return 1;
}
// Get input from user
printf("Enter a line of text: ");
fgets(text, sizeof(text), stdin);
// Write text to file
fputs(text, fp);
// Close the file
fclose(fp);
printf("Text added successfully.\n");
return 0;
}
Counting number of lines, characters and words in a file
Write a C program to read integers from a text file and count how many even and odd numbers are present. ( University question)
Write a C program to create a text file (input text through keyboard).Display the contents and size of the file created. ( University question)
Cheking whether two files are identical or different
{
fputc(ch,fp2);
}
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);
}
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
4. Ensure the file is properly closed after both operations.character until the end of the file.
Write a C program to replace vowels in a text file with character ‘x’.(university question)
Copy one file to another line by line using fgets and fputs function
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)
Note: this program can also be written using putw() getw() function
Write Palindrome words from a file to a new file
#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
Program for writing struct to file using fwrite
#include <stdio.h>#include <stdlib.h>
#include <string.h>
struct person
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
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.
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
Random Access To File
This function is used for seeking the pointer position in the file at the specified byte.
Syntax:
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.
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)
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); |
Comments
Post a Comment