w3resource

C - strncpy() function

C strncpy() function - copy fixed length string, returning a pointer to the array end

The strncpy() function is used to copy n characters of string2 to string1. If n is less than or equal to the length of string2, a null character (\0) is not appended to the copied string. If n is greater than the length of string2, the string1 result is padded with null characters (\0) up to length n.

Why and when to use strncpy()

  • Copying Part of a String: strncpy() is useful for copying a specific number of characters from one string to another, allowing partial copying.
  • Size-Limited Copying: Helps avoid buffer overflow by limiting the number of copied characters, making it safer when dealing with strings of unknown sizes.
  • String Initialization: Commonly used for initializing strings with a fixed number of characters without exceeding array bounds.
  • Padding with Null Characters: If the specified number of characters exceeds the source string length, strncpy() pads the destination with null characters.

Syntax:

char *strncpy(char *string1, const char *string2, size_t n);

Parameters:

Name Description Required /Optional
string1 Destination string. Required
string2 Source string. Required
n The number of characters to be copied from source. Required

Return value from strncpy()

  • The strncpy() function returns a pointer to string1.

Examples: strncpy() function

Example 1: Copy a specific number of characters from one string to another

This example shows how strncpy() can be used to copy a specific number of characters from one string to another. First, only 2 characters from string2 are copied into string1, partially replacing it. In the second example, 5 characters from string4 are copied into string3, demonstrating partial copying and string padding when the character count exceeds the destination’s current length.

Code:

#include <stdio.h>
#include <string.h>
 
#define SIZE 40
 
int main(void)
{
  char string1[ SIZE ] = "123456789";
  char string2[ SIZE ] = "abcdefg";
  char string3[ SIZE ] = "123456789";  
  char string4[ SIZE ] = "abcdefg";
  char * return_string;
  int  n = 2; 
  printf("Original strings:");
  printf("\nString1: %s",string1);
  printf("\nString2: %s",string2);
  printf("\nn = %d",n);
  return_string = strncpy( string1, string2, n);
  printf("\nAfter strncpy(string1, string2, n):");
  printf("\nString1: %s",string1);
  printf("\nString2: %s",string2);
  n = 5; 
  printf("\n\nOriginal strings:");
  printf("\nString3: %s",string3);
  printf("\nString4: %s",string4);
  printf("\nn = %d",n);
  return_string = strncpy(string3, string4, n);
  printf("\nAfter strncpy(string3, string4, n):");
  printf("\nString3: %s",string3);
  printf("\nString4: %s",string4);
}
 

Output:

Original strings:
String1: 123456789
String2: abcdefg
n = 2
After strncpy(string1, string2, n):
String1: ab3456789
String2: abcdefg

Original strings:
String3: 123456789
String4: abcdefg
n = 5
After strncpy(string3, string4, n):
String3: abcde6789
String4: abcdefg

Example 2: Copying a partial string to initialize a file extension code:

Code:

#include <stdio.h>
#include <string.h>


int main() {
    // Source file name with extension
    char filename[] = "example.txt";
    // Array to store file extension
    char extension[5];

    // Copy only the last 4 characters to capture the file extension
    strncpy(extension, filename + 8, 4);
    // Ensure extension string is null-terminated
    extension[4] = '\0';

    // Print the extracted file extension
    printf("File extension: %s\n", extension);
    return 0;
}

Output:

File extension: txt

Explanation:

  • Defines filename with "example.txt".
  • Copies the last 4 characters of filename to extension, capturing ".txt".
  • Manually null-terminates extension to ensure it functions as a string.
  • Displays the extracted file extension.

Example 3: Copying a Prefix from a String

Code:

#include <stdio.h>
#include <string.h>

int main() {
    // Define the full name
    char fullName[] = "Bethari Cunmin";
    // Define an array to store the first name
    char firstName[8];

    // Copy the first 7 characters into firstName
    strncpy(firstName, fullName, 7);
    // Null-terminate firstName
    firstName[7] = '\0';

    // Print the first name
    printf("First name: %s\n", firstName);
    return 0;
}

Output:

First name: Bethari

Explanation:

  • Defines fullName with "Jonathan Smith".
  • Copies the first 7 characters into firstName.
  • Adds a null terminator to ensure firstName is valid.
  • Outputs "Jonathan" as the extracted first name.

C Programming Code Editor:

Previous C Programming: C strcpy()
Next C Programming:C strcspn()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming/string/c-strncpy.php