linux中的系统函数库,Linux文件编程(系统函数+库函数) | 勤奋的小青蛙

Linux下的文件编程,大概我写两个程序,都是拷贝的程序,但是一个采用Linux系统函数,一个采用Linux库函数.

采用Linux系统函数的代码:

#include

#include

#include

#include

#include

#include

void copy_file(char *sourcename, char *destname)

{

char *buf[255] = {0};

ssize_t count = 0;

size_t n, d = 0;

int fd, fd_1;

fd = open(sourcename, O_RDWR);

fd_1 = open(destname, O_CREAT | O_RDWR);

if (fd < 0) {

printf("open file %s open error\n", sourcename);

exit(EXIT_FAILURE);

}

if (fd_1 < 0) {

printf("open file %s open error\n", destname);

exit(EXIT_FAILURE);

}

count = lseek(fd, 0, SEEK_END);

lseek(fd, 0, SEEK_SET);

n = read(fd, buf, count);

buf[n] = '\0';

printf("Read content is:\n%s \n", buf);

d = write(fd_1, buf, n);

printf("write %d bytes.\n", d);

close(fd_1);

close(fd);

}

int main(int argc, char *argv[])

{

if (argc < 3) {

printf("Usage:./cp sourcefile destfile\n");

exit(EXIT_FAILURE);

}

copy_file(argv[1], argv[2]);

exit(EXIT_SUCCESS);

}

采用C语言库函数的代码:

#include

#include

#include

#include

#define BUFFER_SIZE 255

void copy_file(char *src, char *dest)

{

FILE *openfile;

FILE *writefile;

size_t s = 0, d = 0, file_len = 0;

char *buf[255];

openfile = fopen(src, "rb");

writefile = fopen(dest, "wb");

fseek(openfile, 0, SEEK_END);

file_len = ftell(openfile);

fseek(openfile, 0, SEEK_SET);

while (!feof(openfile)) {

fread(buf, BUFFER_SIZE, 1, openfile);

if (BUFFER_SIZE >= file_len) {

fwrite(buf, BUFFER_SIZE, 1, writefile);

} else {

fwrite(buf, BUFFER_SIZE, 1, writefile);

file_len = file_len - BUFFER_SIZE;

}

bzero(buf, BUFFER_SIZE);

}

fclose(openfile);

fclose(writefile);

}

int main(int argc, char *argv[])

{

if (argc < 3) {

printf("Usage:\n./cp srcfile destfile\n");

exit(EXIT_FAILURE);

}

copy_file(argv[1], argv[2]);

exit(EXIT_SUCCESS);

}

文章的脚注信息由WordPress的wp-posturl插件自动生成

|2|left

打赏

1b6439c6a040252321edad911c85491b.png微信扫一扫,打赏作者吧~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值