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,316
  • 2
  • 19
  • 35
user2754070
  • 509
  • 1
  • 7
  • 16
  • Don't use `>>` for reading raw file data. Use `ifs.read`, and read more than one character at a time. You can read the entire file in one go if you know the size beforehand, or in chunks of any size you want. – n. m. could be an AI Dec 24 '13 at 03:58
  • Write and read in binary using `fwrite` and `fread` respectively. – Fiddling Bits Dec 24 '13 at 04:01
  • 1
    Do you really want `array_name[0]` to be the integer -6? Or, do you want it to be `'-'` and `array_name[1] == '6'`? – chwarr Dec 24 '13 at 05:21

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
  • 46,614
  • 9
  • 72
  • 119