gpt4 book ai didi

c - 如何仅使用 linux 系统调用将两个文件合并为第三个文件?

转载 作者:太空宇宙 更新时间:2023-11-04 07:44:07 32 4
gpt4 key购买 nike

当涉及到与 C 代码交互的 Linux 系统调用时,我完全是个菜鸟。到目前为止,我已经能够打开一个文件,但仅此而已。我不确定如何获取第二个文件并将这两个文件合并为第三个文件。

例如,我有一个包含简单文本内容的 file1 和一个包含相同文本内容的 file2,我如何仅使用 linux 系统调用将这两个内容合并到 file3 中?我知道我必须使用 lseek 来更改指针,但不确定如何使用它。

这是我目前所拥有的......我为稀缺表示歉意:

我相信这会获取 file1 并将其复制到 file2

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

int copyfile(const char *file1, const char *file2)
{
int infile, outfile;
ssize_t nread;
char buffer[BUFSIZE]

if( (infile = open(file1, O_RDONLY)) == -1 )
return (-1);

if( (infile = open(file2, O_WRONLY|O_CREATE|O_TRUNC, PERM)) == -1 )
{
close (infile);
return (-2);
}

/*read from file1 BUFSIZE chars at a time*/
while ( nread = read (infile, buffer, BUFSIZE) )
{
// write buffer to output file
if (write (outfile, buffer, nread) < nread)
{
close(infile);
close(outfile);
return (-3);
}
}
close (infile)
close (outfile)

if (nread == -1)
return (-4);
else
return(0);
}

文件将在终端中输入:

lastnameCat.c file1 file2 file3

这样 file1 和 file2 被加在一起,并发送到 file3。

最佳答案

您可以为此使用copy_file_range 系统调用。它比使用 readwrite 调用更快,因为复制是在内核内部完成的。来自man页:

The copy_file_range() system call performs an in-kernel copy between two file descriptors without the additional cost of transferring data from the kernel to user space and then back into the kernel.

这是一个使用它的例子:

#define _GNU_SOURCE
#include <fcntl.h>
#include <limits.h>
#include <stdint.h>
#include <unistd.h>

int do_copy(int infd, int outfd)
{
ssize_t bytes = 0;
do
{
bytes = copy_file_range(infd, NULL, outfd, NULL, SSIZE_MAX, 0);
}
while(SSIZE_MAX == bytes);

return bytes;
}

int concatenate(const char *inpath1, const char *inpath2, const char *outpath)
{
int infd1 = -1;
int infd2 = -1;
int outfd = -1;
int res = -1;

infd1 = open(inpath1, O_RDONLY);
if(infd1 < 0)
goto close;

infd2 = open(inpath2, O_RDONLY);
if(infd2 < 0)
goto close;

outfd = open(outpath, O_WRONLY|O_CREAT|O_TRUNC);
if(outfd < 0)
goto close;

res = do_copy(infd1, outfd);
if(res < 0)
goto close;

res = do_copy(infd2, outfd);

close:
if(infd1 >= 0)
close(infd1);

if(infd2 >= 0)
close(infd2);

if(outfd >= 0)
close(outfd);

return res;
}

do_copy 中的循环允许非常大的文件,这可能会超过单次调用中可能的最大复制量。

关于c - 如何仅使用 linux 系统调用将两个文件合并为第三个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58261963/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com