How to Read Data from Files in C++ with Xcode on Mac

by Yukong Zhang, 09-19-2024

Often times your programs need to read and/or write data from and into files. If you use Xcode for running C++ program on Mac, it could be a little bit tricky. This tutorial shows how to read data from files in C++ programs with Xcode on Mac. Writing data into files follows the same concept. In general, there are two locations you can use for input data files. The first location is the default location where the "product" generated by Xcode is located, and the second location is the working folder where your C++ code resides. This working location can be controled by programmers. The following instructions show how to specify these two locations for your input data files.

Input Data Files in the Default Location

When you run your C++ program with Xcode, a "software" product will be created and put in a location (folder) set up by Xcode by default. If clicking on Product on the menu bar and then select Scheme -> Edit Scheme, you will see the Working Directory checkbox is not selected. In this case, you need to add your input data file in the default product folder, so your program can read data from there.

You can view this default folder for the product by clicking on Product on the menu bar and then select Show Build Folder in Finder.

A finder window pops up and displays an executable file (product). This is the folder where you can add your input files. Simply drag your input files into this folder for the program to read. This folder is located in a deep subfolder as shown in the red box at the bottom of the finder window.

Input Data Files in Working Directory

Alternatively, you can place your input data files into the working directory (folder) where your C++ programs are located. To do so, you need to select the checkbox in the Edit Scheme window as shown in the preceding screenshots. Click on the folder icon (folder path) at the lower right corner in the red box to open the working folder.

Just drag your input data file to this working folder and click on the Choose button.

In the Choose Options window to select the way to add input files. Then click the Finish button.

For easy access to the input data file, you can drag it to the left workspace where your C++ file is located. Note that the input data files in the left workspace don't necessarily located in the same folder as the C++ program. Click the Run button to run your program. Output from your program will be displayed on the Output windonw.

Since the underlying operating system of Mac is a UNIX, you can use a Terminal window to view your source code and data files.