Programming Fundamentals/Files/C++

files.cpp

edit
// This program creates a file, adds data to the file, displays the file,
// appends more data to the file, displays the file, and then deletes the file.
// It will not run if the file already exists.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/C%2B%2B_Programming

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

void create_file(string filename);
void read_file(string filename);
void append_file(string filename);
void delete_file(string filename);
int file_exists(string filename);

int main()
{
    string FILENAME = "~file.txt";

    if(file_exists(FILENAME))
    {
        cout << "File already exists." << endl;
    }
    else
    {
        create_file(FILENAME);
        read_file(FILENAME);
        append_file(FILENAME);
        read_file(FILENAME);
        delete_file(FILENAME);
    }
}

void create_file(string filename)
{
    fstream file;
    float c;
    float f;
    
    file.open(filename, fstream::out);
    file << "C\tF\n";
    for(c = 0; c <= 50; c++)
    {
        f = c * 9 / 5 + 32;
        file << c << "\t" << f << endl;
    }
    file.close();
}

void read_file(string filename)
{
    fstream file;
    string line;

    file.open(filename, fstream::in);
    while (getline(file, line))
    {
        cout << line << endl;
    }
    file.close();
    cout << endl;
}

void append_file(string filename)
{
    fstream file;
    float c;
    float f;
    
    file.open(filename, fstream::out | fstream::app);
    for(c = 51; c <= 100; c++)
    {
        f = c * 9 / 5 + 32;
        file << c << "\t" << f << endl;
    }
    file.close();
}

void delete_file(string filename)
{
    remove(filename.c_str());
}

int file_exists(string filename)
{
    FILE *file;
    
    file = fopen (filename.c_str(), "r");
    if (file != NULL)
    {
        fclose (file);
    }
    return (file != NULL);
}

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own C++ compiler / interpreter / IDE.

See Also

edit