0

What is the best way to add a '\r' to my new-line sequence? I am writing a string to a file and doing various parsing to it but according to my assignment spec a new line will be considered '\r\n'.

Right now I only have a new line at the end. I was thinking of a for loop and/or using memmove but not sure exactly how to make it work?

for (int x = 0;x < strlen(string);x++)
{
    if (string[x] == '\n')
    {
        ..............
    }
}
  • 1
    You can't simply append an additional character to the end of a string if you haven't made room for it. Your code doesn't show how `string` is defined and initialized. – jwdonahue Nov 02 '17 at 19:29
  • What are you doing now? How does it not work? Provide complete code. – klutt Nov 02 '17 at 19:29
  • Please review https://stackoverflow.com/help/mcve. – jwdonahue Nov 02 '17 at 19:31
  • 1
    Why not let the system handle that by including `\n` in the output string, after opening the output file in text mode. If the system typically uses `"\r\n"` then `"\n"` will be automatically expanded (or contracted on a read). – Weather Vane Nov 02 '17 at 19:48

1 Answers1

0

The algorithm is something along the lines of:

  1. Check that the last two characters in string aren't already "\r\n", if they are return string.
  2. Check whether the last character in string has either '\r' or '\n', set a flag.
  3. Allocate strlen(string) + 2 bytes to hold the new string, if the flag is set, otherwise allocate strlen(string) + 3 bytes.
  4. Calculate bytes to copy as strlen(string) - 1 if flag is set, otherwise strlen(string).
  5. Copy number of bytes to copyfrom string to the allocated storage.
  6. Append "\r\n\0" to the end of the bytes copied above.
  7. Return the string just created in allocated storage.

EDIT: Your mileage may vary if you can make assumptions about the state of string. If it resides in a large enough buffer to add characters to the end of it, no new allocation would be required. If your char type is not one byte, you would need to adjust accordingly.

jwdonahue
  • 6,199
  • 2
  • 21
  • 43