【发布时间】:2023-03-13 02:15:01
【问题描述】:
对于与 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中。
【问题讨论】:
-
仅供参考,您可以作弊并做
system("cat file1 file2 > file3");。或者只是从 linux shell 中完成,而不是编写 C 程序。 -
注意:
read()可以返回-1。处理它! -
@Gillespie 我很乐意这样做,但不幸的是,他们想要一个可以每天为不知道如何运行终端的人执行多次的程序
-
请始终尝试正确缩进您的代码,这样更容易跟踪和查找错误。
-
@Graeme 很抱歉,感谢 John Kugelman 为我正确缩进