C getline() question

Discussion in 'OT Technology' started by nillyp, Feb 1, 2004.

  1. nillyp

    nillyp Guest

    I have a C getline() function that I am trying to make work. I can't figure out why my code does not detect the newline '\n' character when it is encountered, instead, it reads to EOF. If anyone can help out...I'd appreciate it.

    int getline(
    int in,
    char *buf)
    {
    int len;
    char *loc;

    len = 0;
    loc = buf;
    while (read(in, loc, 1) > 0)
    {

    len += 1;
    loc += 1;
    if (*loc == '\n')
    break;

    }
    return(len);
    }
     
  2. DFWSR4EVER

    DFWSR4EVER There's Stlil Time to Change the Road You're On

    Joined:
    Jul 29, 2001
    Messages:
    51,573
    Likes Received:
    0
    Location:
    Wisco
    moved to C&P
     
  3. D1G1T4L

    D1G1T4L Active Member

    Joined:
    May 4, 2001
    Messages:
    16,489
    Likes Received:
    0
    Location:
    Bay Area
    use
    Code:
     tags when posting code
     
  4. uneek

    uneek OT Supporter

    Joined:
    Dec 14, 2003
    Messages:
    12,002
    Likes Received:
    0
    Because you increment loc before checking for '\n'

    Code:
    int getline(int in, char *buf)
      {
      int len;
      char *loc;
     
      len = 0;
      loc = buf
     
      while (read(in, loc, 1) > 0)
    	{
    	len += 1;
    	loc += 1;
    	if (*(loc - 1) == '\n')
    	  break;
    	}
      }
     
  5. nillyp

    nillyp Guest

    I appreciate it! I hate when I overlook minor details like that.
     

Share This Page