前言

这两个函数与printf()和scanf()函数类似。
scanf()printf()的返回值为成功输入的数据个数

scanf(”%d%d%s”,&a,&b,s);执行成功返回3.
scanf(”%d%d”,&a,&b);执行成功返回2.

如果在输入的过程中scanf(“%d%d”,&a,&b);由于某种原因只有a输入成功了则返回1,a、b都没成功则返回0

如果遇到错误或遇到end of file,返回EOF(一般宏定义EOF为-1)。

区别

加多第一个参数(FILE指针)

rewind();

  1. 参数:FILE指针
  2. 作用
    回到文件开头

示例

输入到文件中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 41

int main(void)
{
FILE *fp;
char words[MAX];//临时存储每个字符串。

if ((fp = fopen("wordy", "a+")) == NULL)
{
fprintf(stdout,"Can't open \"wordy\" file.\n");
exit(EXIT_FAILURE);
}

puts("Enter words to add to the file; press the #");
puts("key at the beginning of a line to terminate.");
while ((fscanf(stdin,"%40s", words) == 1) && (words[0] != '#'))
fprintf(fp, "%s\n", words);

puts("File contents:");
rewind(fp); /* go back to beginning of file */
while (fscanf(fp,"%s",words) == 1)
puts(words);
puts("Done!");
if (fclose(fp) != 0)
fprintf(stderr,"Error closing file\n");

return 0;
}

注意

1
2
while ((fscanf(stdin,"%40s", words) == 1)  && (words[0] != '#'))
fprintf(fp, "%s\n", words);
  1. fscanf()的文件指针是stdin是从键盘中进行标准输入,并且将输入的每个字符串用while循环存储到字符串works[]
    即等于scanf("%s", words);
  2. fprintf()的文件指针是fp,就是将words每个字符串,一个一个地输入到文件。
  3. scanf与%s

1
2
while (fscanf(fp,"%s",words) == 1)
puts(words);
  1. fscanf()的文件指针是fp,将文件中的每个字符串(到空白字符结束)逐个读入words中,并逐个puts函数输出。