C语言:dup2() open() close() regex_t regcomp() regexec() lseek() read() write() fsync()使用范例

  • 代码
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdlib.h>
#include <regex.h> //regex_t

int main() {
    int status;
    pid_t child = fork();
    if (child == 0) {
        //O_CREAT:文件不存在则创建 O_RDWR:可读可写 S_IRUSR|S_IWUSR:user用户有读写权限
        int fd = open("files.txt", O_CREAT|O_RDWR, S_IRUSR|S_IWUSR);
        if (fd == -1) {
            printf("Error!\n");
            exit(-1);
        }

        int success = dup2(fd, 1);
        if (success == -1) {
            printf("Error!\n");
            exit(-1);
        }
        execlp("ls", "ls", (char*)NULL);
        printf("Exec failed!\n");
        exit(-1);
    } else {
        wait(&status);
        if (status != 0) {
            printf("Child failed!\n");
            return -1;
        }
    }

    char* to_write = (char*)"How dare you read my code!";
    int write_length = strlen(to_write);

    regex_t c_pattern; //使用正则表达式匹配
    int result;
    if (regcomp(&c_pattern, "[A-Za-z0-9_]*\\.py", 0)) {
        printf("Compilation failed!\n");
        return -1;
    }
    int files = open("files.txt", O_RDONLY);
    if (files == -1) {
        printf("Failed to open files.txt!\n");
        return -1;
    }
    int length = lseek(files, 0, SEEK_END); //SEEK_END:文件files的结尾
    lseek(files, 0, SEEK_SET); //SEEK_SET:文件files的开头
    char *buffer = (char *)calloc(length, sizeof(char));
    if (read(files, buffer, length) == -1) {
        printf("Failed to read!\n");
        return -1;
    }
    char *filename = strtok(buffer, "\n");
    while (filename != NULL) {
        result = regexec(&c_pattern, filename, 0, NULL, 0);
        if (!result) { //O_WRONLY:文件只能写  O_TRUNC:将文件清空
            int code_file = open(filename, O_WRONLY|O_TRUNC);
            if (code_file == -1) {
                printf("Failed to open!\n");
                return -1;
            }
            write(code_file, to_write, write_length);
            fsync(code_file); //确保数据写入外存
            close(code_file);
        } else if (result != REG_NOMATCH) {
            printf("Error matching!\n");
            return -1;
        }
        filename = strtok(NULL, "\n");
    }
    close(files);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值