Linux文件编程(系统函数+库函数)

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: Linux文件编程(系统函数+库函数)

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

采用Linux系统函数的代码:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#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);
}

 

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: Linux文件编程(系统函数+库函数)

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



|2|left
打赏

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: