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);
}
文章的脚注信息由WordPress的wp-posturl插件自动生成
 
                 微信扫一扫,打赏作者吧~
微信扫一扫,打赏作者吧~ 
	![[已解决]nc命令报错 close: Bad file descriptor](http://www.jyguagua.com/wp-content/themes/begin/timthumb.php?src=http://www.jyguagua.com/wp-content/uploads/2022/03/Snipaste_2022-03-18_20-16-48.png&w=280&h=210&zc=1)
![[整理]how to run flask with pyqt5](http://www.jyguagua.com/wp-content/themes/begin/timthumb.php?src=http://www.jyguagua.com/wp-content/uploads/2021/03/pyqt_flask.png&w=280&h=210&zc=1)
![[已解决]SecureCRT/SSH 连接Linux缓慢](http://www.jyguagua.com/wp-content/themes/begin/timthumb.php?src=http://www.jyguagua.com/wp-content/uploads/2020/07/ssh_slow.jpg&w=280&h=210&zc=1)
![[转载]Linux的tickless设置](http://www.jyguagua.com/wp-content/themes/begin/timthumb.php?src=http://www.litrin.net/wp-content/uploads/2018/11/kernel_menuconfig_tickless-1.png&w=280&h=210&zc=1)
