Welcome, coders! Today, we're diving into the world of strings in C programming and learning about the strcpy() function. šÆ
strcpy()?strcpy() is a built-in C function that stands for "string copy." It copies the source string (the string from which characters are being copied) to the destination string (the string where the copied characters will be stored). š
Here's the basic syntax for using the strcpy() function:
char *strcpy(char *dest, const char *src);dest: the destination string (where the copied characters will be stored)src: the source string (the string from which characters are being copied)Let's see an example of how to use the strcpy() function:
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[20];
strcpy(destination, source);
printf("Source String: %s\n", source);
printf("Destination String: %s\n", destination);
return 0;
}In this example, we have a source string "Hello, World!", and a destination array destination that can store up to 20 characters. We use the strcpy() function to copy the source string into the destination array.
When we run this program, the output will be:
Source String: Hello, World!
Destination String: Hello, World!
š Note: The destination array should be large enough to hold the source string, including the null terminator (\0).
In real-world applications, the strcpy() function is useful for tasks such as reading user input, copying filenames, or handling strings in data structures like arrays. š”
Which function in C is used to copy a source string into a destination string?
Here's an example that demonstrates copying a line from a file into a string:
#include <stdio.h>
#include <string.h>
int main() {
FILE *file;
char line[100];
char filename[] = "example.txt";
file = fopen(filename, "r");
if (file == NULL) {
printf("Unable to open file.\n");
return 1;
}
fgets(line, sizeof(line), file);
fclose(file);
printf("Line from file: %s\n", line);
return 0;
}In this example, we open a file named example.txt and read a line into the line array using the fgets() function. Then we close the file, and print the line that we read.
š Note: The fgets() function reads up to one less than the size of the destination array, to account for the null terminator.
That's all for today! In the next lesson, we'll explore more string functions in C programming. Keep coding, and remember to have fun! šŖ