Question

I am reading C primer Plus 5th edition and I am in the I/O chapter. I come up with an example (page 451) that do some stuff and in some point it creates a new file which is named after a existing file but with an .red ending. For example if I have this file "test", the programme creates a "test.red". I cannot understand the following..

char name[LEN];
//some code...

strncpy(name,argv[1], LEN - 5);
name[LEN - 5] = '\0';
strcat(name,".red");

I looked the definition of the command strcpy. It copies the first LEN-5 characters from the arv[1] (it contains the source file) to the name. The strcat command adds the .red to the end. However, I cannot understand the existence of this name[LEN - 5] = '\0';. I removed it and the program still working good.
EDIT
I post the comment from the book for these lines..

To construct the new name for the output file, the program uses strncpy() to copy the name eddy into the array name. The LEN - 5 argument leaves room for the .red suffix and the final null character. No null character is copied if the argv[2] string is longer than LEN – 5, so the program adds a null character just in case. The first null character in name after the strncpy() call then is overwritten by the period in .red when the strcat() function appends that string, producing, in this case, eddy.red.

Was it helpful?

Solution

In C, strings are just arrays of characters. To know where the string ends, a '\0' character (the character with the character code zero, called the NUL character in the ASCII alphabet) is added after the last character.

strncpy copies at most the number of characters given by its third argument, and there is no guarantee that the copy will be NUL-terminated. Back when strncpy was designed, storage was more limited than today, and even a single byte was important. Since if one knew that, say, 14 characters was the maximum for a certain string, one could store a 14-character string without the terminating NUL character.

So, when working with strncpy, if the string copy is to be used in other C functions, such as strcat, one needs to add that missing NUL character, in the cases strncpy didn't copy it.

It might work anyway, if there happens to be a NUL character in that place from the start, but that is not something that you an rely on, or that the compiler will help you with.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top