Home > Mobile >  General questions about scanf and fscanf in C programming language
General questions about scanf and fscanf in C programming language

Time:06-12

If I'm not wrong, library function int fscanf(FILE *stream, const char *format, ...) works exactly the same as function int scanf(const char *format, ...) except that it requires stream selection. For example if I wanted to read two ints from standard input the code would look something like this.

int first_number; 
int second_number; 
scanf("%d%d", &first_number, &second_number);

There's no point of me adding newline character in between format specifiers even though the second number is entered in next line of input? Function just looks for next decimal integer right? What happens when I enter two characters instead of ints? Why the function sometimes doesn't work if there's a space between format specifiers?

In addition to that. When reading from file with fscanf(..), lets says the txt file contains next lines:

P6
255
1920 1080

Do I need to specify next line characters in fscanf(..)? I read it like this.

FILE *input = ..
char type[2];
int tr;
int width; int height;
fscanf(input, "%s\n", &type);
fscanf(input, "%d\n" &tr);
fscanf(input, "%d %d\n", &width, &height)

Is there a need for \n to signal next line? Can fscanf(..) anyhow affect any other functions for reading files like fread()? Or is it a good practice to just stick to one function through the whole file?

CodePudding user response:

scanf(...) operates like fscanf(stdin, ....).

Unless '\n', ' ', or other white spaces are inside a "%[...]", as part of a format for *scanf(), scanning functions the same as if ' ', '\t' '\n' was used. (Also for '\v, '\r, '\f.)

// All function the same.
fscanf(input, "%d\n" &tr);
fscanf(input, "%d " &tr);
fscanf(input, "%d\t" &tr);

There's no point of me adding newline character in between format specifiers even though the second number is entered in next line of input?

All format specifiers except "%n", "^[...]", "%c" consume optional leading white-spaces. With "%d" the is no need other than style to code a leading white-space in the format.


Function just looks for next decimal integer right?

Simply: yes.


What happens when I enter two characters instead of ints?

Scanning stops. The first non-numeric input remains in stdin as well as any following input. The *scanf() return value reflects the incomplete scan.


Why the function sometimes doesn't work if there's a space between format specifiers?

Need example. Having spaces between specifiers is not an issue unless the following specifier is one of "%n", "^[...]", "%c".


When reading from file with fscanf(..), .... Do I need to specify next line characters in fscanf(..)?

No. fscanf() is not line orientated. Use fgets() to read lines. fscanf() is challenging to use to read a line. Something like

char buf[100];
int cnt = fscanf(f, "           
  • Related