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()函数用于从文件读取字符集。它从文件中读取一个单词,并在文件末尾返回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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)