Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Why not just use the C++ api to read file ?


#include <fstream>
#include <streambuf>
#include <string>
#include <cerrno>

std::string get_file_contents(const char *filename)
{
  std::ifstream in(filename, std::ios::in | std::ios::binary);
  if (in)
  {
    return(std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()));
  }
  throw(errno);
}

Why not just use the C++ api to read file ?


#include <fstream>
#include <streambuf>
#include <string>
#include <cerrno>

std::string get_file_contents(const char *filename)
{
  std::ifstream in(filename, std::ios::in | std::ios::binary);
  if (in)
  {
    return(std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()));
  }
  throw(errno);
}

Check if your file exist, of course it depends also of the content of the file. With a data file like that :

0 1 2 3 4 5 6 7 8

It's works with this piece of code :

#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>

int main()
{
  std::ifstream file("test.txt");
  std::vector<int> data;

  int a[3][3];

  std::memset(a, 0, sizeof(a[0][0]) * 3 * 3);

  if(file.is_open())
  {
    for(int i=0;i<3 && file.good() ;i++)
    {
      for(int j=0;j<3 && file.good() ;j++)
      {
        file >> a[i][j];
      }
    }
  }
  else std::cerr<<"File not found !"<<std::endl;

  for(int i=0;i<3;i++)
    for(int j=0;j<3;j++)
      std::cout<<a[i][j]<<" ";

  return 0;
}