C++ : How to read a file line by line into a vector ?

In this article we will discuss how to read a file line by line and put them in a vector or perform some other operation each line.

Reading File line by line

First open the file i.e.

// Open the File
std::ifstream in("file.txt");

Now keep reading next line using getline() and push it in vector function until end of file i.e.
std::string str;
// Read the next line from File untill it reaches the end.
while (std::getline(in, str))
{
	// Line contains string of length > 0 then save it in vector
	if(str.size() > 0)
		vecOfStrs.push_back(str);
}

Complete example is as follows:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

/*
 * It will iterate through all the lines in file and
 * put them in given vector
 */
bool getFileContent(std::string fileName, std::vector<std::string> & vecOfStrs)
{

	// Open the File
	std::ifstream in(fileName.c_str());

	// Check if object is valid
	if(!in)
	{
		std::cerr << "Cannot open the File : "<<fileName<<std::endl;
		return false;
	}

	std::string str;
	// Read the next line from File untill it reaches the end.
	while (std::getline(in, str))
	{
		// Line contains string of length > 0 then save it in vector
		if(str.size() > 0)
			vecOfStrs.push_back(str);
	}
	//Close The File
	in.close();
	return true;
}


int main()
{
	std::vector<std::string> vecOfStr;

	// Get the contents of file in a vector
	bool result = getFileContent("example.cpp", vecOfStr);

	if(result)
	{
		// Print the vector contents
		for(std::string & line : vecOfStr)
			std::cout<<line<<std::endl;
	}
}

Reading file line by line and performing operations on each line

Many times we encounter scenarios where we need to read a file line by line and perform some operation on each line like,

  • Search something in each line.
  • Modify the content
  • Store the string to some container etc.

We can a make a generic function that will accept a callback or function pointer along with File name i.e.

/*
 * It will iterate through all the lines in file and
 * call the given callback on each line.
 */
bool iterateFile(std::string fileName, std::function<void (const std::string & )> callback)

It will read the file line by line and will call the given function on each line.

Advertisements

Checkout complete example as follows,

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>

/*
 * It will iterate through all the lines in file and
 * call the given callback on each line.
 */
bool iterateFile(std::string fileName, std::function<void (const std::string & )> callback)
{

	// Open the File
	std::ifstream in(fileName.c_str());

	// Check if object is valid
	if(!in)
	{
		std::cerr << "Cannot open the File : "<<fileName<<std::endl;
		return false;
	}

	std::string str;
	// Read the next line from File untill it reaches the end.
	while (std::getline(in, str))
	{
		// Call the given callback
		callback(str);
	}
	//Close The File
	in.close();
	return true;
}


int main()
{
	std::vector<std::string> vecOfStr;

	//Call given lambda function for each line in file
	bool res = iterateFile("example.cpp", [&](const std::string & str){
												// Add to vector
												vecOfStr.push_back(str);
											});

	if(res)
	{
		for(std::string & line : vecOfStr)
			std::cout<<line<<std::endl;
	}
}

To compile the above examples use following command on linux,

g++ –std=c++11 example.cpp

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top