Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

read and write file in c++

#include<iostream>
#include<fstream>

using namespace std;

int main()
{

    string fileName;
    int choice;
    cout << "Enter txt file name:
";
    cin >> fileName;
    cout << "Enter number of command:
";
    cout << "1. Write file
";
    cout << "2. Read file
";
    cin >> choice;

    if (choice == 1)
    {
            ofstream myfile;
            string text;
            myfile.open (fileName);
            cout << "Write text below: 
"; //file must have no text
            cin >> text;
            myfile << text;
            myfile.close();
    }else if (choice == 2)
    {
            ifstream file(fileName);
            string line;

            if (file.is_open())
            {
	            while (getline(file, line))
                {
        	       cout << line << endl;
                }
    }
    }
    return 0;
}
Source by cplusplus.com #
 
PREVIOUS NEXT
Tagged: #read #write #file
ADD COMMENT
Topic
Name
4+1 =