I have a configuration file that is supposed to have \r\n line ending style, and I want to include the code in my program to check and correct the format. Existing code:
int convert_line_endings(FILE *fp)
{
char c = 0, lastc = 0, cnt = 0;
while((c = fgetc(fp)) != EOF)
{
if((c == '\n') && (lastc != '\r'))
{
cnt++;
//somehow "insert" a '\r' in here, after the previous char and before the '\n'
}
lastc = c;
}
return cnt;
}
And in C programming, you can't "insert" a char (or can you?!), just overwrite one or the other. Any suggestions?
No, you can't delete or insert. What you can do is write to a new temporary file by copying everything except \r\n
sequences and then overwrite the original file with it.