DosLib (dos_readdelimitedfile) strings and zeros

DosLib (dos_readdelimitedfile) strings and zeros

svucic
Advocate Advocate
749 Views
2 Replies
Message 1 of 3

DosLib (dos_readdelimitedfile) strings and zeros

svucic
Advocate
Advocate

Hello everyone,

 

I'm using dos_readdelimitedfile to read csv files. However, if I have a string like "00000240" the function reads it as 240.

 

Does anyone have an idea how to solve this problem?

 

Thank you!

0 Likes
750 Views
2 Replies
Replies (2)
Message 2 of 3

martti.halminen
Collaborator
Collaborator

 

The documentation of dos_readdelimitedfile doesn't show any way to control the type of the result.

 

Either you can add some non-numeric characters to those items you don't want to be handled as numbers, or do the reading and splitting by other means, where you control the conversions, if any.

 

One way to do this:

 

(defun read-csv-file (path separator / f1 line result)
  ;; reads a csv file (separator as a one-character string) into a list, each line as a list
  (setq f1 (open path "r"))
  (while (setq line (read-line f1))
    (setq result
          (cons
           (split-at separator line)
           result)))
  (close f1)
  (reverse result))

(defun split-at (char str / pos  )
  ;; Splits string to a list of strings at each char occurrence.
  ;; Separators omitted from the result.
  ;; char as an one-character string.
  (setq pos (vl-string-position (ascii char) str))
  (cond
    ((or (null char) (null str)) nil)
    ((null pos) (list str))
    (T (cons (substr str 1 pos)
             (split-at char (substr str (+ 2 pos)))))))

-- 

Message 3 of 3

roland.r71
Collaborator
Collaborator

Did some extensive testing, but there is no direct way to solve the problem. Even using quotes doesn't help. The double quotes ('') get omitted, but stil the leading zero's get removed. There's no esc. char or anything to get the function to import it as a string.

 

Any possible solution depends on the source for the CSV file. If it can be written using single quotes for example, you can import the data (incl. the quotes), cut the quotes from the string and you have the complete number. ('0001','0002','000240' etc. )

 

Another way is to write your own csv file parser. Like marti.halmen's

Which is not as hard as it may look and gives you more control over the data.

 

If its supposed to be a string of fixed length, you could also simply add the missing number of 0's at the front of the string.

 

(setq a (rtos 240))

(while (< (strlen a) 8)
   (setq a (strcat "0" a))
)
"00000240"