Use fscanf function

fscanf function usage

brief introduction

fcanf () function is a function to read and write format. It is an object of reading a disk file

Prototype:

int fscanf(FILE * fp,char * format,...);

Wherein the file pointer fp, format string is C, ... for the parameter list and returns the number of characters is successfully written.

fscanf function reads the data stream is stored in the format, the file input from experiencing the end of a space and line feed .

Examples of Use

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

typedef struct {
    int id;                 //学生id
    char name[30];          //学生姓名
    char address[100];      //学生地址
}Student;

int main()
{
    Student student;
    FILE* fp = fopen("D:\\markdown.txt", "wt+");
    if (fp == NULL)
    {
        puts("文件不存在,请在指定目录下先行创建文件!");
        exit(0);
    }

    printf("请依次输入学生的id,姓名和地址:\n");
    scanf("%d%s%s", &student.id, student.name, student.address);

    //将学生信息存入D:\\markdown.txt文件中
    fprintf(fp, "%d\t%s\t%s\n", student.id, student.name, student.address);

    Student temp;
    //重置文件指针
    rewind(fp);
    //将文件中的信息读取出来并且存储到temp中
    fscanf(fp, "%d\t%s\t%s\n", &temp.id, temp.name, temp.address);

    printf("第%d位学生的姓名为:%s,地址为%s\n", temp.id, temp.name, temp.address);
    
    fclose(fp);

    return 0;
}

operation result:

请依次输入学生的id,姓名和地址:
1
yaya
未知
第1位学生的姓名为:yaya,地址为未知

important point

1, when fscanf function reads the data in the file input stream, encountered a space or newline will end the reading, if you want to ignore the impact of space, you can use

fscanf(fp, "%[^\n]", test);

Above this statement,% [] denotes read the specified character set, i.e.% [0-2] is read a number between 0 and 2 (including 0 and 2), ^ represents read backwards, i.e. read outside the specified character set characters, the characters encounter designated stops (do not read the specified character). So% [^ \ n] represents reads characters until it encounters \ far n.

If you want to read out a newline, but not stored in a variable, you can use

fscanf(fp, "%[^\n]%*c", test);

2, scanf and fscanf interconversion

char name[10] = "";
scanf("%[0-2]", name);              //等价于下一句
fscanf(stdin, "%[0-2]", name);      //等价于上一句
printf("%s", name);

Guess you like

Origin www.cnblogs.com/yaya12138/p/11329319.html