2

This is probably a very newbish question, but can I fix this so that any characters (except \r) are added to my new string ucontents? Just now it only add characters up until the \r. I want to add characters after \r too.

void to_unix_line_endings(char* contents, char* ucontents) { int i; for (i = 0; i < strlen(contents); i++) { if(contents[i] != '\r') { ucontents[i] = contents[i]; } } } char out[5000]; to_unix_line_endings("spaghettiand\rmeatballs", out); printf("%s\n", out); // Prints "spaghettiand". I want "spaghettiandmeatballs". 

Thanks.

2
  • 2
    ucontents[i] : use other index variable instead of i. and null-terminator add to end. Commented May 8, 2016 at 13:42
  • Thanks. I've added how I fixed it below following your advice. Have I added the null terminator correctly? Commented May 8, 2016 at 13:48

2 Answers 2

2

In the comments (under your answer), @BLUEPIXY is pointing out that because j will never be equal to length, ucontents will never be NULL terminated in the if(j == length) block.

So although your code example (in the answer section) appeared to work for you as is, the code will eventually fail. printf() needs a null terminator to identify end of string. When the memory you are writing to does not happen to have a NULL terminator in the right spot, it will fail. (as would any of the string functions).

The following change will null terminate your buffer:

void to_unix_line_endings(char* contents, char* ucontents) { int i; int j = 0; int length = strlen(contents);//BTW, good improvement over original post for (i = 0; i < length; i++) { if(contents[i] != '\r') { ucontents[j] = contents[i]; /*if (j == length) { //remove this section altogether ucontents[j] = '\0'; break; }*/ j++;//this increment ensures j is positioned //correctly for NULL termination when loop exits } } ucontents[j]=NULL;//add NULL at end of loop } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I changed my code to take out the redundant block.
1

Fixed like so. Thanks, BLUEPIXY.

void to_unix_line_endings(char* contents, char* ucontents) { int i; int j = 0; int length = strlen(contents); for (i = 0; i < length; i++) { if(contents[i] != '\r') { ucontents[j] = contents[i]; if (j == length) { ucontents[j] = '\0'; break; } j++; } } } 

3 Comments

Thanks. That was better than what I did. I'm porting a program from C++ to C.
@SamSaint-Pettersen - Your if (j == length) block will never be executed. (this is what BLUEPIXY's comment is saying)
@ryyker: Thanks. I understood that. I meant the sample was better because it correctly attached the null character.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.