File Handling

Why Use Files?

  • Files provide a way to ​store data ​permanently, allowing programs to access and manipulate it later
  • Files allow for ​organised storage​ of data, making it easier to find, access, and update
  • They enable ​sharing​ of data between different programs and users
  • They support ​data backup, ensuring data is not lost when a program or computer system shuts down
  • They allow for ​large amounts of data​ to be stored and managed efficiently
  • Data can be transported from one system to another

Opening & Closing Files

  • Common file operations include:
    • Opening: creates a connection between the file and the program
    • Reading: retrieves data from a file
    • Writing​: saves new data to a file, overwriting existing content
    • Appending: adds new data to the end of a file without overwriting existing content
    • Closing: ends the connection between the file and the program, releasing system resources
  • Single items of data can be numbers, characters, or other simple data types
  • A line of text typically ends with a newline character or an end-of-line marker

Pseudocode example:

OPEN "file.txt" 
filedata =  READ data
PRINT filedata
CLOSE file

OPEN "file.txt"
WRITE data
CLOSE file

Python example:

with open("file.txt", "r") as file:
    data = file.read()
    print(data)

with open("file.txt", "w") as file:
    file.write(data)

Java example:

    public static void main(String[] args) {
        String path = ("file.txt");

        try {

      FileReader f = new FileReader(path);

     BufferedReader reader = new BufferedReader(f);
            String data = reader.readLine();

      reader.close();

      BufferedWriter out = new BufferedWriter(f);

      out.write(data);

      out.close();

   } catch (Exception e) {

      System.err.println("No file found");

   }

}

Visual Basic example:

Dim File As New System.IO.StreamReader("file.txt")

Console.WriteLine(File.ReadLine())

File.Close()

Dim fileWrite As New System.IO.StreamWriter("file.txt")

fileWrite.WriteLine(data)

fileWrite.Close()

Loading

error: Content is protected !!