I have made a method/function to read lines from a text file and stores them in one string until end of the file. Then the function returns the size of the string. This generally works but on some text files it stops before the end of the file. Here is my code.
AP_Text_File::AP_Text_File(){
File_Name="text.txt";
File_Directory="text.txt";
}
int AP_Text_File::return_Number_Char(){
ofstream writefile;//--------------------------------------------used to write to files
ifstream readfile;//---------------------------------------------used to open files
string content;
string filename;
filename=File_Name;//-----------------------------------temporary sets the file name
readfile.open(filename.c_str());//-------------------------------opens the name with name
if(readfile.fail()){//-------------------------------------------If file does not exist....
writefile.open(filename.c_str());//------------------------------The file will be created
//cout<<"Creating "<<filename<<endl;//-----------------------------displays what is being created
};
if(!readfile.fail()){//------------------------------------------If the file already exists then...
while(!readfile.eof()){//------------------------------------While the open file is not at the end of file...
string store;
getline(readfile, store);//---------------------------gets that line from file and stores it in store
content=content+store;
};
};
writefile.close();//---------------------------------------------Closes the file (took me along time lol)
readfile.close();//----------------------------------------------Closes the file
return content.size();
};
@Binary Thoughts
Your code have something wrong:
1. youfunction returns a number of a text. so, when the "text.text" isn't exist you should not creat new. if you want , you can do that somewhere.
2. you don't need a string to store the content. you just need to: read a line, get the size of the line, sum.
3. in you code, if "readfile.open(filename.c_str())" succeful, then "writefile.open(filename.c_str())" will not be executed. so writefile.close()...
4.when you use "getline(readfile, store);", the function drops the '\n'. you should deal with it specially.