File I/O - Missing something simple [SOLVED]

New to FreeBASIC? Post your questions here.
Post Reply
Trinity
Posts: 214
Joined: Sep 16, 2017 17:07

File I/O - Missing something simple [SOLVED]

Post by Trinity »

To try to learn about file I/O I have managed to get FB to write the one record I want , but I can not get it to input again .
I have spent some hours trying to solve this problem but I can not get it to work so I would be glad if someone could point me to what is wrong with the code (code output all right but do not input into string) :

Code: Select all

screenres 800,600
Dim As String buffer,filename
Dim As Integer f

filename = "FreeBASIC\MyFiles\FileTest.mine"

' OUTPUT 
f = FreeFile
buffer = "1234567890"

Print "Opening output , FreeFile # ";f : Print 

Open filename For Binary Access Write As #f
If Err>0 Then Print "Error opening the file":End

Put #f, , buffer

Close

Sleep

' INPUT 
f = FreeFile
buffer = ""

Print "Opening input , FreeFile # ";f 

Open filename For Binary Access Read As #f
If Err>0 Then Print "Error opening the file":End

Get #f, , buffer

Close

If buffer = "" then print : Print : print " FILE INPUT ERROR !!!!" : Print  Else Print : print "Record = ";buffer

Sleep 

Print : Print "File name is : ";filename : Print "   Dir = " : Print CurDir : Print "Buffer = " ; buffer

Sleep
Last edited by Trinity on Sep 26, 2017 9:43, edited 2 times in total.
St_W
Posts: 1626
Joined: Feb 11, 2009 14:24
Location: Austria
Contact:

Re: File I/O - Missing something simple

Post by St_W »

In binary mode the data is directly written to the file without any metadata or any other additional information. For strings this means that the raw character data is written into the file. The important thing to consider is that the string-length is not stored in the file. This is no problem if you store only a single string in the file, as one can use the file size in that case, but does not allow restoring multiple strings written to a file. To do that one additionally has to store the length (or use fixed lengths).

Anyway, back to your example code. When reading data in binary mode there is no length information in the file, so the programmer has to specify it. This is done by providing a buffer filled with the number of characters one likes to be read from the file. As your buffer is a zero-length string nothing is read from the file. Typically a string filled with spaces or NULL-characters is used. e.g. to read the whole contents of the file into your string initialize the buffer before reading like this:

Code: Select all

buffer = space(lof(f))
This assigns a string filled with spaces to the buffer variable, that is as long as the file size.

Personally I always use binary mode and do serialization myself, if necessary. But for a beginner maybe another mode would be easier to use.
fxm
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: File I/O - Missing something simple

Post by fxm »

St_W wrote:When reading data in binary mode there is no length information in the file, so the programmer has to specify it. This is done by providing a buffer filled with the number of characters one likes to be read from the file. As your buffer is a zero-length string nothing is read from the file. Typically a string filled with spaces or NULL-characters is used. e.g. to read the whole contents of the file into your string initialize the buffer before reading like this:

Code: Select all

buffer = space(lof(f))
This assigns a string filled with spaces to the buffer variable, that is as long as the file size.
..... and therefore by sizing the buffer after opening the file in read-access mode:
Trinity
Posts: 214
Joined: Sep 16, 2017 17:07

Re: File I/O - Missing something simple

Post by Trinity »

St_W wrote: Personally I always use binary mode and do serialization myself, if necessary. But for a beginner maybe another mode would be easier to use.
Thank you very much for being so kind to explain and for taking your time doing so. Your explanation were quite clear and to the point.

My choosing the binary format were after consulting the manual as best I could. From what were presented in the manual then the random-access reading or writing of arbitrary sized data sounded as the best , which is features of Binary and Random file modes , and of those two modes then the Binary mode looked to me as better because it said that it could read and write to arbitrary locations in the disk file.
However I had no idea that there in binary mode is no (record) length information in the file , I might not have either read documentation proper enough or understood what I read (?) but I thought that I could just specify record number to read... Since that appear to not being so then I ought maybe at least switch to Random file mode for the time being. Dunno , I will have to ponder a lot more on it , but no matter which file "Open" system I go with then I am sure that this is going to be a lot of pain before I am able to fully use it and master it...

But thanks again :-)
fxm wrote:..... and therefore by sizing the buffer after opening the file in read-access mode:

As far as I understand it after consulting manual for the use of Space() and LOF() then your point is that one can only use the LOF Command (or Statement or whatever it is) on a file that is already open .

Thank you for specifying that :-)
dodicat
Posts: 7983
Joined: Jan 10, 2006 20:30
Location: Scotland

Re: File I/O - Missing something simple [SOLVED]

Post by dodicat »

For files I use binary for strings.
Like this:

Code: Select all

 


 #Include "file.bi"
