【Linux C编程】第七章 系统IO函数1

举报
Yuchuan 发表于 2021/06/19 15:40:02 2021/06/19
【摘要】 系统函数IO

一、整体大纲

 二、常用文件IO函数介绍

    对于Centos7查看系统函数需要安装man手册

[root@centos linuxC]# yum -y install man-pages

1. 常用IO热身:

(1)首先来看下面一个示例:

print_where.c

1 #include<stdio.h>
 2 #include<fcntl.h>
 3 #include<sys/types.h>
 4 #include<unistd.h>
 5 
 6 int main()
 7 {
 8     close(1);
 9     int fd = open("msg.log", O_CREAT|O_TRUNC|O_WRONLY, 0644);
10     printf("hello world\n");
11     //fflush(stdout);
12     close(fd);
13 
14     return 0;
15 }

执行结果如下:

[root@centos linuxC]# gcc print_where.c -o print_where
[root@centos linuxC]# ./print_where
[root@centos linuxC]# cat msg.log

注意:没有打印出预期的"hello world",也没有在文件msg.log中写入"hello world"。

(2)去掉代码中的注释掉的 fflush 再试下:

[root@centos linuxC]# gcc print_where.c -o print_where
[root@centos linuxC]# ./print_where
[root@centos linuxC]# cat msg.log
hello world

注意:没有打印出 "hello world"但是将结果写入到了文件msg.log中。

 (3)结果分析:

    系统默认会打开三个文件描述符(stdin,stdout,stderr),在程序中close(1)关掉了标准输出,此时open打开返回的是最小可用的文件描述符,也就是 fd = 1,因此printf本应该打印到文件中,但是close(fd)不会触发buffer刷新,因此既不会输出到屏幕也没有输出到msg.log中。当打开fflush,则会刷新buffer,因此就可以看到msg.log文件中"hello world"。

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

举报
请填写举报理由
0/200