File operations- handling text and binary files – read - write - seek,
command-line arguments.
File
• A file is a place on the disk where a group of related data is stored.
• naming a file, opening a file, reading data from a file, writing data to a
file, and closing a file.
• Text file − A text file contains data in the form of ASCII characters and
is generally used to store a stream of characters. Each line in a text file
ends with a new line character ("\n"), and generally has a ".txt"
extension.
• Binary file − A binary file contains data in raw bits (0 and 1). Different
application programs have different ways to represent bits and bytes
and use different file formats. The image files (.png, .jpg), the
executable files (.exe, .com), etc. are the examples of binary files.
FILE Pointer
• While working with file handling, you need a file pointer to store the
reference of the FILE structure returned by the fopen() function. The
file pointer is required for all file-handling operations.
• The fopen() function returns a pointer of the FILE type. FILE is a
predefined struct type in stdio.h and contains attributes such as the
file descriptor, size, and position, etc.
Opening (Creating) a File
FILE *fp = fopen("filename", "mode");
Text File Modes
Mode
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that
"r"
points to the first character in it. If the file cannot be opened fopen( ) returns NULL.
Open for writing in text mode. If the file exists, its contents are overwritten. If the file doesn’t exist, a
"w"
new file is created. Returns NULL, if unable to open the file.
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that
"a" points to the last character in it. It opens only in the append mode. If the file doesn’t exist, a new file is
created. Returns NULL, if unable to open the file.
Searches file. It is opened successfully fopen( ) loads it into memory and sets up a pointer that points
"r+"
to the first character in it. Returns NULL, if unable to open the file.
Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created.
"w+"
Returns NULL, if unable to open the file.
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that
"a+" points to the last character in it. It opens the file in both reading and append mode. If the file doesn’t
exist, a new file is created. Returns NULL, if unable to open the file.
Binary File Modes
Mode Meaning
"rb" Read binary
"wb" Write binary
"ab" Append binary
"rb+" or "r+b" Read & write binary
"wb+" or "w+b" Read & write binary (overwrite)
"ab+" or "a+b" Read & append binary
Existing Data
Mode File Must Exist File Created
Lost
r Yes No No
w No Yes Yes
a No Yes No
r+ Yes No No
w+ No Yes Yes
a+ No Yes No
Open a File
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE* fptr; // File pointer to store the value returned by fopen
fptr = fopen(“[Link]", "r"); // Opening the file in read mode
if (fptr == NULL) // checking if the file is opened successfully
printf("The file is not opened.");
else
printf("The file is created Successfully.");
return 0;
}
Create a File
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE* fptr; // File pointer
fptr = fopen("[Link]", "w"); // Creating file using fopen() with access mode "w"
if (fptr == NULL) // checking if the file is created
printf("The file is not opened.");
else
printf("The file is created Successfully.");
return 0;
}
Write to a File
Function Description
Similar to printf(), this function uses formatted string and
fprintf()
variable arguments list to print output to the file.
fputs() Prints the whole line in the file and a newline at the end.
fputc() Prints a single character into the file.
fputw() Prints a number to the file. (Not recommended)
This function writes the specified number of bytes to the binary
fwrite()
file.
#include<stdio.h>
int main() fprintf()
{
int i;
char str[50];
FILE *fptr = fopen("[Link]", "w"); //open file [Link] in write mode
if (fptr == NULL)
{
printf("Could not open file");
return 0;
}
printf("Enter names\n");
for (i = 1; i <= 3; i++)
{
scanf("%s", str);
fprintf(fptr,"%s\n", str);
}
fclose(fptr);
return 0;
}
fputs()
#include <stdio.h>
#include <string.h>
int main()
{
char str[20];
scanf("%s",str);
FILE* fp;
fp = fopen(“[Link]", "w");
fputs(str, fp);
fclose(fp);
return 0;
}
fputc()
#include <stdio.h>
#include <string.h>
int main()
{
char str[20];
scanf("%s",str);
FILE* fp;
fp = fopen("[Link]", "w");
int i=0;
do{
fputc(str[i],fp);
i++;
}
while(str[i]!='\0');
fclose(fp);
return 0;
}
fputc()
#include <stdio.h>
#include <string.h>
int main()
{
char str[20];
scanf("%s",str);
FILE* fp;
fp = fopen("[Link]", “a");
int i=0;
do{
fputc(str[i],fp);
i++;
}
while(str[i]!='\0');
fclose(fp);
return 0;
}
Read from a file
Function Description
Reads formatted input (int, float, string, etc.) from a file similar to
fscanf()
scanf()
fgets() Reads up to n-1 characters or until a newline (\n) is found
Reads one character from the file and moves the file pointer forward.
fgetc()
Returns the character or EOF on end-of-file/error.
fgetw() Prints a number to the file. (Not recommended)
fread() Reads blocks of binary data (structures, arrays) from a file.
fscanf()
#include <stdio.h>
int main() {
FILE *fp;
int id; float marks; char name[20];
fp = fopen("[Link]", "r");
if (fp == NULL) {
printf("File not found\n");
return 1;
}
fscanf(fp, "%d %f %s", &id, &marks, name);
printf("ID: %d\n", id);
printf("Marks: %.2f\n", marks);
printf("Name: %s\n", name);
fclose(fp);
return 0;
}
#include <stdio.h>
int main() {
FILE *fp;
int id; float marks; char name[20];
fp = fopen("[Link]", "r");
if (fp == NULL) {
printf("File not found\n");
return 1;
}
while (!feof(fp)) {
if (fscanf(fp, "%d %f %19s", &id, &marks, name) == 3) {
printf("ID: %d\n", id);
printf("Marks: %.2f\n", marks);
printf("Name: %s\n\n", name);
}
}
fclose(fp);
return 0;
}
fgets()
#include <stdio.h>
int main() { It stores the input into a character array and
FILE *fp; stops reading when it reaches a newline
character, the specified number of characters,
char line[100]; or end-of-file (EOF).
fp = fopen("[Link]", "r");
if (fp == NULL) { Returns NULL if an error occurs or the end-of-
file (EOF) is reached.
printf("File not found\n");
return 1;
}
while (fgets(line, sizeof(line), fp) != NULL) {
printf("%s", line);
}
fclose(fp);
return 0;
}
fgetc()
fgetc() is used to obtain input from a file single
#include <stdio.h> character at a time. This function returns the ASCII
int main() { code of the character read by the function.
FILE *fp; It returns the character present at position indicated
char ch; by file pointer. After reading the character, the file
fp = fopen("[Link]", "r"); pointer is advanced to next character.
if (fp == NULL) {
If pointer is at end of file or if an error occurs EOF file
printf("File not found\n");
is returned by this function.
return 1;
}
while ((ch = fgetc(fp)) != EOF)
printf("%c", ch);
fclose(fp);
return 0;
}
#include <stdio.h> if (count == 0) {
int main() { printf("No numbers in file\n");
FILE *fp; return 1;
int num, count = 0; }
float sum = 0.0, avg;
avg = sum / count;
/* Open file in read mode */
fp = fopen("[Link]", "r"); /* Reopen same file in append mode */
if (fp == NULL) { fp = fopen("[Link]", "a");
printf("File not found\n"); if (fp == NULL) {
return 1; printf("File cannot be opened for writing\n");
} return 1;
}
/* Read numbers and calculate sum */
while (fscanf(fp, "%d", &num) == 1) { /* Write result to the same file */
sum += num; fprintf(fp, "\nAverage = %.2f\n", avg);
count++;
} fclose(fp);
return 0;
fclose(fp); }
#include <stdio.h>
#include <stdlib.h> // for atoi() if (count == 0) {
printf("No numbers in file\n");
int main() { return 1;
FILE *fp; }
char line[100];
int num, count = 0; avg = sum / count;
float sum = 0.0, avg;
/* Open same file in append mode */
/* Open file in read mode */ fp = fopen("[Link]", "a");
fp = fopen("[Link]", "r"); if (fp == NULL) {
if (fp == NULL) { printf("File cannot be opened for writing\n");
printf("File not found\n"); return 1;
return 1; }
}
/* Write average to the same file */
/* Read each line using fgets */ fprintf(fp, "\nAverage = %.2f\n", avg);
while (fgets(line, sizeof(line), fp) != NULL) {
num = atoi(line); // convert string to integer fclose(fp);
sum += num; return 0;
count++; }
}
fclose(fp);
Seek
• seek means moving the file pointer to a specific position inside a file so that the
next read or write happens from that position.
int fseek(FILE *fp, long offset, int origin);
•fseek() returns 0 on success, non-zero on failure
•Offset is measured in bytes
•Mainly used in binary files
•Enables random access file handling
• Origin
• SEEK_SET → beginning of file
• SEEK_CUR → current position
• SEEK_END → end of file
#include <stdio.h> /* ---------- SEEK_CUR ---------- */
fseek(fp, 4, SEEK_CUR); // Move 4 bytes forward from
int main() { current
FILE *fp; ch = fgetc(fp);
char ch; printf("Using SEEK_CUR (from current): %c\n", ch);
/* Create file and write data */ /* ---------- SEEK_END ---------- */
fp = fopen("[Link]", "w+"); fseek(fp, -1, SEEK_END); // Move to last character
if (fp == NULL) { ch = fgetc(fp);
printf("File cannot be opened\n"); printf("Using SEEK_END (from end): %c\n", ch);
return 1;
} fclose(fp);
return 0;
fputs("ABCDEFGHIJ", fp); // 10 characters }
/* ---------- SEEK_SET ---------- */
fseek(fp, 0, SEEK_SET); // Move to beginning
ch = fgetc(fp);
printf("Using SEEK_SET (from beginning): %c\n", ch);
#include <stdio.h> printf("Data after fseek():\n");
int main() { /* Read characters from the new position */
FILE *fp; while ((ch = fgetc(fp)) != EOF) {
char ch; putchar(ch);
}
/* Create and write to a file */
fp = fopen("[Link]", "w+"); fclose(fp);
if (fp == NULL) { return 0;
printf("File cannot be opened\n"); }
return 1;
}
fputs("Welcome to File Handling in C", fp);
/* Move file pointer 11 bytes from beginning */
fseek(fp, 11, SEEK_SET);
fwrite()
• fwrite() is a binary file input/output function in C used to write data
directly to a file in binary form.
• It writes data exactly as it is stored in memory (byte by byte).
• size_t fwrite(const void *ptr, size_t size, size_t count, FILE *fp);
Parameter Meaning
ptr Address of the data to be written
size Size of one data item (in bytes)
count Number of data items
fp File pointer
Returns number of items successfully written
If return value < count → write error occurred
#include <stdio.h>
struct student {
int id;
char name[30];
float marks;
};
int main() {
FILE *fp;
struct student s;
printf("Enter Student ID : "); scanf("%d", &[Link]);
printf("Enter Student Name : "); scanf(" %[^\n]", [Link]);
printf("Enter Marks : "); scanf("%f", &[Link]);
fp = fopen("[Link]", "wb"); /* Open file in write binary mode */
if (fp == NULL) {
printf("File cannot be opened\n");
return 1;
}
fwrite(&s, sizeof(struct student), 1, fp); /* Write data to file */
printf("\nData written to file successfully.\n");
fclose(fp);
return 0;
}
fread()
• fread() is used to read data from a binary file into program memory in
blocks of fixed size.
• size_t fread(const void *ptr, size_t size, size_t count, FILE *fp);
Parameter Meaning
ptr Address of the data to be written
size Size of one data item (in bytes)
count Number of data items
fp File pointer
Returns the number of blocks successfully read.
#include <stdio.h>
struct student {
int id;
char name[30];
float marks;
};
int main() {
FILE *fp;
struct student s;
fp = fopen("[Link]", "rb"); // Read binary mode
if (fp == NULL) {
printf("File cannot be opened\n");
return 1;
}
printf("Student Records:\n");
while (fread(&s, sizeof(struct student), 1, fp) == 1) {/* Read until fread returns 0 */
printf("ID : %d\n Name : %s\n Marks : %.2f\n ", [Link], [Link], [Link]);
}
Command Line Arguments
• Command line arguments are values passed to a C program at the time of
execution, through the command prompt or terminal.
• They allow a program to take input without using scanf().
• Syntax int main(int argc, char *argv[])
• argc (Argument Count)
• Stores the total number of command line arguments.
• Includes the program name.
• argv (Argument Vector)
• An array of strings (char *).
• Each element stores one command line argument.
• argv[0] → Program name
• argv[1] → First argument
• argv[2] → Second argument
• Arguments are always strings
Example
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int a, b;
if (argc != 3) {
printf("Usage: program num1 num2\n");
return 1;
}
a = atoi(argv[1]);
b = atoi(argv[2]);
printf("Output of the program %s is %d\n", argv[0], a + b);
return 0;
}