Hi,
Using fgets you can read one line correctly but you need to know the max line size possible.
How read one line without limit correctly ? Read each character until '\n' is the only way ?
Thanks
Hi,
Using fgets you can read one line correctly but you need to know the max line size possible.
How read one line without limit correctly ? Read each character until '\n' is the only way ?
Thanks
std::ifstream ifs(filename);
std::string line;
while (std::getline(ifs, line)) {
// do something with `line'
}
I missed to mention it's to read from a FILE pointer and output into a custom string class variable, here the actual code :
bool CFile::ReadLine( CString& Data, const UInt32 MaxLineLength )
{
// Allocate the buffer used to read the line.
char* Buffer = new char[ MaxLineLength ];
// Read the line into the buffer.
if( fgets( Buffer, MaxLineLength, m_File ) != nullptr )
{
Data = Buffer;
delete[] Buffer;
return true;
}
else
{
delete[] Buffer;
return false;
}
}
Stealing Alvaro's code:
std::ifstream ifs(filename);
std::string line;
while (std::getline(ifs, line))
{
if("" == line)
continue;
// do something with `line'
}
In case you can acquire the length of red string from the function call, you could reliably settle for reading lines of any length, since you could test against the maximum length you provide. But quick glance at the fgets function tells it does not return amount of red characters, and counting them after they are returned is sure an overkill.
http://man7.org/linux/man-pages/man3/getline.3.html
This is a nonstandard function, but you didn't say what platform you're on, so...
Note the second paragraph in the description.
I think Data=Buffer it is wrong, if you delete Buffer, Data points to a released data. To copy the contents, use memcpy.