Hi first post here
I am playing around with text file IO to understand it better. Now I have a function that calls the read method of an ifstream object. It works when I pass an array to the function calling the read() method, but not when I pass a char*. Though the read() method takes a char* as input. I thought my array would decay to a char* when I passed it from main, so why do they work differently with read()?
Here's a MWE, the program crashes due to one function call I commented.
Code:
#include <iostream>
#include <fstream>
#include <algorithm>
template <class T>
inline void checkfile(const T& ff){//basic opening check
if ( (!ff.is_open()) || (!ff.good()) ){std::cerr<<"cant open file!!!\n";}
}
template <class T>
inline void checkfile2(const T& ff){ //write & read check
if (ff.fail()){std::cerr<<"Failed to read/write with file!!!\n";}
}
inline void readstuff(std::ifstream& ii, char* mytxt,const int S) //char array decays to char*
{
ii.seekg(0,std::ios::end);
int N = std::min(int(ii.tellg()),S-1);
ii.seekg(0,std::ios::beg);
ii.clear(); //not sure if I need this
ii.read(mytxt,N);
//if (mytxt[S-1]!='\0'){mytxt[S-1]='\0';std::cout<<"\nInput char[] did not terminate with \\0, fixed it\n";}
}
inline void writestuff(std::ofstream& oo){
oo.seekp(0,std::ios::beg); //reset setter
oo << "bla bla bla";
oo << " more bla\n";
oo << "yuup, bla with an extra \0 in it"; // operator<< terminates at \0 (what happens to last 6 chars?)
oo << "this line moves the EOF again";
}
int main()
{
char mytxt[] = {'h','e','l','l','o','\0'}; //NB(!) cant take words > 5. Can not cast to char*.
char* mytxt2 = "ABCDE"; //same size as mytxt (is it?)
int sizetxt = int(sizeof(mytxt)/sizeof(mytxt[0]));
std::ofstream oo("mydata.txt");
checkfile(oo);
writestuff(oo);
checkfile2(oo);
oo.close();
std::ifstream ii("mydata.txt");
checkfile(ii);
readstuff(ii,mytxt2,sizetxt); //this statement makes it crash
readstuff(ii,mytxt,sizetxt);
checkfile2(ii);
ii.close();
std::cout << mytxt << std::endl; //bla b
std::cout << mytxt2 << std::endl; //bla b
return 0;
}
P.S. since I'm a newbie any style comments are also welcome