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

本文详细介绍了使用C语言进行文件操作的基本方法,包括文件的打开、写入、定位和读取,并通过示例展示了如何实现文件的复制功能。
#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;
}

 

转载于:https://www.cnblogs.com/d442130165/p/5222478.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值