Menu
Coddy logo textTech

Appending Data to Files

Lesson 13 of 23 in Coddy's C++ File Handling course.

The .put(char) method writes a single character to the file, useful for adding individual characters like newlines or formatting symbols. 

On the other hand, .write(string, size n) writes n characters from a string to the file, ideal for handling larger chunks of data.

ofstream output;
output.open("example.txt");

output.put('H');
output.put('I');
output.put('!');
output.put('\n');

char* message = "Hello!";
output.write(message, strlen(message));
challenge icon

Challenge

Easy

Write a program that opens the file named output.txt reads from standard input 3 characters, and then a string, append the characters but each one separated with a whitespace

*Do not change the default code*

Try it yourself

#include <iostream>
#include <fstream>

using namespace std;

int main() 
{
    
    // Enter your code here
    
    
    
    // DO NOT CHANGE THE CODE BELOW!
    ifstream file("output.txt");
    string line;
    while(!file.eof()){
        getline(file, line);
        cout << line;
    }
    file.close();
}

All lessons in C++ File Handling