C fprintf() and fscanf() example函数

首页 / C语言入门教程 / C fprintf() and fscanf() example函数

fprintf()函数

fprintf()函数用于将字符集写入文件。它将格式化的输出发送到流。

语法:

int fprintf(FILE *stream, const char *format [, argument, ...])

示例:

#include<stdio.h> 
main(){
   FILE *fp;
   fp = fopen("file.txt", "w");//opening file
   fprintf(fp, "Hello file by fprintf...\n");//writing data into file
   fclose(fp);//closing file
}

fscanf()函数

fscanf()函数用于从文件读取字符集。它从文件中读取一个单词,并在文件末尾返回EOF。

语法:

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

示例:

#include<stdio.h>
main(){
   FILE *fp;
   char buff[255];//creating char array to store data of file
   fp = fopen("file.txt", "r");
   while(fscanf(fp, "%s", buff)!=EOF){
   printf("%s ", buff );
   }
   fclose(fp);
}

输出:

Hello file by fprintf...

让我们看一个文件处理示例,该示例存储用户从控制台输入的员工信息。我们将存储员工的ID,姓名和工资。

#include<stdio.h> 
void main()
{
    FILE *fptr;
    int id;
    char name[30];
    float salary;
    fptr = fopen("emp.txt", "w+");/*  open for writing */
    if (fptr == NULL)
    {
        printf("File does not exists \n");
        return;
    }
    printf("Enter the id\n");
    scanf("%d", &id);
    fprintf(fptr, "Id= %d\n", id);
    printf("Enter the name \n");
    scanf("%s", name);
    fprintf(fptr, "Name= %s\n", name);
    printf("Enter the salary\n");
    scanf("%f", &salary);
    fprintf(fptr, "Salary= %.2f\n", salary);
    fclose(fptr);
}

输出:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

现在从当前目录打开文件。对于Windows操作系统,请转到TC\bin目录,您将看到emp.txt文件。它将具有以下信息。

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Service Mesh实践指南 -〔周晶〕

编译原理之美 -〔宫文学〕

Netty源码剖析与实战 -〔傅健〕

Electron开发实战 -〔邓耀龙〕

Serverless入门课 -〔蒲松洋(秦粤)〕

OAuth 2.0实战课 -〔王新栋〕

React Native 新架构实战课 -〔蒋宏伟〕

Web 3.0入局攻略 -〔郭大治〕

现代C++20实战高手课 -〔卢誉声〕

好记忆不如烂笔头。留下您的足迹吧 :)