[国嵌攻略][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!
");
    }
    
    //写入文件
    char wbuf[10] = "12345";
    
    write(fd, wbuf, 5);
    
    //定位文件
    lseek(fd, 0, SEEK_SET);
    
    //读取文件
    char rbuf[10];
    
    read(fd, rbuf, 5);
    rbuf[5] = '';
    
    //打印内容
    printf("Read buffer is %s
", 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:
	./copy <source file> <distance file>
");
        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;
}
原文地址:https://www.cnblogs.com/d442130165/p/5222478.html