Path: utzoo!utgpu!jarvis.csri.toronto.edu!clyde.concordia.ca!uunet!cs.utexas.edu!sun-barr!decwrl!shelby!helens!relgyro!mike From: mike@relgyro.stanford.edu (Mike Macgirvin) Newsgroups: comp.lang.c Subject: Re: strncpy Keywords: strncpy null termination Message-ID: <397@helens.Stanford.EDU> Date: 22 Dec 89 18:32:33 GMT References: <11509@csli.Stanford.EDU> <8313@stiatl.UUCP> <1947@crdos1.crd.ge.COM> Sender: news@helens.STANFORD.EDU Reply-To: mike@relgyro.STANFORD.EDU (Mike Macgirvin) Organization: Stanford Relativity Gyro Experiment (GP-B) Lines: 55 In article <1947@crdos1.crd.ge.COM> davidsen@crdos1.crd.ge.COM (Wm E Davidsen Jr) writes: >In article <8313@stiatl.UUCP> cns@stiatl.UUCP (Chris Straut) writes: >| In article <11509@csli.Stanford.EDU> poser@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 /* 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@relgyro.stanford.edu (36.64.0.50) + ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++