You are reading a data file that was created on a Windows system. Lines are terminated by \r\n
(carriage return, line feed). You are either processing this file on that same Windows system, but you are opening the file in binary ("rb"
) mode. Or, you are transferring the file to a Unix or Linux (or Mac) system and processing it there, but you are transferring it in a "binary" mode, that preserves the CRLF, without converting it to the Unix single-newline ('\n'
) convention.
Then, you are reading lines of text, perhaps with fgets
. You are discarding the newline ('\n'
), but you are not discarding the carriage return ('\r'
). So, each line ends with \r
.
Then, you are splitting up the line into fields userdata[0]
, userdata[1]
, userdata[2]
, ... . I'm not sure if you're splitting it up at commas or at whitespace, but in any case, the \r
is remaining attached to the last field.
Finally, when you print out that last field userdata[k+2]
, that carriage return at the end of it is causing the cursor to return to the beginning of the line before the final )
is printed.
You can fix this in several ways:
- Don't create the file with
\r\n
in the first place.
- If processing the file on a Windows system, open it in text (
"r"
or maybe "rt"
) mode, not binary.
- If transferring files from a Windows to a non-Windows system, use a "text" transfer mode that converts line endings.
- When reading lines from the file, strip off trailing
\r
as well as \n
characters.
- If splitting fields on whitespace, include
'\r'
in the set of whitespace characters to split on. For example, if you are calling strtok
, with separators " "
or " \t"
, change to " \r"
or " \t\r"
.
Now that you've posted code, I can be more specific.
To achieve #4, add the line
if (buffer[strlen(buffer)-1] == '\r') buffer[strlen(buffer) - 1] = '\0';
after the line where you strip off the \n
.
To achieve #5, change your two strtok
calls to
data = strtok(buffer, " \r");
and
data = strtok(NULL, " \r");
As a matter of fact, you could also change those two lines to
data = strtok(buffer, " \r\n");
and
data = strtok(NULL, " \r\n");
and then you wouldn't need the newline-stripping step at all.
One more thing: your usage of feof
is wrong. See Why is while(!feof (fp))
always wrong?.