Sub savefile(filename As String,text As String)
    Dim As long f = freefile
    If Open (filename For Binary Access Write As #f)=0 Then
        Put #f,,text
        Close
    Else
        Print "Unable to save " + filename
    End If
End Sub

Function loadfile(filename as string) as String
	If FileExists(filename)=0 Then Print filename;" not found":Sleep:exit function
   dim as long  f=freefile
    Open filename For Binary Access Read As #f
    Dim As String text
    If Lof(1) > 0 Then
      text = String(Lof(f), 0)
      Get #f, , text
    End If
    Close #f
    return text
end Function

dim as string s="Free" + chr(10)+"BASIC"

savefile("tempstring.txt",s)

dim as string g=loadfile("tempstring.txt")
print g
print
kill "tempstring.txt"
print iif( fileexists("tempstring.txt"),"delete manually","Gone.")
sleep


 
These methods are more or less straight from the help files.

Using the so called simpler method (non binary) is very easy to save a text string (put #n,...)
But to retrieve a text string it becomes messy.
The chr(10) is a problem.

From the help file under OPEN
(adjusted only slightly)

Code: Select all



Dim ff As UByte
Dim randomvar As Integer 
Dim name_str As String = "Free" + chr(10) + "BASIC"
Dim age_ubyte As UByte  = 13

ff = FreeFile


Open "testfile" For Output As #ff
Write #ff, Int(Rnd(0)*42),name_str,age_ubyte
Close #ff

randomvar=0
name_str=""
age_ubyte=0

Open "testfile" For Input As #ff
Input #ff, randomvar,name_str,age_ubyte
Close #ff

Print "Random Number was: ", randomvar
Print "Your name is: " + name_str
Print "Your age is: " + Str(age_ubyte)

'File outputted by this sample will look like this,
'minus the comment of course:
'23,"Your Name",19
sleep
kill "testfile"


 
fxm
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: File I/O - Missing something simple

Post by fxm »

Trinity wrote:..... one can only use the LOF Command (or Statement or whatever it is) on a file that is already open .
In fact, there is no runtime error if we call "Lof()" while none file is opened.
In that case, "Lof()" returns 0.
Trinity
Posts: 214
Joined: Sep 16, 2017 17:07

Re: File I/O - Missing something simple

Post by Trinity »

fxm wrote:In fact, there is no runtime error if we call "Lof()" while none file is opened.
In that case, "Lof()" returns 0.
OK , thank you very much for specifying :-)
You ought to put that in the documentation ;-) : https://www.freebasic.net/wiki/wikka.php?wakka=KeyPgLof
So In case that "Lof()" returns 0 then that would mean that *either* the file is not open *or* the file is empty ? (or ? )
Trinity
Posts: 214
Joined: Sep 16, 2017 17:07

Re: File I/O - Missing something simple [SOLVED]

Post by Trinity »

dodicat wrote:For files I use binary for strings.
Like this:
<-----------------SNIP----------------->
From the help file under OPEN
(adjusted only slightly)
It is going to take a little time to fully understand the code you gave me because I will first have to study it and see what it does and why (and also now I need go do something) .
But , thank you very much for sharing and explaining , your helping is educational :-)
fxm
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: File I/O - Missing something simple [SOLVED]

Post by fxm »

fxm wrote:In fact, there is no runtime error if we call "Lof()" while none file is opened.
In that case, "Lof()" returns 0.
Same or similar behavior for:
Loc() => 0
Seek() => 0
Eof() => -1

But I do not know if this behavior should be a requirement for the compiler (and so appear in documentation)!
St_W
Posts: 1626
Joined: Feb 11, 2009 14:24
Location: Austria
Contact:

Re: File I/O - Missing something simple [SOLVED]

Post by St_W »

fxm wrote:
fxm wrote:In fact, there is no runtime error if we call "Lof()" while none file is opened.
In that case, "Lof()" returns 0.
Same or similar behavior for:
Loc() => 0
Seek() => 0
Eof() => -1
It that specificied behavior? If so, it should be documented IMHO. Otherwise the current documentation is fine. Maybe it's even good to leave things like that unspecified in case try-catch-finally error handling is implemented at some time in the future (and the behavior could be change to throw an exception instead of returning an error code).
//edit: sorry for asking, just read your last sentence
Trinity
Posts: 214
Joined: Sep 16, 2017 17:07

Re: File I/O - Missing something simple [SOLVED]

Post by Trinity »

fxm wrote:But I do not know if this behavior should be a requirement for the compiler (and so appear in documentation)!
Ah! , sorry if I keep appearing totally green but I am not sure that I will ever fully understand to which length manual is a manual for language FreeBASIC and to which extend it is only manual for compiler FreeBASIC , and to be honest then I thought that they were sort of the same. Compiler only compile correct syntax FreeBASIC language and the concept of correct syntax FreeBasic language would be meaningless without compiler as it can not run without being compiled..

P.S.
If the language vs compiler discussion is a matter of e.g. that not all platforms necessarily will spit out errors for the same reason or the same codes then of course I already understand that concept in principle :-)
St_W
Posts: 1626
Joined: Feb 11, 2009 14:24
Location: Austria
Contact:

Re: File I/O - Missing something simple [SOLVED]

Post by St_W »

I would consider the documentation to be the official specification for the language. Every different behavior is either undocumented feature or a bug (or an error in the documentation). But as there is only a single FreeBasic compiler the supported syntax/language features are defined by that reference implementation in practice, too. FreeBasic is not that big and thus changes to or refinement of the language specification are usually just discussed on the forum. For big languages like C there is a lot of planning, a standardization process and of course a lot of compiler implementations - you can't really compare that to FB.

The question that arose in this thread is whether the behavior should be specified (and thus documented) or not. In the latter case (which represents the current sitation) it is not documented and the behavior of the compiler might change in the future without notice.

You as user should only rely on what is described in the documentation (or report a documentation error if you think something is incompletely or wrongly documented).
Trinity
Posts: 214
Joined: Sep 16, 2017 17:07

Re: File I/O - Missing something simple [SOLVED]

Post by Trinity »

St_W wrote: You as user should only rely on what is described in the documentation (or report a documentation error if you think something is incompletely or wrongly documented).
OK , thank you for clarifying !
Post Reply