Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home/myscript/public_html/classes/classdb.php on line 42
fscanf() - I/O Function - C++ Tutorial

fscanf() - I/O Function

How is "fscanf()" used in C++?

Explanation

fscanf() is an I/O function similar to scanf but this function reads information from a stream. The function returns the number of items read on success, it can be zero if a matching failure occurs. If an input failure occurs before reading data could result in EOF.

Syntax:


int fscanf( FILE * stream, const char *format,...);

In the above syntax in the format parameter the function discards the whitespace.All the non-whitespace characters except "%" are skipped, then the next character is read. The "%" indicates a format specifier. The following table lists the format specifier used with "fscanf" function.
Type Description Argument
c Used to read a single character, if the width is more than 1 the function reads all the specified width of characters and stores them in successive locations of the array passed as argument. char *
d Represents a decimal integer that mey be preceeded with +/ - sign. int *
e,E,f,g,G Used to represent a floating point number containing a decimal point that may have a +/- sign with a e or E character. float *
o Specifies an octal value int *
s This format type is used to read string of characters until a whitespace is found. char *
u Unsigned decimal integer unsigned int *
x,X Represents a hexadecimal integer. int *

Example :



#include <stdio.h>
int main()
{
FILE *fp;
char name[100];
fp = fopen("fscanfeg.txt", "r");
fscanf(fp, "%s", name);
printf("%s\n", name);
fclose(fp);
return 0;
}

Result :

Hscripts

In the above example the "fscanf()" is used to read the text "Hscripts" from the text file.

C++ Tutorial


Ask Questions

Ask Question