strncpy

Mike Macgirvin mike at relgyro.stanford.edu
Sat Dec 23 05:32:33 AEST 1989


In article <1947 at crdos1.crd.ge.COM> davidsen at crdos1.crd.ge.COM (Wm E Davidsen Jr) writes:
>In article <8313 at stiatl.UUCP> cns at stiatl.UUCP (Chris Straut) writes:
>| In article <11509 at csli.Stanford.EDU> poser at csli.Stanford.EDU (Bill Poser) writes:
>| >	Why is it that strncpy(3) does not null terminate
>| >the string if the length of the source string is greater than
>| >or equal to the length of the target buffer? 
>  I was asked this question just a few days ago mydelf. After some
>thinking, this appears to be consistent with other behavior, namely
>fgets() which drops the trailing newline if the buffer is too small.
 ^^^^^^^
>  We hacked out a quick version which does always terminate the string
>rather than add logic to all the places in which it was being used.
	Since it was mentioned, has anyone but me ever wondered WHY fgets()
should return the newline at all? 'gets()' doesn't. I finally got tired of
stripping off newlines, and created 'fgetsn()', which I prefer for reading
in text lines from a file....

#include <stdio.h>
  
  /* Function which behaves identically to fgets(),
     except that the trailing newline is not included
     in the string. It always pissed me off that fgets()
     and gets() differ in this behaviour, complicating
     the life of any programmer who may wish to take input
     from either a file or stdin, and treat them the same.
     It also makes a mess of strcmp()'s from a file.
     If you feel the same way, write your congressman or
     ANSI, or add this function to libc.
   */

char * fgetsn(string,count,stream)
     char * string;
     int count;
     register FILE * stream;
{
  int ch;
  register char * pointer = string;
  if(count <= 0)
    return(NULL);
  while (( -- count) && ((ch = getc(stream)) != '\n')) {
    if(ch == EOF) {
      if(pointer == string)
	return(NULL);
      break;
    }
    * pointer ++ = ch;
  }
  * pointer = '\0';
  return(string);
}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+  Mike Macgirvin              Relativity Gyroscope Experiment (GP-B)    +
+  mike at relgyro.stanford.edu   (36.64.0.50)                              +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++



More information about the Comp.lang.c mailing list