【linux上机实验】实验八 Linux编程实验

发布时间 2023-12-05 11:31:30作者: Cloudservice

1.使用系统调用对文件进行操作。

编写一个程序,把一个文件的内容复制到另一个文件上,即实现简单的copy功能。要求:只用open(),read(),write(),close()系统调用,程序要求带参数运行,第一个参数是源文件,第二个参数是目标文件。

步骤一:创建file_copy.c文件

vi file_copy.c

步骤二:将下列代码复制进步骤一创建的文件中并保存

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

#define BUF_SIZE 1024

int main(int argc, char *argv[]) {
	if (argc != 3) {
		fprintf(stderr, "Usage: %s source_file target_file\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	int source_fd, target_fd;
	ssize_t bytes_read, bytes_written;
	char buffer[BUF_SIZE];

	source_fd = open(argv[1], O_RDONLY);
	if (source_fd == -1) {
		perror("open");
		exit(EXIT_FAILURE);
	}

	target_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
	if (target_fd == -1) {
		perror("open");
		close(source_fd);
		exit(EXIT_FAILURE);
	}

	while ((bytes_read = read(source_fd, buffer, BUF_SIZE)) > 0) {
		bytes_written = write(target_fd, buffer, bytes_read);
		if (bytes_written != bytes_read) {
			perror("write");
			close(source_fd);
			close(target_fd);
			exit(EXIT_FAILURE);
		}
	}

	if (bytes_read == -1) {
		perror("read");
		close(source_fd);
		close(target_fd);
		exit(EXIT_FAILURE);
	}

	if (close(source_fd) == -1) {
		perror("close");
		exit(EXIT_FAILURE);
	}

	if (close(target_fd) == -1) {
		perror("close");
		exit(EXIT_FAILURE);
	}

	return 0;
}

步骤三:使用以下命令编译生成可执行文件:

gcc file_copy.c -o file_copy

步骤四:创建源文件

vi source_file

里面的内容自行写
image

步骤五:使用以下命令来运行程序进行文件内容的复制:

./file_copy source_file target_file   (这个名字target_file可以随便改,这是目标文件)