Clicky

Any one knows how to convert a given text file (unknown size) into a byte array in C++. Please do not answer this in C or C# or Java. I want this in C++.

Thanks
prain

asked 12/15/2011 10:09

prain's gravatar image

prain ♦♦


6 Answers:
you would retrieve the size of the text file using stat function:

1:
2:
3:
4:
5:
6:
#include "sys/stat.h"
...
std::string filename = "full_path_of_file";
struct stat status;
if (stat(filename.c_str(), &status) != 0)
    // error


then open the file with

1:
std::ifstream file(filename.c_str());


allocate byte array by

1:
std::vector<unsigned char> bytearray(status.st_size);


read the file with

1:
2:
if (!file.read((char*)&bytearray[0],  bytearray.size())
       // error


close the file. the bytearray could be accessed via the vector or as unsigned char * by &bytearray[0]-

Sara
link

answered

sarabande's gravatar image

sarabande

You can do that like
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
#include <sys/stat.h>

#include <fstream>
using namespace std;

typedef unsigned char BYTE;

//..

const char* pFile = "test.txt";

struct stat buf;

stat(pFile,&buf);

BYTE* pAdd = new BYTE[buf.st_size];

ifstream is(pFile);

is.read((char*)pArr,buf.st_size);

// access each byte via pArr[i];

delete [] pArr; // clean up


If you are on Windows, use '_stat(pFile,&buf);' instead.
link

answered 2011-12-16 at 08:41:12

jkr's gravatar image

jkr

Hello jkr,
you meant pAdd and not pArr right? I do not see pAdd is being used anywhere after it is defined.

prain
link

answered 2011-12-16 at 08:44:28

prain's gravatar image

prain

Actually, it should be
1:
BYTE* pArr = new BYTE[buf.st_size];

Sorry about that.
link

answered 2011-12-16 at 09:54:54

jkr's gravatar image

jkr

More points.
link

answered 2011-12-16 at 10:15:32

prain's gravatar image

prain

Ok, with all due respect to sarabande's answer, I accept jrk's because it fits our coding style well.

I have increased the points to 200 and given the increased amount to sarabande, while jrk get full points I promised first.

Thanks guys again.
-prain
link

answered 2011-12-16 at 11:27:21

prain's gravatar image

prain

Your answer
[hide preview]

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Tags:

Asked: 12/15/2011 10:09

Seen: 264 times

Last updated: 12/16/2011 03:29