#include<stdio.h>#include<string.h>/* Compile: cc -g -Wall -o copy-strings copy-strings.c *//* Run: ./copy-strings */intmain(intargc, char *argv[])
{
charprogram_name[100];
charyour_name[100];
strcpy(program_name, argv[0]);
if (argc != 2)
{
printf("Usage: %s <your_name>\n", program_name);
return 1;
}
printf("This program's name is %s.\n", program_name);
strcpy(your_name, argv[1]);
printf("Your name is '%s'.\n", your_name);
return 0;
}
Using strncpy(3) is consider safer than strcpy(3):
(for details see the man page, section 'SECURITY CONSIDERATIONS'):
#include<stdio.h>#include<string.h>/* Compile: cc -g -ansi -pedantic -Wall -O2 -o copy-strncpy copy-strncpy.c *//* Run: ./copy-strncpy */#defineMAX_LEN_PROGRAM_NAME 100
#defineMAX_LEN_YOUR_NAME 10
intmain(intargc, char *argv[])
{
charprogram_name[MAX_LEN_PROGRAM_NAME], your_name[MAX_LEN_YOUR_NAME];
/* Command line validation. */if (argc != 2)
{
printf("Usage: %s <your_name>\n", argv[0]);
if (argc == 1)
{
printf("Tip: Add your name as the 2nd argument. ;-)\n");
}
return 1;
}
if (strlen(argv[0]) > MAX_LEN_PROGRAM_NAME)
{
/* Error: program name is too long. */
printf("Error: The program name must be %i characters or less.\n", MAX_LEN_PROGRAM_NAME);
return 1;
}
if (strlen(argv[1]) > MAX_LEN_YOUR_NAME)
{
/* Error: your name is too long. */
printf("Sorry, this program only accepts names shorter than %i characters.\n", MAX_LEN_YOUR_NAME);
return 1;
}
/* Copy program name string. */
(void)strncpy(program_name, argv[0], sizeof(program_name) - 1);
/* NULL-terminate string. */
program_name[sizeof(program_name) - 1] = '\0';
/* Print program name. */
printf("This program's name is %s.\n", program_name);
/* Copy your name string. */
(void)strncpy(your_name, argv[1], sizeof(your_name) - 1);
/* NULL-terminate string. */
your_name[sizeof(your_name) - 1] = '\0';
/* Print your name. */
printf("Your name is '%s'.\n", your_name);
printf("Hello, %s!\n", your_name);
return 0;
}