Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Tip: Newline stripper
#1
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

Code:
tempdir$ = system$("finddir B_COMMON_TEMP_DIRECTORY")

You may think that the result is
/boot/system/cache/tmp

But it is not. It is

/boot/system/cache/tmp<newline>

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

Code:
tempfile$ = tempdir$ + "/my_temp_file"

the result you want is

/boot/system/cache/tmp/my_temp_file

but what you get is

/boot/system/cache/tmp
/my_temp_file


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:

Code:
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.

Code:
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
endif
Reply


Messages In This Thread
Tip: Newline stripper - by clasqm - 03-18-2016, 07:53 PM

Forum Jump:


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