dirname: add command and libc function
This commit is contained in:
parent
558a273828
commit
6a0845d54a
22
apps/dirname.c
Normal file
22
apps/dirname.c
Normal file
@ -0,0 +1,22 @@
|
||||
/* vim: tabstop=4 shiftwidth=4 noexpandtab
|
||||
* This file is part of ToaruOS and is released under the terms
|
||||
* of the NCSA / University of Illinois License - see LICENSE.md
|
||||
* Copyright (C) 2018 K. Lange
|
||||
*
|
||||
* dirname - print directory name from path string
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <libgen.h>
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
if (argc < 2) {
|
||||
fprintf(stderr, "%s: expected argument\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
char * c = dirname(argv[1]);
|
||||
fprintf(stdout, "%s\n", c);
|
||||
return 0;
|
||||
}
|
||||
|
@ -4,7 +4,7 @@
|
||||
|
||||
_Begin_C_Header
|
||||
|
||||
//extern char * dirname(char * path);
|
||||
extern char * dirname(char * path);
|
||||
extern char * basename(char * path);
|
||||
|
||||
_End_C_Header
|
||||
|
48
libc/libgen/dirname.c
Normal file
48
libc/libgen/dirname.c
Normal file
@ -0,0 +1,48 @@
|
||||
#include <libgen.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
char * dirname(char * path) {
|
||||
int has_slash = 0;
|
||||
char * c = path;
|
||||
while (*c) {
|
||||
if (*c == '/') {
|
||||
has_slash = 1;
|
||||
}
|
||||
c++;
|
||||
}
|
||||
if (!has_slash) {
|
||||
return ".";
|
||||
}
|
||||
|
||||
c--;
|
||||
while (*c == '/') {
|
||||
*c = '\0';
|
||||
if (c == path) break;
|
||||
c--;
|
||||
}
|
||||
|
||||
if (c == path) {
|
||||
return "/";
|
||||
}
|
||||
|
||||
/* All trailing slashes are cleared out */
|
||||
while (*c != '/') {
|
||||
*c = '\0';
|
||||
if (c == path) break;
|
||||
c--;
|
||||
}
|
||||
|
||||
if (c == path) {
|
||||
if (*c == '/') return "/";
|
||||
return ".";
|
||||
}
|
||||
|
||||
while (*c == '/') {
|
||||
if (c == path) return "/";
|
||||
*c = '\0';
|
||||
c--;
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
Loading…
Reference in New Issue
Block a user