Search code examples
c++istreamostreamfilehandle

Read Write Files in C++


I have a dynamically allocated memory:

//dynamic buffer
char *mybuffer;
cin>>n;
mybuffer=new char[n];
//open file for reading
ifstream inpt(filename.c_str(), ios::binary);
for(unsigned int i=0;i<n;i++){

    //copy every single character into buffer
    inpt.read(mybuffer[i],1);
}

says error, argument of type char is incompatible with type char*

I need to read the files character by character and store in buffer. Note that this is sample code. I actually should read multiple files and store in single buffer so I should use buffer with index.

How can I improve this code?


Solution

  • The error

    error, argument of type char is incompatible with type char*

    is due to istream::read takes pointer to char:

    istream& read (char* s, streamsize n);
    

    so you should write:

    inpt.read( &mybuffer[i], 1);