Reading Files in C Programming

Sep 16, 2024

Lecture on Reading Files in C

Common Programming Task

  • One of the most common programming tasks in STEM fields is opening a file, reading data, and analyzing it.
  • This lecture focuses on learning how to open a file and read data in C.

Setting Up

  • Use the Command Prompt:
    • Search for CMD and open Command Prompt.
    • Navigate to the desktop and relevant directory using cd commands.
  • Create a batch file for the program: average uncore ofor file.

Creating a Data File

  • You can create a data file using Notepad++ or directly from Command Prompt:
    • Command: echo. > data file.txt creates an empty file named data file.txt.

Preparing the C Program

  • Open the newly created project folder and files using Notepad++.
  • Use a template from a previous average scanf program:
    • Copy (Ctrl+A, Ctrl+C) the entire program and paste (Ctrl+A, Ctrl+V) it as a starting point.

File Handling in C

  • File Pointer:
    • Declare a file pointer: FILE *FP;
    • FILE is a special type of variable, and C is case-sensitive.
    • FP stands for File Pointer.
  • Opening a File:
    • Use fopen command: FP = fopen("data file.txt", "r");
    • First argument is the file name, second is the mode ('r' for read).
    • C does not error check file operations, so manual checks are necessary.
  • Reading from a File:
    • Use fscanf instead of scanf:
      • First argument is FP, followed by format string and variables.
    • Include a printf statement for diagnostics to confirm data is loaded correctly.

Running the Program

  • Save changes (Ctrl+S).
  • Enter 10 random numbers in data file.txt.
  • Compile and run the program to verify data is read correctly and average is calculated.
  • Manually check the average calculation to ensure accuracy.

File Closure

  • Use fclose(FP); to close the file after operations are complete.
  • Closing files is a best practice to prevent potential issues, although C will not break immediately if you forget to close files.
  • Remember to close files after reading/writing as a good housekeeping measure.