zoukankan      html  css  js  c++  java
  • linux I/O函数使用

    一、lseek

      lseek函数的作用是用来重新定位文件读写的位移。

      头文件以及函数声明

    #include <sys/types.h>
    #include <unistd.h>
    off_t lseek(int fd, off_t offset, int whence);

      lseek()函数会重新定位被打开文件的位移量,根据参数offset以及whence的组合来决定:

      SEEK_SET:
        从文件头部开始偏移offset个字节。
      SEEK_CUR:
        从文件当前读写的指针位置开始,增加offset个字节的偏移量。
      SEEK_END:
        文件偏移量设置为文件的大小加上偏移量字节。

    例程:

    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <stdlib.h>
    #include <stdio.h>
    
    #define BUFFER_SIZE 1024
    #define SRC_FILE_NAME "src_file"
    #define DEST_FILE_NAME "dest_file"
    //根据传入的参数来设置offset
    #define OFFSET (atoi(args[1])) 
    
    int main(int argc, char*args[]) {
        int src_file, dest_file;
        unsigned char buff[BUFFER_SIZE];
        int real_read_len, off_set;
        if (argc != 2) {
            fprintf(stderr, "Usage: %s offset
    ", args[0]);
            exit(-1);
        }
        src_file = open(SRC_FILE_NAME, O_RDONLY);
        dest_file = open(DEST_FILE_NAME, O_WRONLY | O_CREAT, S_IREAD | S_IWRITE );//owner权限:rw
        if (src_file < 0 || dest_file < 0) {
            fprintf(stderr, "Open file error!
    ");
            exit(1);
        }
        off_set = lseek(src_file, -OFFSET, SEEK_END);//注意,这里对offset取了相反数
        printf("lseek() reposisiton the file offset of src_file: %d
    ", off_set);
        while((real_read_len = read(src_file, buff, sizeof(buff))) > 0) {
            write(dest_file, buff, real_read_len);
        }
        close(dest_file);
        close(src_file);
        return 0;
    }
    --------------------- 
    作者:Sino_Crazy_Snail 
    来源:CSDN 
    原文:https://blog.csdn.net/Sino_Crazy_Snail/article/details/80777316 
    版权声明:本文为博主原创文章,转载请附上博文链接!

    二、fflush

    fflush()函数是用来刷新输出(stdout)缓存的。对于输入(stdin),它是没有定义的,
    Linux程序设计中也还是有一种用来清空stdin中的方法,直接调用如下的函数:setbuf(stdin, NULL);
  • 相关阅读:
    Appium+python自动化13-native和webview切换【转载】
    Appium+python自动化12-appium元素定位【转载】
    Appium+python自动化11-adb必知必会的几个指令【转载】
    Appium+python自动化10-AVD 模拟器【转载】
    Appium+python自动化9-SDK Manager【转载】
    Appium+python自动化8-Appium Python API【转载】
    Appium+python自动化7-输入中文【转载】
    Appium+python自动化6-Remote远程控制【转载】
    Appium+python自动化5-Appium Inspector【转载】
    Centos-内核核心组成
  • 原文地址:https://www.cnblogs.com/jly594761082/p/10430327.html
Copyright © 2011-2022 走看看