Get Website Learn Coding Tech Story

C++ Programming Examples

#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;

int main() {
	char data[80], ch;
	cout << "Enter a string for file:" << endl;
	cin >> data;

	/* Input output stream */
	/* Not create a file */
	fstream file;

	/* Open file in read and write mode */
	file.open("data.txt", ios::in | ios::out);

	for( int i = 0; i < strlen(data); i++)

		/* Write character using put() */
		file.put(data[i]);	

	cout << "Reading from begining of the file" << endl;

	/* Move file pointer at the start */
	file.seekg(ios::beg);
	while(file) {

		/* Read character using get() */
		file.get(ch);
		cout << ch;
	}
	cout << endl;
	
	file.close();
	return 0;
}


          /****** Output ******/
          

Enter a text for file:


HelloWorld


Reading from begining of the file


HelloWorld

Learn more about Input/Output in C++