truncate: do not die when a file doesn't exist and no-create flag is on

Additionally, open(2) failures do not make the program die immediately.
This makes the behavior of the program match coreutils more closely.

function                                             old     new   delta
truncate_main                                        161     221     +60

Signed-off-by: Ari Sundholm <ari@tuxera.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
This commit is contained in:
Ari Sundholm 2015-05-25 15:16:11 +02:00 committed by Denys Vlasenko
parent 7f4a49a96c
commit fc3e40ee81

View File

@ -64,12 +64,22 @@ int truncate_main(int argc UNUSED_PARAM, char **argv)
argv += optind;
while (*argv) {
int fd = xopen(*argv, flags);
int fd = open(*argv, flags);
if (fd < 0) {
if (errno != ENOENT || !(opts & OPT_NOCREATE)) {
bb_perror_msg("%s: open", *argv);
ret = EXIT_FAILURE;
}
/* else: ENOENT && OPT_NOCREATE:
* do not report error, exitcode is also 0.
*/
} else {
if (ftruncate(fd, size) == -1) {
bb_perror_msg("%s: ftruncate", *argv);
bb_perror_msg("%s: truncate", *argv);
ret = EXIT_FAILURE;
}
xclose(fd);
}
++argv;
}