strncpy() — 스트링 복사

형식

#include <string.h>
char *strncpy(char *string1, const char *string2, size_t count);

언어 레벨

ANSI

스레드세이프

설명

strncpy() 함수는 string2count자를 string1에 복사합니다. countstring2 길이 이하이면 널(null) 문자(\0)는 복사된 스트링에 추가되지 않습니다. countstring2의 길이보다 큰 경우 string1 결과는 길이 count까지 널(null) 문자(\0)로 채워집니다.

리턴값

strncpy() 함수는 string1에 대한 포인터를 리턴합니다.

이 예는 strcpy()strncpy() 사이의 차이를 보여줍니다.
#include <stdio.h>
#include <string.h>
 
#define SIZE 40
 
int main(void)
{
  char source[ SIZE ] = "123456789";
  char source1[ SIZE ] = "123456789";
  char destination[ SIZE ] = "abcdefg";
  char destination1[ SIZE ] = "abcdefg";
  char * return_string;
  int    index = 5;
 
  /* This is how strcpy works */
  printf( "destination is originally = '%s'\n", destination );
  return_string = strcpy( destination, source );
  printf( "After strcpy, destination becomes '%s'\n\n", destination );
 
 
  /* This is how strncpy works */
  printf( "destination1 is originally = '%s'\n", destination1 );
  return_string = strncpy( destination1, source1, index );
  printf( "After strncpy, destination1 becomes '%s'\n", destination1 );
}
 
/*****************  Output should be similar to:  *****************
 
destination is originally = 'abcdefg'
After strcpy, destination becomes '123456789'
 
destination1 is originally = 'abcdefg'
After strncpy, destination1 becomes '12345fg'
*/