0

I cannot figure this one out. When I remove let size = s.readInt64() from the following proc, the .exe seems to terminate before it reaches the end. It is declared but not used! Its gotta go!

proc load(fn: string): Alternating =
  var s = newFileStream(fn, fmRead)
  let size = s.readInt64() #WITHOUT THIS LINE THE .exe doesn't execute ExitTerminal()
  result = newSeq[(float, int)]()
  while not s.atEnd:
    let element = (s.readFloat64.float, s.readInt64.int)
    result.add(element)
  s.close()

Below is the entire program. The file type is .dat and I suppose it is binary. It is created in the program. I compiled with -d:release Nim version 0.18.0 and minGW compiler

import streams

type
  Alternating = seq[(float, int)]

proc store(fn: string, data: Alternating) =
  var s = newFileStream(fn, fmWrite)
  s.write(data.len)
  for x in data:
    s.write(x[0])
    s.write(x[1])
  s.close()

proc load(fn: string): Alternating =
  var s = newFileStream(fn, fmRead)
  let size = s.readInt64() #WITHOUT THIS LINE THE .exe doesn't execute ExitTerminal()
  result = newSeq[(float, int)]()
  while not s.atEnd:
    let element = (s.readFloat64.float, s.readInt64.int)
    result.add(element)
  s.close()


let data = @[(1.0, 1), (2.0, 2)]

store("tmp.dat", data)
let dataLoaded = load("tmp.dat")

echo dataLoaded


### EXIT PROCEDURE FROM TERMINAL PROGRAM

proc ExitTerminal: bool =
  echo "Exit Application"
  echo "(y/n)"
  while true:
    case readline(stdin)
    of "y", "Y", "yes", "Yes": return true
    of "n", "N", "no", "No": return false
    else: echo "Please be clear: yes or no"


if ExitTerminal() == false: discard ExitTerminal()
Joshua Fenner
  • 355
  • 1
  • 7

1 Answers1

3

It is hard to tell because we know nothing about the file format you're reading. But generally you can't remove s.readInt64() just because it is unused, because apart from reading this proc advances your stream cursor. If you need to ignore the value just use discard s.readInt64() # Ignore size

uran
  • 1,346
  • 10
  • 14
  • Binary. The file is created inside the program `tmp.dat`; I'm not really sure about advancing the stream cursor. I don't know what or why that would be. Can you elaborate? Are there any other cases where I would have to declare but not use a variable in order for the program to function properly? – Joshua Fenner Apr 12 '18 at 14:40
  • @JoshuaFenner, It's not the variable that can't be removed, it is the call to `readInt64` that can't be removed. Let's say your stream has the format `[size: 8bytes, a: 8bytes, b: 8bytes, size: 8bytes, a: 8bytes, b: 8bytes, ...]`. In order to read the first `a`, you have to read or skip the first `size`, in other words you have to advance your stream cursor by 8 bytes. And that's what all `read*` functions do, apart from actual reading. – uran Apr 13 '18 at 07:17
  • Awesome. Thank you. – Joshua Fenner Apr 13 '18 at 07:21