Search code examples
cstringc-stringschars

Add all characters except \r to new string


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.


Solution

  • 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
    }