File Handling#
Overview#
Definition
File Input/Output (I/O) refers to the process of reading data from files or writing data to files in a computer program. This functionality allows programs to store and retrieve information persistently, making it useful for various tasks like saving configurations, storing user data, or processing large datasets.
Use Cases
Reading configuration files to set program parameters.
Saving and loading game progress or user data in games or applications.
Processing large datasets, such as reading from CSV files.
Logging information, debugging, and error handling.
Creating and managing databases.
Pros & Cons
Data Persistence
Files allow data to be stored beyond the program’s runtime, making it available for future use.
Data Sharing
Files enable data exchange between different programs and systems.
Scalability
FIle I/O can handle large volumes of data efficiently.
Portability
Files can be easily transformed between different platforms
Slower Access
Reading from and writing to files is generally slower compared to in-memory operations.
Error Handling
File operations can lead to potential errors, such as file not found or permissions issues.
Security Risks
Improper handling of files can lead to security vulnerabilities.
Syntax#
Open "data.txt" for reading
if the file is opened successfully:
Read data from the file
Close the file
else:
Display an error message
1// In this C++ code, we use the ifstream class to open the file in input mode.
2// We then use a while loop to read the integers one by one until the end of the file.
3
4#include <iostream>
5#include <fstream>
6using namespace std;
7
8int main() {
9 ifstream inputFile("data.txt");
10 if (inputFile.is_open()) {
11 int num;
12 while (inputFile >> num) {
13 cout << num << " ";
14 }
15 inputFile.close();
16 } else {
17 cout << "Error opening file.";
18 }
19 return 0;
20}
1# In Python, we use a with statement to open the file, which automatically closes
2# the file after reading. We read the file contents, split the data into numbers,
3# and then print each number.
4
5try:
6 with open("data.txt", "r") as inputFile:
7 numbers = inputFile.read().split()
8 for num in numbers:
9 print(num, end=" ")
10except FileNotFoundError:
11 print("Error opening file.")
1// Java uses Scanner to read data from the file. The hasNextInt() method checks
2// if the file has more integers, and nextInt() reads the next integer.
3
4import java.io.File;
5import java.io.FileNotFoundException;
6import java.util.Scanner;
7
8public class FileIOJava {
9 public static void main(String[] args) {
10 try {
11 File file = new File("data.txt");
12 Scanner inputFile = new Scanner(file);
13 while (inputFile.hasNextInt()) {
14 int num = inputFile.nextInt();
15 System.out.print(num + " ");
16 }
17 inputFile.close();
18 } catch (FileNotFoundException e) {
19 System.out.println("Error opening file.");
20 }
21 }
22}
1// Rust provides File and BufReader for file handling. We read the file's contents
2// into a string and then split it by whitespace to extract the numbers.
3
4use std::fs::File;
5use std::io::{BufReader, Read};
6
7fn main() {
8 match File::open("data.txt") {
9 Ok(file) => {
10 let mut buf_reader = BufReader::new(file);
11 let mut contents = String::new();
12 buf_reader.read_to_string(&mut contents).unwrap();
13 for num in contents.trim().split_whitespace() {
14 print!("{} ", num);
15 }
16 }
17 Err(_) => println!("Error opening file."),
18 }
19}
1// In Go, we open the file using os.Open and handle the error. Then, we use a
2// Scanner to read the file line by line and print each line.
3
4package main
5
6import (
7 "fmt"
8 "os"
9 "bufio"
10)
11
12func main() {
13 file, err := os.Open("data.txt")
14 if err != nil {
15 fmt.Println("Error opening file.")
16 return
17 }
18 scanner := bufio.NewScanner(file)
19 for scanner.Scan() {
20 fmt.Print(scanner.Text(), " ")
21 }
22 file.Close()
23}
Output
Descriptions included in the comments for each sample code
If “data.txt” contains the numbers “1 2 3 4 5”, the output will be:
1 2 3 4 5
Compare & Contrast#
Language |
File I/O Implementation |
Exception Handling |
Ease of Use |
Performance |
---|---|---|---|---|
C++ |
|
Manual |
Moderate |
Efficient |
Python |
|
Automatic |
Easy |
Moderate |
Java |
|
Try-Catch |
Easy |
Moderate |
Rust |
|
Result |
Moderate |
Efficient |
Golang |
|
Error Handling |
Easy |
Efficient |