Prerequisite:
The C++ Standard Template Library (STL) provides several useful container classes that can be used to store and manipulate data. One of the most commonly used container classes is the vector. In this article, we will discuss how to copy the contents of a file into a vector using C++ STL.
Approach:
The basic approach to copy a file into a vector is to open the file, read its contents, and store them in the vector. The C++ STL provides several functions that can be used to accomplish this task. The most commonly used functions are the ifstream class and the vector’s push_back() function. The ifstream class is used to open a file for reading. Once the file is open, we can use the >> operator to read the contents of the file one character at a time and store them in the vector. The push_back() function is used to add an element to the end of the vector.
Example:
C++
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
ifstream fin("example.txt");
vector<char> v;
char c;
while (fin >> c) {
v.push_back(c);
}
fin.close();
for (int i = 0; i < v.size(); i++) {
cout << v[i];
}
return 0;
}
|
Output:

“example.txt” file

Output
Time complexity: O(n). // n is the number of words in the file example.txt
Auxiliary space: O(n).
In this example, the file “example.txt” is opened for reading using the ifstream class. The contents of the file are read one character at a time and stored in the vector “v” using the push_back() function. Finally, the contents of the vector are printed to the screen.
Note: Make sure that the file exists in the same directory as the code or that you provide the correct path of the file.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!
Last Updated :
16 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...