C-standard-library-c-function-fscanf

提供:Dev Guides
移動先:案内検索

Cライブラリ関数-fscanf()

説明

Cライブラリ関数 int fscanf(FILE stream、const char * format、…​)*は、ストリームからフォーマットされた入力を読み取ります。

宣言

以下は、fscanf()関数の宣言です。

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

パラメーター

  • stream -これは、ストリームを識別するFILEオブジェクトへのポインタです。
  • format -これは、次の項目の1つ以上を含むC文字列です-Whitespace character、Non-whitespace character_および_Format specifiers。 書式指定子は* [=%[*] [width] [modifiers] type =] *になります。これについては以下で説明します-
Sr.No. Argument & Description
1 これはオプションの開始アスタリスクで、データはストリームから読み取られるが無視されることを示します。 対応する引数には保存されません。
2

width

これは、現在の読み取り操作で読み取られる最大文字数を指定します。

3

modifiers

が指すデータに対して、int(d、i、nの場合)、unsigned int(o、u、xの場合)、またはfloat(e、f、gの場合)とは異なるサイズを指定します対応する追加の引数:h:short int(d、i、nの場合)、またはunsigned short int(o、u、xの場合)l:long int(d、i、nの場合)、またはunsigned long int(oの場合、 uおよびx)、またはdouble(e、fおよびgの場合)L:long double(e、fおよびgの場合)

4

type

読み取られるデータのタイプと、その読み取り方法を指定する文字。 次の表を参照してください。

fscanf型指定子

type Qualifying Input Type of argument
c Single character: Reads the next character. If a width different from 1 is specified, the function reads width characters and stores them in the successive locations of the array passed as argument. No null character is appended at the end. char *
d Decimal integer: Number optionally preceded with a + or - sign int*
e, E, f, g, G Floating point: Decimal number containing a decimal point, optionally preceded by a + or - sign and optionally followed by the e or E character and a decimal number. Two examples of valid entries are -732.103 and 7.12e4 float *
o Octal Integer: int*
s String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab). char *
u Unsigned decimal integer. unsigned int*
x, X Hexadecimal Integer int *
  • 追加引数-書式文字列に応じて、関数は追加の引数のシーケンスを期待する場合があり、それぞれに書式パラメータで指定された各%タグの代わりに1つの値が含まれます(存在する場合)。 これらの引数の数は、値を予期する%タグの数と同じでなければなりません。

戻り値

この関数は、正常に一致して割り当てられた入力項目の数を返します。これは、指定された数よりも少ない場合があります。

次の例は、fscanf()関数の使用法を示しています。

#include <stdio.h>
#include <stdlib.h>


int main () {
   char str1[10], str2[10], str3[10];
   int year;
   FILE * fp;

   fp = fopen ("file.txt", "w+");
   fputs("We are in 2012", fp);

   rewind(fp);
   fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);

   printf("Read String1 |%s|\n", str1 );
   printf("Read String2 |%s|\n", str2 );
   printf("Read String3 |%s|\n", str3 );
   printf("Read Integer |%d|\n", year );

   fclose(fp);

   return(0);
}

次の結果を生成する上記のプログラムをコンパイルして実行しましょう-

Read String1 |We|
Read String2 |are|
Read String3 |in|
Read Integer |2012|