博学而笃志 切问而近思 仁在其中
详情
C语言fprintf()和fscanf()函数
作者:--     发布时间:2019-11-20     评论:0     阅读:0

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


下一篇:测试
相关文章
loading......
最新动态
所有评论

loading......

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册