[英]Copying file fails, EBADF on closing output file descriptor
So I was following a little outdated book (2010) and I'm trying to copy a file with Linux system calls. 因此,我正在关注一本过时的书(2010年),并尝试使用Linux系统调用复制文件。 This is what i have: 这就是我所拥有的:
NOTE: Ignore the tlpi_hdr.h
and error_functions.h
, they define errExit()
and fatal()
and some otheres, they just print the error and exit. 注意:忽略tlpi_hdr.h
和error_functions.h
,它们定义了errExit()
和fatal()
等,它们只是打印错误并退出。
#include <stdio.h>
#include <fcntl.h>
#include "lib/tlpi_hdr.h"
#include "lib/error_functions.h"
#ifndef BUF_SIZE
#define BUF_SIZE 1024
#endif
int main(int argc, char *argv[])
{
int inputFd, outputFd, openFlags;
mode_t filePerms;
ssize_t numRead;
char buf[BUF_SIZE];
if (argc != 3 || strcmp(argv[1], "--help") == 0) {
usageErr("%s old-file new-file\n", argv[0]);
}
inputFd = open(argv[1], O_RDONLY);
if (inputFd == -1) {
errExit("Opening file %s", argv[1]);
}
openFlags = O_CREAT | O_WRONLY | O_TRUNC;
filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
outputFd = open(argv[2], openFlags, filePerms);
if (outputFd == -1) {
errExit("Opening file for writing %s", argv[1]);
}
while ((numRead = read(inputFd, buf, BUF_SIZE)) > 0) {
if (write(outputFd, buf, numRead) != numRead))
fatal("I/O Error");
if (numRead == -1)
fatal("Reading error");
}
if (close(outputFd == -1))
errExit("close input");
if (close(inputFd == -1))
errExit("close output");
return EXIT_SUCCESS;
}
I'm failing on closing of the output file descriptor with EBADF Bad file descriptor
: 我无法使用EBADF Bad file descriptor
关闭EBADF Bad file descriptor
关闭输出EBADF Bad file descriptor
:
thinkpad :: ~/.tlpi % ./cp.o a b
ERROR [EBADF Bad file descriptor] close output
The file copies fine tho: 该文件可以复制到:
thinkpad :: ~/.tlpi % sha1sum a
40a925a93e149ac53d2630cde8adeb63b8134b29 a
thinkpad :: ~/.tlpi % sha1sum b
40a925a93e149ac53d2630cde8adeb63b8134b29 b
thinkpad :: ~/.tlpi %
Why? 为什么?
Let's take a closer look at your close
call: 让我们仔细看看您的close
通话:
close(outputFd == -1)
Here you are comparing outputFd
to the value -1
. 在这里,您将outputFd
与值-1
进行比较。 The result of that is a boolean value, which in C will be either 0
or 1
. 结果是一个布尔值,在C中为0
或1
。 This happens to be either standard input or standard output, depending on the result. 根据结果,这恰好是标准输入或标准输出。 Not a file you descriptor you should close. 不是您描述符中应该关闭的文件。
My guess is that you meant 我的猜测是你的意思是
if (close(outputFd) == -1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.