c++ - Reading a file using fstream -
when try read file buffer, appends random characters end of buffer.
char* thefile; std::streampos size; std::fstream file(_file, std::ios::in | std::ios::ate); if (file.is_open()) { size = file.tellg(); std::cout << "size: " << size; thefile = new char[size]{0}; file.seekg(0, std::ios::beg); file.read(thefile, size); std::cout << thefile; } int x = 0;
while original text in file is: "hello" output becomes: "helloýýýý««««««««þîþîþ"
could me happening here? thanks
if file not opened ios::binary
mode, cannot assume position returned tellg()
give number of chars read. text mode operation may perform transformations on flow (f.ex: on windows, convert "\r\n" in file in "\n", might find out size of 2 read 1)
anyway, read()
doesn't add null terminator.
finally, must allocate 1 more character size expect due null terminator have add. otherwise risk buffer overflow when add it.
you should verify how many chars read gcount()
, , set null terminator string accordingly.
thefile = new char[size + 1]{0}; // 1 more trailing null file.seekg(0, std::ios::beg); if (file.read(thefile, size)) thefile[size]=0; // successfull read: size chars read else thefile[file.gcount()]=0; // or less chars read due text mode
Comments
Post a Comment