系统函数

系统函数_第1张图片

实现一个cat功能

#include 
  2 #include <unistd.h>
  3 #include <sys/stat.h>
  4 #include <sys/types.h>
  5 #include <fcntl.h>
  6 
  7 
  8 int main(int argc, char *argv[])
  9 {
 10     if (argc != 2)
 11     {
 12         printf("./a.out filename\n");
 13         return -1;
 14     }
 15     int fd = open(argv[1], O_RDONLY);
 16     // 读  输出到屏幕
 17     char buf[256];
 18     int ret =  read(fd, buf, sizeof(buf));
 19 
 20     write(STDOUT_FILENO, buf, ret);
 21                                                                                                                                                                         
 22 
 23     close(fd);
 24     printf("Hello world\n");
 25     return 0;
 26 }
需求:打开一个文件,写入内容:helloworld,然后读取一下该文件的内容,输出到屏幕
 #include 
  2 #include <unistd.h>
  3 #include <sys/stat.h>
  4 #include <sys/types.h>
  5 #include <fcntl.h>
  6 
  7 
  8 int main(int argc, char *argv[])
  9 {
 10     if (argc != 2)
 11     {
 12         printf("./a.out filename\n");
 13         return -1;
 14     }
 15     int fd = open(argv[1], O_RDWR | O_CREAT, 0666);
 16 
 17     write(fd, "helloworld", 11);
 18     char buf[256] = {0};
 19                                                                                                                                                                         
 20     lseek(fd, 0, SEEK_SET);
 21     int ret = read(fd, buf, sizeof(buf));
 22     // 文件读写位置已经到末尾了
 23     // 需要移动读写位置
 24     if (ret)
 25     {
 26         write(STDOUT_FILENO, buf, ret);
 27     }
 28 
 29     close(fd);
 30     return 0;
 31 }
计算文件大小
 1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include <sys/stat.h>
  4 #include <sys/types.h>
  5 #include <fcntl.h>
  6 
  7 
  8 
  9 int main(int argc, char *argv[])
 10 {
 11     if (argc != 2)
 12     {
 13         printf("./a.out filename \n");
 14         return -1;                                                                                                                                                      
 15     }
 16     // 1.open
 17     int fd = open(argv[1], O_RDONLY);
 18     // 2.lseek  得到返回值
 19     int ret = lseek(fd, 0, SEEK_END);
 20     printf("file size is %d \n", ret);
 21     // close
 22     return 0;
 23 }
扩展文件
1 #include <stdio.h>
    2 #include <unistd.h>
    3 #include <sys/stat.h>
    4 #include <sys/types.h>
    5 #include <fcntl.h>
    6 
    7 
    8 
    9 int main(int argc, char *argv[])
   10 {
   11     if (argc != 2)
   12     {
   13         printf("./a.out filename \n");
   14         return -1;
   15     }
   16     // 1.open
   17     int fd = open(argv[1], O_WRONLY | O_CREAT, 066);                                                                                                                  
   18     // 2.lseek  扩展文件19     int ret = lseek(fd, 256, SEEK_END);
   20     // 需要至少写一次,否则不能保存
   21     write(fd, "a", 1);
   22     // close
   23     close(fd);
   24     return 0;
   25 }

你可能感兴趣的:(系统函数,Linux系统编程)