- C Programming Tutorial
- C - Home
- Basics of C
- C - Introduction
- C - Features
- C - Basics
- C - History
- C - Structure of C Program
- C - Program Structure
- C - Hello World
- C - Compilation Process
- C - Comments
- C - Tokens
- C - Keywords
- C - Identifiers
- C - User Input
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Integer Promotions
- C - Type Conversion
- C - Type Casting
- C - Booleans
- Constants and Literals in C
- C - Constants
- C - Literals
- C - Escape sequences
- C - Format Specifiers
- Operators in C
- C - Operators
- C - Arithmetic Operators
- C - Relational Operators
- C - Logical Operators
- C - Bitwise Operators
- C - Assignment Operators
- C - Unary Operators
- C - Increment and Decrement Operators
- C - Ternary Operator
- C - sizeof Operator
- C - Operator Precedence
- C - Misc Operators
- Decision Making in C
- C - Decision Making
- C - if statement
- C - if...else statement
- C - nested if statements
- C - switch statement
- C - nested switch statements
- Loops in C
- C - Loops
- C - While loop
- C - For loop
- C - Do...while loop
- C - Nested loop
- C - Infinite loop
- C - Break Statement
- C - Continue Statement
- C - goto Statement
- Functions in C
- C - Functions
- C - Main Function
- C - Function call by Value
- C - Function call by reference
- C - Nested Functions
- C - Variadic Functions
- C - User-Defined Functions
- C - Callback Function
- C - Return Statement
- C - Recursion
- Scope Rules in C
- C - Scope Rules
- C - Static Variables
- C - Global Variables
- Arrays in C
- C - Arrays
- C - Properties of Array
- C - Multi-Dimensional Arrays
- C - Passing Arrays to Function
- C - Return Array from Function
- C - Variable Length Arrays
- Pointers in C
- C - Pointers
- C - Pointers and Arrays
- C - Applications of Pointers
- C - Pointer Arithmetics
- C - Array of Pointers
- C - Pointer to Pointer
- C - Passing Pointers to Functions
- C - Return Pointer from Functions
- C - Function Pointers
- C - Pointer to an Array
- C - Pointers to Structures
- C - Chain of Pointers
- C - Pointer vs Array
- C - Character Pointers and Functions
- C - NULL Pointer
- C - void Pointer
- C - Dangling Pointers
- C - Dereference Pointer
- C - Near, Far and Huge Pointers
- C - Initialization of Pointer Arrays
- C - Pointers vs. Multi-dimensional Arrays
- Strings in C
- C - Strings
- C - Array of Strings
- C - Special Characters
- C Structures and Unions
- C - Structures
- C - Structures and Functions
- C - Arrays of Structures
- C - Self-Referential Structures
- C - Lookup Tables
- C - Dot (.) Operator
- C - Enumeration (or enum)
- C - Structure Padding and Packing
- C - Nested Structures
- C - Anonymous Structure and Union
- C - Unions
- C - Bit Fields
- C - Typedef
- File Handling in C
- C - Input & Output
- C - File I/O (File Handling)
- C Preprocessors
- C - Preprocessors
- C - Pragmas
- C - Preprocessor Operators
- C - Macros
- C - Header Files
- Memory Management in C
- C - Memory Management
- C - Memory Address
- C - Storage Classes
- Miscellaneous Topics
- C - Error Handling
- C - Variable Arguments
- C - Command Execution
- C - Math Functions
- C - String Functions
- C - Static Keyword
- C - Random Number Generation
- C - Command Line Arguments
C Programming - C File I/O (File Handling)
![]() Share with a Friend |
C Programming - C File I/O (File Handling)
File I/O (File Handling) in C
In C, File I/O (Input/Output) refers to the process of reading data from files and writing data to files. The C standard library provides a set of functions for performing file operations. These functions are declared in the <stdio.h> header file and allow for both text and binary file handling.
Opening and Closing Files
Before reading or writing to a file, it must be opened using the fopen() function. After the operations are complete, the file must be closed using the fclose() function.
- Opening a File (fopen())
The fopen() function opens a file and returns a pointer to a FILE object. The FILE pointer is then used for subsequent operations like reading or writing to the file.
Syntax:
C
FILE *fopen(const char *filename, const char *mode);
- filename: The name of the file to be opened (with or without path).
- mode: The mode in which the file is to be opened. Common modes are:
- "r": Read mode. Opens a file for reading.
- "w": Write mode. Creates a new file for writing. If the file already exists, it is overwritten.
- "a": Append mode. Opens a file for appending at the end.
- "r+": Read and write mode. Opens a file for both reading and writing.
- "w+": Read and write mode. Creates a file if it doesn't exist and overwrites if it does.
- "a+": Read and append mode. Opens for reading and appending.
- Closing a File (fclose())
After performing file operations, it is essential to close the file using the fclose() function. This ensures that resources are freed up and the file is saved properly.
Syntax:
C
int fclose(FILE *stream);
- stream: The FILE pointer returned by fopen().
Example:
C
FILE *file = fopen("data.txt", "w");
if (file == NULL) {
printf("Error opening file.\n");
} else {
printf("File opened successfully.\n");
fclose(file);
}
Reading from a File
- fgetc() - Reads a single character from the file.
Syntax:
C
int fgetc(FILE *stream);
- stream: The pointer to the file from which to read.
- Returns the character read as an unsigned char cast to an int, or EOF if the end of the file is reached.
Example:
C
FILE *file = fopen("data.txt", "r");
char ch;
if (file != NULL) {
while ((ch = fgetc(file)) != EOF) {
putchar(ch); // Prints each character from the file
}
fclose(file);
}
- fgets() - Reads a line of text from the file.
Syntax:
C
char *fgets(char *str, int n, FILE *stream);
- str: Pointer to the character array where the input will be stored.
- n: The maximum number of characters to read (including the null terminator).
- stream: The pointer to the file from which to read.
- Returns the string read from the file (including the newline character) or NULL on error or end of file.
Example:
C
FILE *file = fopen("data.txt", "r");
char line[100];
if (file != NULL) {
while (fgets(line, sizeof(line), file)) {
printf("%s", line); // Prints each line from the file
}
fclose(file);
}
- fscanf() - Reads formatted input from a file.
Syntax:
C
int fscanf(FILE *stream, const char *format, ...);
- stream: The file pointer to read from.
- format: A format string containing format specifiers like %d, %f, %s, etc.
- Returns the number of items successfully read.
Example:
C
FILE *file = fopen("data.txt", "r");
int num;
if (file != NULL) {
fscanf(file, "%d", &num); // Reads an integer from the file
printf("Read integer: %d\n", num);
fclose(file);
}
Writing to a File
- fputc() - Writes a single character to a file.
Syntax:
C
int fputc(int character, FILE *stream);
- character: The character to write.
- stream: The pointer to the file to write to.
- Returns the character written as an unsigned char cast to an int, or EOF on error.
Example:
C
FILE *file = fopen("data.txt", "w");
if (file != NULL) {
fputc('A', file); // Writes character 'A' to the file
fclose(file);
}
- fputs() - Writes a string to a file.
Syntax:
C
int fputs(const char *str, FILE *stream);
- str: The string to write to the file.
- stream: The pointer to the file to write to.
- Returns a non-negative number on success, EOF on error.
Example:
C
FILE *file = fopen("data.txt", "w");
if (file != NULL) {
fputs("Hello, File!", file); // Writes the string to the file
fclose(file);
}
- fprintf() - Writes formatted output to a file.
Syntax:
C
int fprintf(FILE *stream, const char *format, ...);
- stream: The file pointer to write to.
- format: A format string containing format specifiers (e.g., %d, %f).
- Returns the number of characters written, or a negative value on error.
Example:
C
FILE *file = fopen("data.txt", "w");
if (file != NULL) {
fprintf(file, "Name: %s, Age: %d\n", "John", 25); // Writes formatted data
fclose(file);
}
Binary File Handling
Binary file operations are similar to text file operations, but binary files allow the storage of data in a binary format. This is useful for non-text data (e.g., images, audio, or custom data formats).
- Opening a Binary File ("rb", "wb", "rb+", "wb+")
- "rb": Open for reading binary.
- "wb": Open for writing binary.
- "rb+": Open for both reading and writing binary.
- "wb+": Open for both reading and writing binary (creates a new file).
- Reading from a Binary File
Use fread() to read data from a binary file.
Syntax:
C
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
- ptr: Pointer to the memory block where data will be stored.
- size: Size of each element to read.
- count: Number of elements to read.
- stream: The file pointer.
Example:
C
FILE *file = fopen("data.bin", "rb");
int num;
if (file != NULL) {
fread(&num, sizeof(int), 1, file); // Reads an integer from the binary file
printf("Number from binary file: %d\n", num);
fclose(file);
}
- Writing to a Binary File
Use fwrite() to write data to a binary file.
Syntax:
C
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
- ptr: Pointer to the memory block containing data to write.
- size: Size of each element to write.
- count: Number of elements to write.
- stream: The file pointer.
Example:
C
FILE *file = fopen("data.bin", "wb");
int num = 42;
if (file != NULL) {
fwrite(&num, sizeof(int), 1, file); // Writes an integer to the binary file
fclose(file);
}
File Positioning
- fseek() - Moves the file pointer to a specific location.
Syntax:
C
int fseek(FILE *stream, long int offset, int origin);
- offset: The number of bytes to move.
- origin: The starting point. It can be SEEK_SET, SEEK_CUR, or SEEK_END.
- ftell() - Returns the current position of the file pointer.
Syntax:
C
long int ftell(FILE *stream);
- rewind() - Resets the file pointer to the beginning of the file.
Syntax:
C
void rewind(FILE *stream);
Conclusion
File handling in C is an essential feature for persistent storage. Using the standard I/O functions (fopen(), fclose(), fread(), fwrite(), etc.), you can read from and write to both text and binary files. It's crucial to open files in the appropriate mode, perform file operations efficiently, and close files when done to prevent resource leaks.
