文件I/O-lseek-ioctl

lseek文件偏移量

  • lseek()不适用于所有类型的文件,不允许应用于lseek()应用于管道、FIFO、socket或者终端

文件空洞

/*拷贝多份文件*/
#include <stdio.h>
#include <fcntl.h>      // open
#include <string.h>
#include <stdlib.h>     // exit
#include <unistd.h>     // read

#define NUM 3
#define LEN 10

int main(void) {
    int fdRead = -1;
    int fdWrite = -1;
    char * readName = "./log.txt";
    const char writeName[10] = "./copy";
    off_t offset = -1;
    ssize_t size = -1;
    char buf[LEN] = {0};
    char * ptr = NULL;
    char lastName[5] = {0};
    char firstName[20] = {0};

    // 打开文件
    fdRead = open(readName, O_RDONLY);
    if (fdRead == -1) {
        perror("error open:");
        exit(EXIT_FAILURE);
    }
    // 循环拷贝
    printf("copy");
    for (int i = 0; i < NUM; i++) {
        // 重新设定偏移量
        offset = lseek(fdRead, 0, SEEK_SET);    
        // 自定义文件名
        strcpy(firstName, writeName);
        sprintf(lastName, "_%d", i);
        strcat(firstName, lastName);  
        strcat(firstName, ".txt");
        printf("create file:%s\n", firstName);
        // 打开创建copy文件
        fdWrite = open(firstName, O_WRONLY | O_CREAT);
        do {
            size = read(fdRead, buf, LEN);
            ptr = buf;
            if (size > 0) {
                printf("read %ld bytes:\n", size);
                write(fdWrite, ptr, size);

            } else {
                printf("reach the end of file.\n");
            }
        } while (size > 0);
        close(fdWrite);
    }
    close(fdRead);
    return 0;
}

通用IO模型以外的系统调用操作:ioctl()

posted @ 2022-04-30 13:26  steve的miao  阅读(35)  评论(0编辑  收藏  举报