fscanf

Description

The function fscanf() is similar to
sscanf(), but it takes its input from a file
associated with handle and interprets the
input according to the specified format, which is
described in the documentation for sprintf().

Any whitespace in the format string matches any whitespace in the input
stream. This means that even a tab \t in the format
string can match a single space character in the input stream.

Each call to fscanf() reads one line from the file.

Parameters

Return Values

If only two parameters were passed to this function, the values parsed will be
returned as an array. Otherwise, if optional parameters are passed, the
function will return the number of assigned values. The optional
parameters must be passed by reference.

If you want to read text files in csv format or the like(no matter what character the fields are separated with), you should use fgetcsv() instead. When a text for a field is blank, fscanf() may skip it and fill it with the next text, whereas fgetcsv() correctly regards it as a blank field.

If you want fscanf()to scan one variable in a large number of lines, e.g an Ipadress in a line with more variables, then use fscanf with explode()<?$filename = "somefile.txt";$fp = fopen($filename, "r") or die ("Error opening file! \n");$u = explode(" ",$line); // $u is the variable eg. an IPadresswhile ($line = fscanf($fp,"%s",$u)) {if(preg_match("/^$u/",$_SERVER['REMOTE_ADDR'])) {$badipadresss++;} // do something and continue scan}?>Besides, fscanf()is much faster than fgets()

fscanf works a little retardedly I've found. Instead of using just a plain %s you probably will need to use sets instead. Because it works so screwy compared to C/C++, fscanf does not have the ability to scan ahead in a string and pattern match correctly, so a seemingly perfect function call like:

fscanf($fh, "%s::%s");

With a file like:

user::password

Will not work. When fscanf looks for a string, it will look and stop at nothing except for a whitespace so :: and everything except whitespace is considered part of that string, however you can make it a little smarter by:

fscanf($fh, "%[a-zA-Z0-9,. ]::%[a-zA-Z0-9,. ]" $var1, $var2);

Which tells it that it can only accept a through z A through Z 0 through 9 a comma a period and a whitespace as input to the string, everything else cause it to stop taking in as input and continue parsing the line. This is very useful if you want to get a sentence into the string and you're not sure of exactly how many words to add, etc.