IO-使用文件IO write和read函数 实现图片的copy

主函数

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

int main(int argc, const char *argv[])
{
	int fd_r = open(argv[1],O_RDONLY);
	if (fd_r < 0)
	{
		perror("open_fd");
		return -1;
	}
	printf("open success\n");
	
	umask(0);
	int fd_w = open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,0664);
	if (fd_w < 0)
	{
		perror("open_fd1");
		return -1;
	}

	char medi;
	while (1)
	{
		int res = read(fd_r,&medi,1);
		if (res < 1)
		{
			perror("read");
			return -1;
		}
		int res1 = write(fd_w,&medi,1);
		if (res1 < 0)
		{
			perror("write");
			return -1;
		}
	}

	if(close(fd_r) < 0)
	{
		perror("read_close");
		return -1;
	}

	if(close(fd_w) < 0)
	{
		perror("write_close");
		return -1;
	}

	printf("close success\n");
	return 0;
}

 测试

root@VM-12-9-ubuntu:zouye# a any.jpg test.jpg
open success
read: Success

原图片 

copy成功的图片 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
下面是一个利用标准文件IO编程实现普通文件拷贝的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "Usage: %s <source_file> <destination_file>\n", argv[0]); exit(EXIT_FAILURE); } // 打开源文件 int src_fd = open(argv[1], O_RDONLY); if (src_fd == -1) { perror("open"); exit(EXIT_FAILURE); } // 检查源文件是否是普通文件 struct stat src_stat; if (fstat(src_fd, &src_stat) == -1) { perror("fstat"); exit(EXIT_FAILURE); } if (!S_ISREG(src_stat.st_mode)) { fprintf(stderr, "%s is not a regular file\n", argv[1]); exit(EXIT_FAILURE); } // 创建目标文件 int dst_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644); if (dst_fd == -1) { perror("open"); exit(EXIT_FAILURE); } // 拷贝数据 char buffer[4096]; ssize_t nread; while ((nread = read(src_fd, buffer, sizeof(buffer))) > 0) { ssize_t nwritten = write(dst_fd, buffer, nread); if (nwritten == -1) { perror("write"); exit(EXIT_FAILURE); } } if (nread == -1) { perror("read"); exit(EXIT_FAILURE); } // 关闭文件 if (close(src_fd) == -1) { perror("close"); exit(EXIT_FAILURE); } if (close(dst_fd) == -1) { perror("close"); exit(EXIT_FAILURE); } return 0; } ``` 代码中首先检查了命令行参数个数,如果不足两个则输出用法信息并退出程序。然后通过 `open` 函数打开源文件,并利用 `fstat` 函数检查源文件是否是普通文件。如果不是普通文件则输出错误信息并退出程序。接着通过 `open` 函数创建目标文件,并利用 `read` 和 `write` 函数进行数据拷贝。最后关闭文件并返回。 需要注意的是,代码中使用了系统调用函数,因此需要在编译时链接相应的库,例如: ``` gcc -o copy_file copy_file.c ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Coding Peasant

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值