个性化阅读
专注于IT技术分析

c使用fprintf和fscanf

点击下载

本文概述


编写文件: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...

C文件示例:存储员工信息

让我们看一个文件处理示例,该示例存储用户从控制台输入的员工信息。我们将存储员工的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)
未经允许不得转载:srcmini » c使用fprintf和fscanf

评论 抢沙发

评论前必须登录!