[国嵌攻略][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 @ 2016-02-27 10:54  盛夏夜  阅读(365)  评论(0编辑  收藏  举报