A
arnuld
WANTED: To write a function like strcpy(). Unlike strcpy() it copies till
a newline occurs.
GOT: It is working fine. Just want to have any ideas for improvement
#include <stdio.h>
enum { SIZE_ARR = 20 };
int string_copy_till_newline(char dest[], char src[]);
int main(void)
{
char arr_dest[SIZE_ARR]; /* intentionally not initialized with NULLs.
Check the intended function definition */
char arr_src[] = "This is\n an Array\n";
printf("arr_dest = %s\n", arr_dest);
printf("arr_src = %s\n", arr_src);
printf("\n\n------------------------------\n\n");
string_copy_till_newline(arr_dest, arr_src);
printf("arr_dest = %s\n", arr_dest);
printf("arr_src = %s\n", arr_src);
return 0;
}
/* Will copy contents from SRC to DEST till a newline occurs, will not
include newline, puts a NULL character at the end.
returns number of characters copied, else -1 on error. Will write
beyond the array, size checking is user's responsibility */
int string_copy_till_newline(char dest[], char src[])
{
int idx;
if(NULL == dest || NULL == src)
{
printf("IN: %s at %d: One of the arguments is NULL\n", __func__,
__LINE__);
return -1;
}
for(idx = 0; src[idx] != '\n'; ++idx)
{
dest[idx] = src[idx];
}
dest[idx] = '\0';
return idx;
}
==================== OUTPUT ==========================
[arnuld@dune TEST]$ gcc -ansi -pedantic -Wall -Wextra string-copy-till-
newline.c
[arnuld@dune TEST]$ ./a.out
arr_dest = %Ψ
arr_src = This is
an Array
------------------------------
arr_dest = This is
arr_src = This is
an Array
[arnuld@dune TEST]$
a newline occurs.
GOT: It is working fine. Just want to have any ideas for improvement
#include <stdio.h>
enum { SIZE_ARR = 20 };
int string_copy_till_newline(char dest[], char src[]);
int main(void)
{
char arr_dest[SIZE_ARR]; /* intentionally not initialized with NULLs.
Check the intended function definition */
char arr_src[] = "This is\n an Array\n";
printf("arr_dest = %s\n", arr_dest);
printf("arr_src = %s\n", arr_src);
printf("\n\n------------------------------\n\n");
string_copy_till_newline(arr_dest, arr_src);
printf("arr_dest = %s\n", arr_dest);
printf("arr_src = %s\n", arr_src);
return 0;
}
/* Will copy contents from SRC to DEST till a newline occurs, will not
include newline, puts a NULL character at the end.
returns number of characters copied, else -1 on error. Will write
beyond the array, size checking is user's responsibility */
int string_copy_till_newline(char dest[], char src[])
{
int idx;
if(NULL == dest || NULL == src)
{
printf("IN: %s at %d: One of the arguments is NULL\n", __func__,
__LINE__);
return -1;
}
for(idx = 0; src[idx] != '\n'; ++idx)
{
dest[idx] = src[idx];
}
dest[idx] = '\0';
return idx;
}
==================== OUTPUT ==========================
[arnuld@dune TEST]$ gcc -ansi -pedantic -Wall -Wextra string-copy-till-
newline.c
[arnuld@dune TEST]$ ./a.out
arr_dest = %Ψ
arr_src = This is
an Array
------------------------------
arr_dest = This is
arr_src = This is
an Array
[arnuld@dune TEST]$