您的位置:首页 > 编程语言

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

2016-02-27 10:54 429 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: