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);
}
输出:
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