I have two classes:
buffer, which allocates char buffer
file, which manages file io
My file.read() functions wants to return a buffer object, but i cannot assign it to a variable (see main() at the end of the code is where the error is))
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
class buffer {
public:
buffer(int _size) : buf((char *)malloc(_size)), len(_size)
{
}
char *ptr()
{
return buf;
}
int size()
{
return len;
}
~buffer()
{
free(buf);
}
buffer() : buf(0), len(0)
{
}
buffer(buffer& rhs)
{
buf = (char *)malloc(rhs.len);
memcpy(buf, rhs.buf, rhs.len);
}
operator=(buffer& rhs)
{
free(buf);
buf = (char *)malloc(rhs.len);
memcpy(buf, rhs.buf, rhs.len);
}
private:
char *buf;
int len;
};
class file {
public:
file(const char *filename, const char *mode) : f(fopen(filename, mode))
{
}
int size()
{
int ret;
int pos = ftell(f);
fseek(f, 0, SEEK_END);
ret = ftell(f);
fseek(f, 0, pos);
return ret;
}
buffer read(int n)
{
buffer buf(n);
fread(buf.ptr(), 1, n, f);
return buf;
}
void write(buffer& buf)
{
fwrite(buf.ptr(), 1, buf.size(), f);
}
~file()
{
fclose(f);
}
private:
FILE *f;
};
int main(int argc, char *argv[])
{
if (argc == 3) {
file infile(argv[1], "rb");
file outile(argv[2], "wb");
buffer buf = infile.read(infile.size());
}
}
Please ignore that the code is not generic (no templates and poor error handling) this is just a demo I am learning c++.
Update
Still not working:
buffer& operator=(const buffer& rhs)
{
free(buf);
buf = (char *)malloc(rhs.len);
memcpy(buf, rhs.buf, rhs.len);
}
file infile(argv[1], "rb");
file outile(argv[2], "wb");
buffer buf = infile.read(infile.size()); // error