I'm reading a multi-line file with the
fscanf()
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]);