// 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 <iomanip>
#include <iostream>
#include <string>
using namespace std;
double calculateFahrenheit(double celsius);
void createFile(string);
void readFile(string);
void appendFile(string);
void deleteFile(string);
int fileExists(string);
int main() {
string FILENAME = "~file.txt";
if(fileExists(FILENAME)) {
cout << "File already exists." << endl;
} else {
createFile(FILENAME);
readFile(FILENAME);
appendFile(FILENAME);
readFile(FILENAME);
deleteFile(FILENAME);
}
}
double calculateFahrenheit(double celsius) {
double fahrenheit;
fahrenheit = celsius * 9 / 5 + 32;
return fahrenheit;
}
void createFile(string filename) {
fstream file;
float celsius;
float fahrenheit;
file.open(filename, fstream::out);
if (file.is_open()) {
file << "Celsius,Fahrenheit\n";
for(celsius = 0; celsius <= 50; celsius++) {
fahrenheit = calculateFahrenheit(celsius);
file << fixed << setprecision (1) << celsius << "," << fahrenheit << endl;
}
file.close();
} else {
cout << "Error creating " << filename << endl;
}
}
void readFile(string filename)
{
fstream file;
string line;
file.open(filename, fstream::in);
if (file.is_open()) {
while (getline(file, line))
{
cout << line << endl;
}
file.close();
cout << endl;
} else {
cout << "Error reading " << filename << endl;
}
}
void appendFile(string filename)
{
fstream file;
float celsius;
float fahrenheit;
file.open(filename, fstream::out | fstream::app);
if (file.is_open()) {
for(celsius = 51; celsius <= 100; celsius++) {
fahrenheit = calculateFahrenheit(celsius);
file << fixed << setprecision (1) << celsius << "," << fahrenheit << endl;
}
file.close();
} else {
cout << "Error appending to " << filename << endl;
}
}
void deleteFile(string filename)
{
remove(filename.c_str());
}
int fileExists(string filename)
{
FILE *file;
file = fopen (filename.c_str(), "r");
if (file != NULL)
{
fclose (file);
}
return (file != NULL);
}