12 File and Device I/O using System Calls

1 System Calls, File Management and Device I/O

1.用户使用C standard library,调用malloc() calloc(),真实的空间申请是系统调用sbrk()
2.

2 Hello World (again)

1.假设没有C standard library(fopen,fwrite,fread),我们就需要低等级的函数,既系统调用,直接写入device

#include <unistd.h>
int main(int argc, char * argv[]){
  char hello[] = "Hello World\n";
  char *p;
  for(p = hello ; *p ; p++){
     write(1, p, 1); 
  }

}

2.1 Basics of write() to terminal

1.read() and write()操作文件描述符(fd),而不是文件流(file stream);
2.read from or write to buffers not strings

//    .-- Write to standard out, file descriptor 1
//    v
write(1, p, 1); 
//       ^  ^
//       |  '--- Number of bytes to write, just the char p points to
//       |
//       '-------- char *, points to the byte we want to write

3 read() and write() in Detail

3.1 write()'ing a Buffer of Bytes

1.A buffer is the general term for an array of bytes.

  ssize_t write(int fd, const void *buf, size_t count);
//                  ^               ^            ^
//file descriptor---'       buffer--'            '-- num. bytes to write

3.2 read()'ing a Buffer of Bytes

  ssize_t read(int fd,      void *buf, size_t count);
//                  ^               ^            ^
//file descriptor---'       buffer--'            '-- num. bytes to write

4 Opening Files

4.1 File descriptors

4.2 open()'ing a File Descriptor

int   open(const char *path, int oflag, ... /*mode_t mode*/ );
int fd = open("path/to/file", O_RDONLY);
int fd = open("test.txt", O_WRONLY | O_TRUNC | O_CREAT, 0664);

1.open来自fcntl.h,系统级;fopen()来自stdlib.h,用户级
2.oflag

flag描述
O_RDONLYopen for reading only
O_WRONLYopen for writing only
O_RDWRopen for reading and writing
O_APPENDappend on each write
O_CREATcreate file if it does not exist
O_TRUNCtruncate size to 0

3.mode

mode描述
S_IRUSR 00400owner has read permission
S_IWUSR 00200owner has write permission
S_IXUSR 00100owner has execute permission
S_IRGRP 00040group has read permission
S_IWGRP 00020group has write permission
S_IXGRP 00010group has execute permission
S_IROTH 00004others have read permission
S_IWOTH 00002others have write permission
S_IXOTH 00001others have execute permission

4.3 User Masks for File Creation

1.umask用来处理用户权限

4.4 close()'ing a File

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值