1

I want to read a file such that I can access it character by character using any type of storage such as char array or vector (I heard vectors are safer and faster). My file size will be around 1 MB to 5 MB. I've tried vectors but it reads a word that ends with \n at a time (I mean it reads file at a time outputting single line at once) not by single character. My file will vary in size in the context of row x column wise, hence I presume 2-D arrays cannot be used.

#include <iostream>
#include <fstream>
#include <stdlib.h> 

using namespace std;

const int MAX_SIZE = 1000;

int main()
{
        ifstream hexa;
        hexa.open("test.txt");
        char* hexarray = new char[MAX_SIZE];        
            while (!hexa.eof())
            {   
                for (int i = 0; i <= MAX_SIZE; i++)
                {
                        hexa >> hexarray[i];
                        cout << hexarray[i]<<endl;
                }
            }
        delete[] hexarray;   
        hexa.close();
        return 0;
}

Using vector:

vector<string> data;
ifstream ifs;
string s;
ifs.open("test.txt");
while(ifs>>s)
{
data.push_back(s);
}

Can anyone let me know how I can access a single character of my file?

File content:
-6353
-cf
-CF
0
1
-10
11
111111
-111111
CABDF6
-cabdf6
defc

So I need to get array_name[0] = -, array_name[1] = 6, .... array_name[n] = c

Deanie
  • 2,205
  • 2
  • 17
  • 32
user2754070
  • 509
  • 1
  • 7
  • 16

1 Answers1

2

Simplest way :

#include <iostream>
#include<fstream>
#include<vector>
#include<algorithm>
#include<iterator>
//...

std::vector<char> v;

std::ifstream hexa("test.txt");

std::copy( std::istream_iterator<char> (hexa),
           std::istream_iterator<char>(),
           std::back_inserter(v) );
//...
for(std::size_t i=0 ;i < v.size() ;++i)
      std::cout << v[i] << " ";
P0W
  • 44,365
  • 8
  • 69
  • 114