Input output and File Handling
By Notes Vandar
Input output and File Handling
In C, input and output operations are fundamental for interacting with users and handling data files.
7.1 Concept of File handling
File handling in C involves using a set of functions to perform operations on files such as creating, reading, writing, and closing them. Here’s a detailed overview of the key concepts and functions involved in file handling:
1. File Pointers
A file pointer is a variable of type FILE
that is used to access files. It is returned by functions like fopen
and used in other file handling functions.
Declaration:
2. Opening a File
The fopen
function is used to open a file and returns a file pointer. If the file cannot be opened, it returns NULL
.
Syntax:
filename
: The name of the file to be opened.mode
: The mode in which to open the file. Common modes include:"r"
: Read-only mode."w"
: Write-only mode (creates a new file or truncates an existing file)."a"
: Append mode (writes data to the end of the file)."r+"
: Read and write mode."w+"
: Read and write mode (creates or truncates the file)."a+"
: Read and write mode (appends to the end of the file).
Example:
if (file == NULL) {
printf(“Error opening file.\n”);
return 1;
}
3. Writing to a File
To write data to a file, you can use functions like fprintf
, fwrite
, or fputs
.
Examples:
fprintf
: Writes formatted output.fprintf(file, “Hello, World!\n”);fwrite
: Writes binary data.int data = 123;
fwrite(&data, sizeof(int), 1, file);fputs
: Writes a string.fputs(“Hello, World!\n”, file);
4. Reading from a File
To read data from a file, use functions like fscanf
, fread
, or fgets
.
Examples:
fscanf
: Reads formatted input.int num;
fscanf(file, “%d”, &num);fread
: Reads binary data.int data;
fread(&data, sizeof(int), 1, file);fgets
: Reads a string.char buffer[100];
fgets(buffer, sizeof(buffer), file);
5. Closing a File
After completing file operations, it’s important to close the file using fclose
. This frees up resources and ensures that all data is properly written to the file.
Syntax:
Example:
6. File Error Handling
To check for errors in file operations, use functions like ferror
and clearerr
.
ferror
: Returns a non-zero value if an error has occurred.if (ferror(file)) {
printf(“Error reading from file.\n”);
}clearerr
: Clears the error indicators.clearerr(file);
7. File Positioning
You can move the file position indicator using functions like fseek
, ftell
, and rewind
.
fseek
: Moves the file position indicator to a specific location.fseek(file, 0, SEEK_SET); // Move to the beginning of the fileftell
: Returns the current position of the file indicator.long pos = ftell(file);rewind
: Moves the file position indicator to the beginning.rewind(file);
7.2 File Access methods
In C, file access methods refer to the ways you can read from and write to files. These methods determine how you interact with the file’s data. Here’s a breakdown of the common file access methods:
1. Sequential Access
Sequential access means reading or writing data in a linear fashion, from the beginning of the file to the end. This is the simplest and most common form of file access.
Example:
- Reading Sequentially:
FILE *file = fopen(“example.txt”, “r”);
if (file == NULL) {
printf(“Error opening file.\n”);
return 1;
}char buffer[100];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf(“%s”, buffer);
}fclose(file);
- Writing Sequentially:
FILE *file = fopen(“example.txt”, “w”);
if (file == NULL) {
printf(“Error opening file.\n”);
return 1;
}fprintf(file, “Hello, World!\n”);
fputs(“Welcome to file handling in C.\n”, file);fclose(file);
2. Random Access
Random access allows you to read from or write to a file at any location, not necessarily sequentially. This is useful for tasks where you need to access specific parts of the file directly.
Functions Used:
fseek
: Moves the file position indicator to a specific location.ftell
: Returns the current file position.rewind
: Resets the file position indicator to the beginning of the file.
Example:
FILE *file = fopen(“example.dat”, “r+”);
if (file == NULL) {
printf(“Error opening file.\n”);
return 1;
}
// Move to the 10th byte from the beginning
fseek(file, 10, SEEK_SET);
char buffer[100];
fread(buffer, sizeof(char), sizeof(buffer), file);
printf(“Data at position 10: %s\n”, buffer);
// Move back to the beginning
rewind(file);
// Write data at the beginning
fprintf(file, “Start of file data.\n”);
fclose(file);
3. Direct Access
Direct access (also known as indexed access) involves accessing a specific record or data element directly, based on its index or position. This method is often used in conjunction with binary files.
Example:
- Writing Binary Data:
FILE *file = fopen(“example.bin”, “wb”);
if (file == NULL) {
printf(“Error opening file.\n”);
return 1;
}int data = 1234;
fwrite(&data, sizeof(int), 1, file);fclose(file);
- Reading Binary Data:
FILE *file = fopen(“example.bin”, “rb”);
if (file == NULL) {
printf(“Error opening file.\n”);
return 1;
}int data;
fread(&data, sizeof(int), 1, file);
printf(“Read data: %d\n”, data);fclose(file);
4. File Modes
When opening a file, the mode you choose affects how you can access the file:
"r"
: Open for reading (file must exist)."w"
: Open for writing (creates a new file or truncates an existing file)."a"
: Open for appending (writes data to the end of the file)."r+"
: Open for reading and writing (file must exist)."w+"
: Open for reading and writing (creates a new file or truncates an existing file)."a+"
: Open for reading and writing (appends data to the end of the file).
7.3 Functions of file handling: fopen(), fclose(), fflush(), freopen()
In C, file handling functions are essential for managing files and performing operations like opening, closing, and manipulating file streams. Here’s a detailed look at some key file handling functions:
1. fopen()
Purpose: Opens a file and associates a file stream with it.
Syntax:
filename
: The name of the file to be opened.mode
: The mode in which to open the file (e.g.,"r"
for read,"w"
for write,"a"
for append).
Modes:
"r"
: Open for reading. The file must exist."w"
: Open for writing. Creates a new file or truncates an existing file."a"
: Open for appending. Data is written to the end of the file."r+"
: Open for reading and writing. The file must exist."w+"
: Open for reading and writing. Creates a new file or truncates an existing file."a+"
: Open for reading and writing. Appends data to the end of the file.
Example:
if (file == NULL) {
printf(“Error opening file.\n”);
return 1;
}
fprintf(file, “Hello, World!\n”);
fclose(file);
2. fclose()
Purpose: Closes an open file associated with a file pointer. It flushes the output buffer and deallocates resources associated with the file.
Syntax:
stream
: The file pointer to the file to be closed.
Return Value:
- Returns
0
if successful. - Returns
EOF
if an error occurs.
Example:
if (file != NULL) {
fprintf(file, “Hello, World!\n”);
fclose(file); // Close the file
}
3. fflush()
Purpose: Flushes the output buffer of a stream, forcing all buffered data to be written to the file. This is useful when you want to ensure that all data written to a file is actually saved immediately.
Syntax:
stream
: The file pointer associated with the stream to be flushed.
Return Value:
- Returns
0
if successful. - Returns
EOF
if an error occurs.
Example:
if (file != NULL) {
fprintf(file, “Hello, World!\n”);
fflush(file); // Flush the output buffer to ensure data is written to the file
fclose(file);
}
4. freopen()
Purpose: Reopens an existing file stream with a new file or mode. This function is often used to redirect input or output streams.
Syntax:
filename
: The name of the file to open.mode
: The mode in which to open the file (e.g.,"r"
,"w"
,"a"
).stream
: The existing file pointer to be associated with the new file.
Return Value:
- Returns the file pointer on success.
- Returns
NULL
on failure.
Example:
FILE *file = fopen(“example.txt”, “w”);
if (file != NULL) {
fprintf(file, “This will be written to example.txt\n”);
fclose(file);
}
FILE *newFile = freopen(“newfile.txt”, “w”, file);
if (newFile != NULL) {
fprintf(newFile, “This will be written to newfile.txt\n”);
fclose(newFile);
}
7.4 Formatted input out
Formatted input and output in C involve using functions that allow you to read and write data in a specific format. These functions are part of the C standard library and are used for handling text data with formatting requirements.
Formatted Output
1. printf()
The printf
function is used for formatted output. It allows you to print variables and constants to the console with specified formatting.
Syntax:
format
: A format string that specifies how subsequent arguments are converted for output....
: A variable number of arguments that are formatted according to the format string.
Format Specifiers:
%d
or%i
: Integer%f
: Floating-point number%s
: String%c
: Character%x
or%X
: Hexadecimal integer
Example:
#include <stdio.h>
int main() {
int age = 25;
float height = 5.9;
char name[] = “Alice”;
printf(“Name: %s\n”, name);
printf(“Age: %d\n”, age);
printf(“Height: %.1f\n”, height);
return 0;
}
Special Formatting:
- Width and Precision: Control the width and precision of the output.
%5d
: Integer with a width of 5 characters.%.2f
: Floating-point number with 2 decimal places.%10s
: String with a minimum width of 10 characters.
Example:
#include <stdio.h>
int main() {
int num = 42;
printf(“Number: %5d\n”, num); // Right-aligned within 5 characters
printf(“Float: %.3f\n”, 3.14159); // 3 decimal places
return 0;
}
Formatted Input
1. scanf()
The scanf
function is used for formatted input. It reads data from the standard input (usually the keyboard) and stores it in variables according to the specified format.
Syntax:
format
: A format string that specifies how input data is interpreted....
: Pointers to variables where the input data will be stored.
Format Specifiers:
%d
or%i
: Integer%f
: Floating-point number%s
: String (reads until whitespace)%c
: Character
Example:
#include <stdio.h>
int main() {
int age;
float height;
char name[50];
printf(“Enter your name: “);
scanf(“%s”, name); // Read a string (up to whitespace)
printf(“Enter your age: “);
scanf(“%d”, &age); // Read an integer
printf(“Enter your height: “);
scanf(“%f”, &height); // Read a floating-point number
printf(“Name: %s\n”, name);
printf(“Age: %d\n”, age);
printf(“Height: %.1f\n”, height);
return 0;
}
Special Input Handling:
- Width Specifier: Limits the number of characters read for a string.
%10s
: Read up to 10 characters into a string.
- Character Input:
scanf
reads single characters including whitespace.%c
: Read a single character.
Example:
#include <stdio.h>
int main() {
char str[10];
printf(“Enter a string (max 9 characters): “);
scanf(“%9s”, str); // Read up to 9 characters (leave space for null terminator)
printf(“You entered: %s\n”, str);
return 0;
}
7.5 Character input output
In C, character input and output involve functions that handle individual characters rather than strings or formatted data. These functions are part of the C standard library and allow you to read and write characters directly.
Character Output
1. putchar()
The putchar
function is used to write a single character to the standard output (usually the console).
Syntax:
char
: The character to be written.
Return Value: Returns the character written as an unsigned char
cast to an int
or EOF
on error.
Example:
#include <stdio.h>
int main() {
char c = ‘A’;
putchar(c); // Output: A
putchar(‘\n’); // Output: newline character
return 0;
}
2. fputc()
The fputc
function writes a single character to a specified file stream.
Syntax:
char
: The character to be written.stream
: The file pointer to the file where the character will be written.
Return Value: Returns the character written as an unsigned char
cast to an int
or EOF
on error.
Example:
#include <stdio.h>
int main() {
FILE *file = fopen(“example.txt”, “w”);
if (file != NULL) {
fputc(‘H’, file); // Write ‘H’ to the file
fclose(file);
}
return 0;
}
Character Input
1. getchar()
The getchar
function reads a single character from the standard input (usually the keyboard).
Syntax:
Return Value: Returns the character read as an unsigned char
cast to an int
, or EOF
on end-of-file or error.
Example:
#include <stdio.h>
int main() {
char c;
printf(“Enter a character: “);
c = getchar(); // Read a character from standard input
printf(“You entered: “);
putchar(c); // Output the character
putchar(‘\n’);
return 0;
}
2. fgetc()
The fgetc
function reads a single character from a specified file stream.
Syntax:
stream
: The file pointer from which the character will be read.
Return Value: Returns the character read as an unsigned char
cast to an int
, or EOF
on end-of-file or error.
Example:
#include <stdio.h>
int main() {
FILE *file = fopen(“example.txt”, “r”);
if (file != NULL) {
int c = fgetc(file); // Read a character from the file
if (c != EOF) {
putchar(c); // Output the character
}
fclose(file);
}
return 0;
}