Programming Reference/Librarys
Question & Answer
Q&A is closed
int fscanf(FILE *stream, const char *format, ...);
Performs formatted input conversion, reading from stream stream according to format format. The function returns when format is fully processed. Returns number of items converted and assigned, or EOF if end-of-file or error occurs before any conversion. Each of the arguments following format must be a pointer. Format string may contain:
blanks and tabs, which are ignored
ordinary characters, which are expected to match next non-white-space of input
%
optional assignment suppression character “*”
optional maximum field width
optional target width indicator:
h argument is pointer to short rather than int
l argument is pointer to long rather than int, or double rather than float
L argument is pointer to long double rather than float
conversion character:
d decimal integer; int* parameter required
i integer; int* parameter required; decimal, octal or hex
o octal integer; int* parameter required
u unsigned decimal integer; unsigned int* parameter required
x hexadecimal integer; int* parameter required
c characters; char* parameter required; white-space is not skipped, and NUL-termination is not performed
s string of non-white-space; char* parameter required; string is NUL-terminated
e,f,g floating-point number; float* parameter required
p pointer value; void* parameter required
n chars read so far; int* parameter required
[…] longest non-empty string from specified set; char* parameter required; string is NUL-terminated
[^…] longest non-empty string not from specified set; char* parameter required; string is NUL-terminated
% literal %; no assignment
/* * fscanf example code * http://code-reference.com/c/stdio.h/fscanf */ #include <stdio.h> /* including standard library */ //#include <windows.h> /* uncomment this for Windows */ int main ( void ) { FILE *stream; char content[80]; stream=fopen("test.txt","r"); if (stream == 0) { perror("error opening file\n"); return 1; } while (( fscanf( stream, "%s", &content )) != EOF ) { printf("%s\n",content); } return 0; }
content of test.txt
Test 1 2 3 4
output:./fscanf Test 1 2 3 4