Reading Text Files in C++
Introduction
Welcome to the first lesson in our course on "Fundamentals of Text Data Manipulation." This lesson will introduce you to the crucial skill of reading text files in C++. Text files are a fundamental data source in programming, commonly used for storing data, configuration files, and logs. Being able to open and read files in C++ is a foundational skill you'll often rely on when working with data. By the end of this lesson, you will be able to read the entire contents of a text file into a string, a skill essential for various data manipulation tasks. Let's get started!
Working with File Paths
A file path is essentially the address of a file in your system's storage. It tells your program where to find or save a file. There are two types of file paths:
-
Absolute Path: This is the full path to a file, starting from the root directory. Here are some examples from different operating systems:
- Linux:
/home/user/documents/input.txt - Mac:
/Users/user/documents/input.txt - Windows:
C:\\Users\\user\\documents\\input.txt(note the double backslashes)
Think of an absolute path like a complete address. If you were sending a letter, you’d include details like the street, city, and postal code, allowing anyone to find the address without additional context.
- Linux:
-
Relative Path: This path is relative to the directory you are working in. For example,
documents/input.txtassumes your executable is running from theuserdirectory in the examples above. A relative path is like saying "the house next door" — it depends on your current location.
Here's how you can specify a file path in C++:
Make sure your C++ program and the text file are in the same directory if you use a relative path. Otherwise, use the absolute path to ensure that C++ can find your file.
Defining Relative Paths with Examples
When working with relative paths, it's important to understand the structure of your directories. Here are a few examples with file trees:
-
Example 1: (Assuming the code is located in the
programfile)File Tree:
textRelative Path:
C++ -
Example 2: (Assuming the code is located in the
programfile)File Tree:
textRelative Path:
C++The
..is used to navigate to the parent directory. It works this way in both macOS/Linux and Windows. -
Example 3:
File Tree:
textRelative Path (assuming the program is in
program2):C++ -
Example 4: (When both the program and
input.txtare in the same location)File Tree:
textRelative Path:
C++
These examples illustrate how relative paths depend on the current working directory of your program.
