Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Tip: Newline stripper
The system$ command is a useful one: it lets you use any Haiku command that you can issue in terminal and returns the output into a string variable. Haiku is quite robust about these variables: once I accidentally requested a megabyte of data to be fed into a$ and yab didn't even blink.

But have you noticed that when you issue a command in terminal, it gives you the result and then opens up a new prompt for you? That is because almost every bash command is terminated by a newline character. This is an invisible code that tells the system "I am finished, you can start a new command prompt now"

So if you issue the command

tempdir$ = system$("finddir B_COMMON_TEMP_DIRECTORY")

You may think that the result is

But it is not. It is


Sometimes this will not matter. But sometimes it does. Suppose you now want to specify your temporary file. you use basic string concatenation, like this

tempfile$ = tempdir$ + "/my_temp_file"

the result you want is


but what you get is


How is your program supposed to make sense of that?

Luckily, getting rid of that pesky newline is very easy. There are probably other ways, but I use this:

tempdir$ = system$("finddir B_COMMON_TEMP_DIRECTORY")
tempdir$ = left$(tempdir$, len(tempdir$)-1) //strip off trailing newline

We take the result of the system$ command, then take the part to the left of the newline character and feed it back into the variable.

You could combine these lines into one long command, but code readability would be bad.

But wait! What if the system$ command you are using is one of those rare ones that do not end their result with a newline? No problem.

tempdir$ = system$("finddir B_COMMON_TEMP_DIRECTORY")
if instr(tempdir$, "\n", len(tempdir$)) <> 0 then
    tempdir$ = left$(tempdir$, len(tempdir$)-1) //strip off trailing newline

Forum Jump:

Users browsing this thread: 1 Guest(s)
Free Web Hosting