zoukankan      html  css  js  c++  java
  • Linux C编程之七(1)系统IO函数

    一、整体大纲

     二、常用文件IO函数介绍

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

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

    执行结果如下:

    [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"。

  • 相关阅读:
    Java8性能优化之字符串拼接
    Java8字符串分割的几种方式及性能比较
    【Collections:集合工具类:常用方法】
    【ArrayList嵌套HashMap】
    【集合工具类:Collections】
    【HashMap 嵌套 HashMap】
    【HashMap 嵌套 ArrayList】
    【TreeMapDemo】
    【LinkedHashMap】
    【TreeMap】
  • 原文地址:https://www.cnblogs.com/xuejiale/p/10777650.html
Copyright © 2011-2022 走看看