Read one text line without limit correctly

Started by
10 comments, last by Bregma 8 years, 2 months ago

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

Advertisement
Your tags mention C++, so the generally favorable answer is to use std::getline() and read into a std::string.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

I write this kind of code a lot:

  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.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.
I think Data=Buffer it is wrong, if you delete Buffer, Data points to a released data. To copy the contents, use memcpy.

I think Data=Buffer it is wrong, if you delete Buffer, Data points to a released data. To copy the contents, use memcpy.


data is of a type CString. While I'm not familiar with the type it is reasonable to assume it will do its own copy.

Ah ok, I didn't know that it was part of <afx.h>, just checked .

This topic is closed to new replies.

Advertisement