[国嵌攻略][074][系统调用方式文件编程]

复制代码
#include <stdio.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

void main(){
    //打开文件
    int fd;
    
    fd = open("./test.c", O_RDWR | O_CREAT, 0777);
    if(fd < 0 ){
        printf("File not exist!\n");
    }
    
    //写入文件
    char wbuf[10] = "12345";
    
    write(fd, wbuf, 5);
    
    //定位文件
    lseek(fd, 0, SEEK_SET);
    
    //读取文件
    char rbuf[10];
    
    read(fd, rbuf, 5);
    rbuf[5] = '\0';
    
    //打印内容
    printf("Read buffer is %s\n", rbuf);
    
    close(fd);
}
复制代码

 

复制文件程序

复制代码
#include <stdio.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char **argv){
    //参数检查
    if(argc != 3){
        printf("Usage:\n\t./copy <source file> <distance file>\n");
        return -1;
    }
    
    //打开文件
    int srcFd, dstFd;
    
    srcFd = open(argv[1], O_RDONLY);
    dstFd = open(argv[2], O_WRONLY | O_CREAT, 0777);
    
    //复制文件
    int count;
    char buffer[512];
    
    count = read(srcFd, buffer, 512);
    while(count > 0){
        write(dstFd, buffer, count);
        
        count = read(srcFd, buffer, 512);
    }
    
    //关闭文件
    close(srcFd);
    close(dstFd);
    
    return 0;
}
复制代码

 

posted @   盛夏夜  阅读(365)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示