Skip to content

Commit

Permalink
Userland: "touch" can now handle multiple paths as arguments
Browse files Browse the repository at this point in the history
You can now do:
  touch a.txt b.txt c.txt d.txt

Also now you can't do:
  touch --test  # This created a "./--test" file

Also adds ArgsParser to the mix to better handle arguments :)
  • Loading branch information
zlotny authored and awesomekling committed May 1, 2020
1 parent 8551c10 commit 15aedc6
Showing 1 changed file with 23 additions and 18 deletions.
41 changes: 23 additions & 18 deletions Userland/touch.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <LibCore/ArgsParser.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
Expand Down Expand Up @@ -55,24 +56,28 @@ int main(int argc, char** argv)
return 1;
}

if (argc != 2) {
fprintf(stderr, "usage: touch <path>\n");
return 1;
}
if (file_exists(argv[1])) {
int rc = utime(argv[1], nullptr);
if (rc < 0)
perror("utime");
} else {
int fd = open(argv[1], O_CREAT, 0100644);
if (fd < 0) {
perror("open");
return 1;
}
int rc = close(fd);
if (rc < 0) {
perror("close");
return 1;
Vector<const char*> paths;

Core::ArgsParser args_parser;
args_parser.add_positional_argument(paths, "Files to touch", "path", Core::ArgsParser::Required::Yes);
args_parser.parse(argc, argv);

for (auto path : paths) {
if (file_exists(path)) {
int rc = utime(path, nullptr);
if (rc < 0)
perror("utime");
} else {
int fd = open(path, O_CREAT, 0100644);
if (fd < 0) {
perror("open");
return 1;
}
int rc = close(fd);
if (rc < 0) {
perror("close");
return 1;
}
}
}
return 0;
Expand Down

0 comments on commit 15aedc6

Please sign in to comment.