Table of Contents
This article discusses different methods to Write Vector to File in C++.
Vectors in C++ are sequential containers similar to arrays. However, vectors need to have a fixed size.
On the other hand, files facilitate the storage of data permanently to the disk, therefore, mitigating the data loss even after the program stops execution.
Write Vector to File in C++ using vector indices
You can traverse all the elements of a vector one by one using the indices. Writing to the file is similar to writing to the console output except that you need to open a file output stream.
You can open the file using the fstream
library’s open()
function. The definition of the open()
function is given below.
1 2 3 4 |
void open (const char* filename, ios_base::openmode mode = ios_base::in | ios_base::out); |
The function accepts the pathname of the file and the mode of opening it. You can read more about modes of opening a file in C++ here.
To write the vector to the file,
- Open the file.
- Traverse each element of the vector using indices in a loop,
- Write each element to the file (using
<<
operator).
- Write each element to the file (using
- Close the file by calling the
close()
function.
You can get the number of elements in the vector by calling the size() function of the vector class.
Let us see the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <iostream> #include <fstream> #include <vector> #include <string> using namespace std; int main() { vector<string> v; v.push_back("Hello!"); v.push_back("We are Java2Blog."); v.push_back("You can a lot from our articles."); fstream file; file.open("vector_file.txt",ios_base::out); for(int i=0;i<v.size();i++) { file<<v[i]<<endl; } file.close(); return 0; } |
Note that the program writes a special newline character to the file after each vector element for formatting purposes.
Output (from the file):
We are Java2Blog.
You can a lot from our articles.
Write Vector to File in C++ Using Iterator
An iterator points to a specific memory location of the vector. Iterators are similar to pointers and you can use them to access the elements of a vector.
You can define an iterator to your vector as given below.
1 2 3 |
vector<datatype>::iterator itr_name; |
You can also use the auto keyword that automatically defined iterator for your vector. The code example in this section uses the auto keyword.
After opening a file, you can write a vector to it by following the steps given below.
- Get the starting iterator by calling
begin()
function. - Get the final iterator by calling the
end()
function. - Traverse from starting to the ending iterator using a loop,
- Write each element to file by dereferencing the iterator (using
*
operator).
- Write each element to file by dereferencing the iterator (using
- Close the file.
Let us see the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <iostream> #include <fstream> #include <vector> #include <string> using namespace std; int main() { vector<string> v; v.push_back("Hello!"); v.push_back("We are Java2Blog."); v.push_back("You can a lot from our articles."); v.push_back("This method uses iterator."); fstream file; file.open("vector_file_2.txt",ios_base::out); vector<string>::iterator itr; for(itr=v.begin();itr!=v.end();itr++) { file<<*itr<<endl; } file.close(); return 0; } |
Output (from the file):
We are Java2Blog.
You can a lot from our articles.
This method uses iterator.
Further reading:
Write Vector to File in C++ Using Range-Based for Loop
Range-based for loop is great when you have to traverse the contents of a container like vectors. You do not need to define the beginning and ending indices or iterators. The range-based for loop does it itself.
The result of each iteration i.e. each element is stored in the loop variable. You can write the loop variable directly to the file.
Let us see the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include <iostream> #include <fstream> #include <vector> #include <string> using namespace std; int main() { vector<string> v; v.push_back("Hello!"); v.push_back("We are Java2Blog."); v.push_back("You can a lot from our articles."); v.push_back("This method uses range-based for loop."); fstream file; file.open("vector_file_3.txt",ios_base::out); for(auto content: v) { file<<content<<endl; } file.close(); return 0; } |
Output (from the file):
We are Java2Blog.
You can a lot from our articles.
This method uses range-based for loop.
Write Vector to File in C++ Using the for_each() Function
The for_each()
function applies a custom user function to all the elements of a container like a vector.
You can define a custom function that writes a number to a file stream and pass it to for_each()
. In this way, you can write all elements to a file.
The definition of the for_each()
function is given below.
1 2 3 4 |
template <class InputIterator, class Function> Function for_each (InputIterator first, InputIterator last, Function fn); |
Let us see the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#include <iostream> #include <fstream> #include <vector> #include <string> #include <algorithm> using namespace std; fstream file; void fun(string str) { file<<str<<endl; } int main() { vector<string> v; v.push_back("Hello!"); v.push_back("We are Java2Blog."); v.push_back("You can a lot from our articles."); v.push_back("This method uses for_each()."); file.open("vector_file_4.txt",ios_base::out); for_each(v.begin(), v.end(), fun); file.close(); return 0; } |
Note that you shall define a global file stream to be used by the function that writes to the file.
Output (from the file):
We are Java2Blog.
You can a lot from our articles.
This method uses for_each().
Write Vector to File in C++ Without Using a Loop
You can Write Vector to File without using a loop by calling the copy()
function. The copy()
writes all values of the vector to an output stream passed to it as an argument.
You can pass the file output stream as the output stream to which function writes the elements.
The definition of the copy()
function is given below.
1 2 3 4 |
template <class InputIterator, class OutputIterator> OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result); |
The function accepts a starting and an ending iterator to denote the range of values that it must write to the output stream. The third parameter is the output stream itself.
Note that you must create an output stream iterator to pass it to copy()
. You can create an output stream iterator using the ostream_iterator
class.
Let us see the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include <iostream> #include <fstream> #include <vector> #include <string> #include <algorithm> #include <iterator> using namespace std; int main() { vector<string> v; v.push_back("Hello!"); v.push_back("We are Java2Blog."); v.push_back("You can a lot from our articles."); v.push_back("This method uses no loop."); fstream file; file.open("vector_file_5.txt",ios_base::out); ostream_iterator<string> out_itr(file, "\n"); copy(v.begin(), v.end(), out_itr); file.close(); return 0; } |
Output (from the file):
We are Java2Blog.
You can a lot from our articles.
This method uses no loop.
Conclusion
The article discussed several different methods to Write Vector to File each with potential usage in different situations.
You can also use the write()
function of the fstream
class to write to the file. You can check out more about this method of writing files in our article here.
This is all about How to write Vector to file in C++.
Hope you enjoyed reading the article. Stay tuned for more articles. Happy Learning!