C++ I/O

From Wiki
Jump to navigation Jump to search

Terminal I/O

#include <iostream>  // defines cout, cin, endl
using namespace std;
...
cout << "Enter your name: ";
cin >> name;
cout << "Hi there, " << name << "!" << endl;

File I/O

#include <iostream>
#include <fstream>
using namespace std;

// reading a file:
void readFile(char* fileName){
    fstream infile(fileName);
    if (!infile.is_open()){
       cerr << "failed to open file " << fileName << endl;
       exit(1);
    }
    const int maxLineSize = 256;
    char line[maxLineSize];
    int i = 0;
    while ( !infile.eof( ) ) {
        infile.getline(line, maxLineSize);
        cout << "line" << (i++) << ": " << line << endl;
    }
}
   
// write to a file:
void writeStringToFile(char* fileName, string msg){
    ofstream outfile(fileName);
    if (!outfile.is_open()){
        cerr << "failed to open file " << fileName << endl;
        exit(1);
    }
    outfile << msg;
    cout << "string successfully written to file" << endl;
}
   
int main(){
    readFile("test.txt");
    writeStringToFile("test.txt", "here is more text");
}
   
//To append, use
//   ofstream outfile(fileName, ios::app);