tags:

views:

49

answers:

4

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 \

A: 

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.

Oli Charlesworth
I'm readying from a file and some of the contents have path names with a \n at the end of it. I need a way to strip the \n away
KunGor
Many systems allow a \n in filenames.
nos
@KunGor: Then you need a first stage that removes them! Something as simple as `char *p = str; while (*p != '\0') { if (*p == '\n') { *p = '\0'; } p++; }`, perhaps.
Oli Charlesworth
@nos: By \n, are we talking about the character `'\'` followed by the character `'n'`, or are we talking about `\n`?
Oli Charlesworth
@Oli Charlesworth a newline character. (although a \ followed by a n is nothing special either on many systems)
nos
@nos: I wasn't aware that `'\n'` could possibly be a valid filename character. How could this possibly be a good idea?
Oli Charlesworth
+1  A: 

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

buflen = strlen(buf);
if (buflen && (buf[buflen - 1] == '\n')) buf[--buflen] = 0;
pmg
John Marshall
+2  A: 

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.

codaddict
+1  A: 

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.

R..