Lecture 11: File I/O and Command Line Arguments

Feb 14, 2024  β”‚  Last updated Feb 14, 2024 by Charlotte Curtis

HTML Slides html β”‚ PDF Slides PDF

Where we left off

  • Grouping data with structures
  • Functions + structures
  • Arrays + structures

Textbook Chapter 10

Struct Point {
   double x;
   double y;
}

Point p1 = {1.0, 2.0};
Point p2 = {3.0, 4.0};

Today’s topics

Assignment 1

Assignment 2

After this assignment you can use std::string for the next one

File I/O

Reading from a file

Python

in_file = open("input.txt", "r")
out_file = open("output.txt", "w")

for line in in_file:
    out_file.write(line)

in_file.close()
out_file.close()

C++

ifstream in_file("input.txt");
ofstream out_file("output.txt");
char line[256];

while (in_file.getline(line, 256)) {
    out_file << line << endl;
}
in_file.close();
out_file.close();

Reading from a file

Side Tangent: while (getline)

The fail bit

Consider the following code snippet:

ifstream in_file("input.txt"); // can also declare and then open separately
// do stuff with in_file
in_file.close();

Command line arguments

Command line arguments

emoji File I/O check-in 1/2

What is this code snippet doing? Assume the appropriate #include directives are present - it compiles and runs.

  1. Nothing, it’s just reading from a file
  2. Displaying the contents of a file
  3. Copying the contents of a file
  4. Removing newlines from a file
ifstream in("input.txt");
ofstream out("output.txt");
const int BUFSIZE = 256;
char line[BUFSIZE];
while (in.getline(line, BUFSIZE)) {
    out << line << endl;
}
in.close();
out.close();

emoji File I/O check-in 2/2

What is forgotten in the following code snippet? Assume the appropriate #include directives are present - it compiles and runs.

  1. Nothing, it’s perfect
  2. The file isn’t closed
  3. The file isn’t used for anything
  4. Should use getline instead of >>
  5. The file is opened for writing, not reading
ifstream in("input.txt");
int x;
while (cin >> x) {
    cout << x << endl;
}
in.close();

Command line plus file I/O example

Write a program that takes two command line arguments, an input file and an output file, and copies the contents of the input file to the output file. It should also replace any instance of the word “now” with “meow”.

If the user does not provide two arguments, or if the files can’t be opened, the program should print an error message and exit.

Preview of pointers

Coming up next

Textbook Chapter 10



Previous: Lecture 10: Structures
Next: Lecture 12: Pointers