Team 2550
Technical Documentation
 All Files Variables Pages
File I/O

Table of Contents

Everything that can be done with iostream can also be used with files through the fstream header. However, there are a few things that you need to handle manually. Here are the necessary steps...

  1. Create a file stream variable
  2. Open a file
  3. Read/write to/from the file
  4. Close the file
Note
cin and cout are actually treated as files (especially on UNIX systems). The only difference is that they are automatically opened and closed.

Output

#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main() {
ofstream file;
file.open("file.txt");
//Generate the 1st 10 powers of 2 and write them to the file
for (int i = 1; i <= 10; i++)
file << pow(2, i) << "\n";
file.close();
}
Note
\n is faster than endl due to the fact that it has less overhead.

The output file will look like this...

2
4
8
16
32
64
128
256
512
1024
Note
file.txt will be created in the working directory. The working directory is where the command line (console) is looking when the file is executed. Typically, it will be either your home folder or the location that the file was executed.
Warning
Every time you run the above code, the file will be overwritten if it already exists.

Input

#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main() {
int input[10];
ifstream file;
file.open("file.txt");
//Generate powers of 2 and write them to the file
for (int i = 0; i < 10; i++)
file >> input[i];
file.close();
for (int i = 0; i < 10; i++)
cout << input[i] << "\n";
}
Warning
This page was created in order demonstrate the basics of file I/O. In robotics, file I/O is not extremely useful, so I have not covered it in much detail. Google C++ file I/O for more information about the various modes you can use.