File stream I/O and Structures in C++

This article contains how to read from a file, write to a file and more details about structures, array of structures and pointer to struct.

File stream is a base class to carry out all the file operations like read ,write, append and much more.

The most commonly used operations are read and write from and to a file.

Read from a file and writing to a file

We can read from a file with various flags. We have ofstream for writing to files and ifstream to read from file. Can also use fstream base class to do both read and write operations.

I open the file as a first step before we read or write. When we open a file we need to specify flags or mode in which we want to open the file.

Mode Description
ios::inopen file for only reading purpose
ios::outopen file for writing purpose
ios::binary open file in binary mode
ios::ateopens the file and sets the initial position to end of file
ios::appappend the contents to the end of the file
ios::truncopen file such that the previous contents are cleared and the new content is added
modes or flags of file open operation

For instance, look at the example below.

void WriteFileStreamsIO()
{
	ofstream myfile; 
	myfile.open("C:\\greetings.txt",
		ofstream::in|ofstream::app); 
	myfile << "Hello, A great day today, Date published : Feb 3rd 2021"<<endl;
	cout << "Writing to the file..." << endl;
	myfile.close();
	return;
}

In this example. I create an object of the type ofstream called myfile. I use this object and open the file at a location whose path is given as a string input along with the flag to append. This means the it opens the file ready to write and appends the contents to the existing ones. After executing this, you should be able to see this files with the contents. If the file does not exist then it creates one and writes content.

Lets see how we can read this file.

void ReadFileStreamIO()
{
	string result; 
	ifstream readFile;
	readFile.open("C:\\greetings.txt",
		ifstream::in);
	if (readFile.is_open())
	{
		while (getline(readFile, result))
		{
			cout << result << endl;
		}
	}
readFile.close();
	return;
}
/**********OUTPUT*******************/
Hello, A great day today, Date published : Feb 3rd 2021

We read the file until we reach the end of it, every time it gets a line and stores it in the result string. As there is only 1 line in this file it will print that and close the file.

Structures in C++

A structure is a data type that holds the members together. A structure can contain items of different datatype. Different datatype members are grouped into a structure.

The syntax of a structure looks like below.

struct structname
{
    datatype1 name1;
    datatype2 name2;
    datatype3 name3; 
}objName1,objName2;

For instance, Lets look at the Employee example below.

struct Employee
{
	string fname, lname, address; 
	int empid; 
	int age; 
};

The employee structure is a group of entries which contains first name, last name and address which are of type string, an employee id and age of type int. We can create an object of employee in the function we want to use.

A simple example

Firstly, I will explain about how I can use the employee structure and fill in the details.

void StructTutorial()
{
	Employee emp1, emp2;
	emp1.fname = "Rick";
	emp1.lname = " Cooper";
	emp1.address = "London";
	cout << " Please enter " << emp1.fname << "'s age" << endl;
	cin >> emp1.age;

	emp2.fname = " Martin ";
	emp2.lname = "King"; 
	emp2.age = 30; 
	emp2.address = "New york";

	cout << " Details of emp1\n";
	cout << emp1.fname << " " << emp1.lname << " " << emp1.age << endl;
	cout << " Details of emp2\n";
	cout << emp2.fname << " " << emp2.lname << " " << emp2.age << endl;
}

We have created an object(emp1, emp2) of the structure employee. After which I filled the members with the data of the Employee. We access the members by using the object and the member name of the structure.

Pointers and structures

In this topic, I will discuss more on pointers to structures. We declare a pointer of the struct type and then assign another memory location type to this pointer. I have more details in the example below.

void pointersandStructures()
{
	Employee record; 
	Employee* emp1; 
	emp1 = &record; // emp1 is a pointer pointing to the value at record 
	
	{
		cout << " Details of Employee 1" << endl;
		cout << "Enter first name, lastname , employee ID" << endl;
		cin >> emp1->fname;// method 1 
		cin >> (*emp1).lname; //method 2
		cin >> emp1->empid;
	}
	
	{
		cout << emp1->fname << emp1->lname << (*emp1).empid << endl;
	}

}

In the example, I have a record of type ‘Employee’ and another pointer called emp1 of the same type as record. After which, I request the user to enter the details of the employee. I access the members of the structure through the pointer by using -> (arrow) operator. I have also provided another alternative where I have used (*emp1).member.

Conclusion

In conclusion, we learned about file streams and structure. One can also use the structure inside a structure or a structure array can be created. All of these are just simple variations of the concept I explained to you above.

This completes by basic blocks towards learning the real C++. Let’s deep dive into Object-Oriented design in the next session.

Go back to the tutorial overview.

Prev: Functions and parameters

Next: Coming soon.