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 

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

技术教程推荐

从0开始做增长 -〔刘津〕

玩转webpack -〔程柳锋〕

说透中台 -〔王健〕

互联网人的英语私教课 -〔陈亦峰〕

软件设计之美 -〔郑晔〕

A/B测试从0到1 -〔张博伟〕

说透区块链 -〔自游〕

陈天 · Rust 编程第一课 -〔陈天〕

结构思考力 · 透过结构看思考 -〔李忠秋〕

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