read file into vector

Solutions on MaxInterview for read file into vector by the best coders in the world

showing results for - "read file into vector"
Nicola
18 Jan 2017
1std::vector<char> vec;
2if (FILE *fp = fopen("filename", "r"))
3{
4	char buf[1024];
5	while (size_t len = fread(buf, 1, sizeof(buf), fp))
6    {
7		v.insert(vec.end(), buf, buf + len);
8    }
9	fclose(fp);
10}
Ilyas
28 Aug 2018
1#include <iostream>
2#include <iterator>
3#include <fstream>
4#include <vector>
5#include <algorithm> // for std::copy
6
7int main()
8{
9  std::ifstream is("numbers.txt");
10  std::istream_iterator<double> start(is), end;
11  std::vector<double> numbers(start, end);
12  std::cout << "Read " << numbers.size() << " numbers" << std::endl;
13
14  // print the numbers to stdout
15  std::cout << "numbers read in:\n";
16  std::copy(numbers.begin(), numbers.end(), 
17            std::ostream_iterator<double>(std::cout, " "));
18  std::cout << std::endl;
19
20}
21