加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

Linux中的系统IO函数

发布时间:2020-12-14 01:11:37 所属栏目:Linux 来源:网络整理
导读:一、整体大纲 ?二、常用文件IO函数介绍 ? ? 对于Centos7查看系统函数需要安装man手册 [[email?protected] linuxC]# yum -y install man-pages 1. 常用IO热身: (1)首先来看下面一个示例: 1 #includestdio.h 2 #includefcntl.h 3 #includesys/types.h 4 #i

一、整体大纲

?二、常用文件IO函数介绍

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

[[email?protected] linuxC]# yum -y install man-pages

1. 常用IO热身:

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

 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 worldn");
11     //fflush(stdout);
12     close(fd);
13 
14     return 0;
15 }
print_where.c

执行结果如下:

[[email?protected] linuxC]# gcc print_where.c -o print_where
[[email?protected] linuxC]# ./print_where
[[email?protected] linuxC]# cat msg.log

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

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

[[email?protected] linuxC]# gcc print_where.c -o print_where
[[email?protected] linuxC]# ./print_where
[[email?protected] 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"。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读