C语言fprintf()和fscanf()函数

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

fprintf()函数的语法如下:

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

示例:

创建一个源文件:fprintf-write-file.c,其代码如下 -

#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  
    printf("Write to file : file.txt finished.");
}

执行上面示例代码,得到以下结果 -

Write to file : file.txt finished.

打开filehadling 目录下,应该会看到一个文件:file.txt

读取文件:fscanf()函数

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

fscanf()函数的语法如下:

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

示例:

创建一个源文件:fscanf-read-file.c,其代码如下 -

#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,姓名和工资。

示例:

创建一个源文件:storing-employee.c,其代码如下 -

#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 Emp ID:");
    scanf("%d", &id);
    fprintf(fptr, "Id= %d\n", id);
    printf("Enter the name: ");
    scanf("%s", name);
    fprintf(fptr, "Name= %s\n", name);
    printf("Enter the salary: ");
    scanf("%f", &salary);
    fprintf(fptr, "Salary= %.2f\n", salary);
    fclose(fptr);
}

执行上面示例代码,得到以下结果 -

Enter the Emp ID:10010
Enter the name: Maxsu
Enter the salary: 15000

现在从当前目录打开文件。将看到有一个emp.txt文件,其内容如下 -

emp.txt

Id= 10010
Name= Maxsu
Salary= 15000.00

上一篇: C语言文件处理 下一篇: C语言fputc()和fgetc()函数