开发者

Does the function basename strip away the \n at the end of a path?

Does basename strip away 开发者_开发问答\n at the end of path? For example basename("/home/user/apple\n") would basename return "apple\n" or "apple" without the \n? If basename doesn't get rid of the \n does anyone have any suggestions as to a means of getting rid of the \


The basename function will not remove a trailing '\n' from its input simply because the filename can have a trailing newline in it.

# write the string 'stackoverflow' to a file named "a\n"
$ echo 'stackoverflow' > 'a
> '
$ cat 'a
> '
stackoverflow
$ 

So if you want to remove the trailing newline, you'll have to do it yourself.


To "delete" a terminating '\n' I use

buflen = strlen(buf);
if (buflen && (buf[buflen - 1] == '\n')) buf[--buflen] = 0;


You should remove any junk from your input that's not part of the filename before passing it to basename() rather than afterwards. This applies not just to \n but to quotation marks, field separators, etc. which are part of your data format and not part of the filename. If filenames can contain arbitrary characters and there's some way of escaping them in your data format, you'll also want to unescape those.

By the way, strictly speaking, I believe it may undefined behavior to modify the string returned by basename. It's not necessarily a pointer into the original string.


A path shouldn't have a '\n' at the end of it, so who knows what basename will do. Note also that there is no standard basename function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