C++ binary file question

I have to read a binary file into a structure, so I allocated memory and read this binary file into myptr. How do I ouput the data myptr never gets set to null? What do I loop on. Would it be better to use the container vecotor instead or shoud I loop until eof and use a counter along with C realloc? What's the best way to do this?


typedef struct student
{
char name[10];
int age;
int grades;
}student_t;

char fname[100];
int idx = 0;
student_t* myptr;
ifstream::pos_type size;

int main()
{
cout << "Enter file name";
cin >> fname;

input_file.seekg(0, ios::end);
size = input_file.tellg();
myptr = new student_t [size];
input_file.seekg (0, ios::beg);
input_file.read((char*)myptr, size);
system("PAUSE");
return EXIT_SUCCESS;
}
Last edited on
myptr will never be null. If new fails, it'll throw an exception.

A standard collection would be better than an array allocation. Vectors can do range checking and they can grow/shrink. Forget malloc/realloc, they don't play well with C++ objects.
I'm assuming that by standard collection you mean use the container vector? Correct.
Yes.
Topic archived. No new replies allowed.