// 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.

#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);
}

कोशिश करो

सम्पादन

निम्न कोड मुफ्त ऑनलाइन विकास के वातावरण में से एक में ऊपर कॉपी और पेस्ट करो या अपने खुद के कम्पाइलर/इंटरप्रेटर/आईडीई का उपयोग करें।

यह भी देखें

सम्पादन