Skip to the content.

标准IO和系统调用IO的区别

标准IO和系统调用IO的区别如下表:

  标准IO 系统调用IO
帮助(man手册) man 3 man 2
文件描述符 FILE 类型的流 int 类型文件描述符
缓存 行缓存、全缓存、不缓存 不带缓存

标准IO常用的函数和注意项

函数说明:

  #include <stdio.h>
  
         FILE *fopen(const char *path, const char *mode);
  
         FILE *fdopen(int fd, const char *mode);   //有用
  
         FILE *freopen(const char *path, const char *mode, FILE *stream);

      关于mode:
       r      Open text file for reading.  The stream is positioned at the beginning of the file. (要求文件必须存在)

       r+     Open for reading and writing.  The stream is positioned at the beginning of the file.(要求文件必须存在)

       w      Truncate  file to zero length or create text file for writing.  The stream is positioned at
              the beginning of the file.

       w+     Open for reading and writing.  The file is created if it does not exist,  otherwise  it  is
              truncated.  The stream is positioned at the beginning of the file.

       a      Open  for  appending  (writing  at end of file).  The file is created if it does not exist.
              The stream is positioned at the end of the file.

       a+     Open for reading and appending (writing at end of file).  The file is created  if  it  does
              not exist.  The initial file position for reading is at the beginning of the file, but out‐
              put is always appended to the end of the file.(读和写的位置是不同的)

几个注意点:

在windows环境下需要注意加’b’,识别二进制文件,而在Linux/UNIX中不需要考虑这个问题;

只识别以上面字符开头的mode字符串,如’readwrite’只识别’r’;

自动创建的文件将具有umak定义的默认权限,可用umask修改;默认权限:S_IRUSR S_IWUSR S_IRGRP S_IWGRP S_IROTH S_IWOTH (0666)

那么fopen返回的FILE,存放在哪里?堆。一般来说,有对应逆操作的函数,都会放在堆上。

关于freopen(const char *path, const char *mode, FILE *stream)函数,一般用于修改stderr,stdout 到一个文件,如下所示:

#include <stdio.h>
#include <stdlib.h>

int main(void){

        FILE * f;

        f = freopen("/tmp/test", "a", stderr);

        fprintf(stderr, "test for freopen()\n");

        fclose(f);
        return 0;
}

FILE *fdopen(int fd, const char *mode),将一个文件描述符转换为一个FILE流,比如将socket文件描述符转换为FILE流,用标准IO函数来处理socket。