C语言的文件IO函数

本文深入探讨了C语言中的文件输入输出函数,包括fprintf()、fscanf()、fgets()和fputs()。通过实例演示了如何使用fprintf()和fscanf()进行格式化文件读写,以及如何利用fgets()和fputs()处理字符串输入输出。文章提供了详细的函数说明和返回值解释,适合初学者和进阶者参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C语言的文件IO函数

在这里插入图片描述

引言

C语言文件I/O函数主要指fprintf()、fscanf()、fgets()和fputs()。它们既可以实现向gets()、puts()、getc()和putc()函数样从键盘和屏幕进行输入输出,也可以对文件进行输入输出。

fprintf()和fscanf()函数

头文件:#include <stdio.h>

定义函数:int fprintf(FILE * stream, const char * format, ...);

函数说明:fprintf()会根据参数format 字符串来转换并格式化数据, 然后将结果输出到参数stream 指定的文件中, 直到出现字符串结束(’\0’)为止。

返回值:关于参数format 字符串的格式请参考printf()。 成功则返回实际输出的字符数, 失败则返回-1, 错误原因存于errno 中。

示例:

/* addaword.c -- uses fprintf(), fscanf(), and rewind() */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 41

int main(void)
{
    FILE *fp;
    char words[MAX];
    
    if ((fp = fopen("wordy", "a+")) == NULL)
    {
        fprintf(stdout,"Can't open \"wordy\" file.\n");
        exit(EXIT_FAILURE);
    }
    
    puts("Enter words to add to the file; press the #");
    puts("key at the beginning of a line to terminate.");
    while ((fscanf(stdin,"%40s", words) == 1)  && (words[0] != '#'))
        fprintf(fp, "%s\n", words);
    
    puts("File contents:");
    rewind(fp);           /* go back to beginning of file */
    while (fscanf(fp,"%s",words) == 1)
        puts(words);
    puts("Done!");
    if (fclose(fp) != 0)
        fprintf(stderr,"Error closing file\n");
    
    return 0;
}

该程序可以在文件中添加单词。使用"a+"模式,程序可以对文件进行读写操作。首次使用该程序,它将创建wordy文件,以便把单词存入其中。随后再使用该程序,可以在wordy文件后面添加单词。虽然"a+"模式只允许在文件末尾添加内容,但是该文件模式可以读整个文件。rewind()函数让程序回到文件开始处,方便while循环打印整个文件的内容。注意,rewind()接受一个文件指针作为参数。

下面是在Cygwin在windows下模拟的linux环境下运行示例(可执行程序名字为a.exe):

$ ./a.exe[第一次运行]
Enter words to add to the file; press the #
key at the beginning of a line to terminate.
The fabulous programmer
#
File contents:
The
fabulous
programmer
Done!
$ ./a.exe[第二次运行]
Enter words to add to the file; press the #
key at the beginning of a line to terminate.
enchanted the
large
#
File contents:
The
fabulous
programmer
enchanted
the
large
Done!

fgets()和fputs()函数

这两个函数的分析可以参考前面的博客《C语言的字符串输入fgets()函数》和《C语言的字符串输出fputs()函数》。


参考资料:

[1] 史蒂芬・普拉达. C Primer Plus (第6版) 中文版[M]. 人民邮电出版社, 2016.

[2] C语言fprintf()函数:输出函数(格式化输出数据至文件-来源

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Galaxy_Robot

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值