piper1935 piper1935 - 23 days ago 7
C Question

Ignoring newline characters with fscanf()

I'm reading a multi-line file with the

fscanf()
function. I'd like to ignore the newline characters, but not other whitespace characters that might be in the file. How can I best do this?

Answer

I think that this does what you ask:

char ch[2];
while (fscanf(fp, "%1[^\n]%*[\n]", ch) == 1)
    putchar(ch[0]);

The first format specifier reads up to one character that is not a newline and stores it in the string ch, and the second specifier reads newlines but suppresses assignment. The result of this loop is to print all of the characters in the file, skipping over newlines, until EOF.

@AnT has pointed out in the comments that this method will fail for a text file the starts with a newline character, and has suggested the fix: a call to fscanf() before the loop that reads newlines while suppressing assignment. The improved code is:

char ch[2];
fscanf(fp, "%*[\n]");
while (fscanf(fp, "%1[^\n]%*[\n]", ch) == 1)
    putchar(ch[0]);
Comments