May 01, 2024, 10:36:24 PM

News:

Own IWBasic 2.x ? -----> Get your free upgrade to 3.x now.........


reading text but doesn't close properly

Started by TexasPete, February 01, 2009, 06:10:49 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

TexasPete

I have worked thru the following a produced a working example. But after listing the text, it causes a microsoft error message. I do not know why. Any gurus that can help with my ignorance. I would appreciate. I will also post the working example for other newbies.

OPENCONSOLE
DEF myfile:FILE
DEF ln:STRING
DEF STARTPATH:STRING
myfile=1
STARTPATH=GETSTARTPATH
ChangePath(STARTPATH)
STARTPATH=STARTPATH+"test.txt"
print STARTPATH
PRINT myfile
IF(OPENFILE(myfile,STARTPATH,"R") = 0)
  while EOF(myfile)=0
   IF(READ(myfile,ln) = 0)
    print ln
   ENDIF
  ENDWHILE
CLOSEFILE myfile
   PRINT "File read successfully"
ELSE
   PRINT "File could not be opened"
ENDIF
'-------------------------------
PRINT "Press Any Key To Close"
DO:UNTIL INKEY$ <>""
CLOSECONSOLE
END
SUB ChangePATH(TEMP:STRING)
DEF TEMPPATH:STRING
DEF X:INT
DEF S$:STRING
S$=CHR$(92)+CHR$(92)
TEMPPATH=""
FOR X = 1 TO LEN(TEMP):X$=MID$(TEMP,X,1)
IF X$ = CHR$(92) THEN
TEMPPATH=TEMPPATH+S$
ELSE
TEMPPATH=TEMPPATH+X$                   
END IF
NEXT X
TEMP=TEMPPATH
RETURN
ENDSUB


Thanks Texas Pete

GJ

Hi Pete,

Did not have trouble reading a file, maybe you can change the subroutine a bit

IF X$ = CHR$(92) THEN
TEMPPATH=TEMPPATH+S$
ELSE
TEMPPATH=TEMPPATH+X$                   
END IF


IF X$ = CHR$(92)
TEMPPATH=TEMPPATH+S$
ELSE
TEMPPATH=TEMPPATH+X$                   
ENDIF


Seems to me the END IF is treated like an END statement




Gertjan


Ionic Wind Support Team

What in the world are you doing with that changepath subroutine??  You don't need to make a \ a double \\ unless you the user are physically typing it into the source code.  A literal string, as described in the users guide, is a string enclosed in quotes typed into the source code.  Not a string that you construct in code at runtime.

There is an example in the users guide on how to open and read a text file, but you didn't read the supporting text around the examples.  Heck for that matter steal the code from editor.eba which opens a text file and displays it in an edit box.

Here is your code, changed to remove the unneeded bits:


OPENCONSOLE
DEF myfile:FILE
DEF ln:STRING
DEF STARTPATH:STRING
STARTPATH=GETSTARTPATH() +"test.txt"

IF(OPENFILE(myfile,STARTPATH,"R") = 0)
   while READ(myfile,ln) = 0
     print ln
   ENDWHILE
   CLOSEFILE myfile
   PRINT "File read successfully"
ELSE
   PRINT "File could not be opened"
ENDIF
'-------------------------------
PRINT "Press Any Key To Close"
DO:UNTIL INKEY$ <>""
CLOSECONSOLE
END



Now that will work for text files that don't have lines longer than 255 characters.  Which is the maximum length of a STRING variable.  If you want to be able to read longer lines then define a longer string

DEF ln[1024] AS ISTRING

For a quick test of the concept, save my example above as "test.eba", anywhere.  Change "test.txt" to "test.eba" in the startpath line, compile and run.

Also, explore the alphabetical command reference in the users guide.  From the READ entry:

Quote
String data can be any length. In ASCII mode READ will continue to read the string character by character until a new line or NULL terminator is found. Be sure to use a large enough string to accommodate the data. READ will overwrite string memory if the data is longer than the dimensioned string.

Paul.
Ionic Wind Support Team

TexasPete

February 01, 2009, 10:28:05 AM #3 Last Edit: February 01, 2009, 10:39:36 AM by TexasPete
Paul thanks a lot.
I am used to liberty basic and power basic . In those languages I don't have to worry about the "\\" at all. I know I could steal some code, But I would not know what I am doing that way. I will struggle for a few weeks untill I understand the differences. Thanks a lot Philp.
Paul I have read the supporting help files several times. I obviously, did not understand what you were trying to say.

So let me understand. Is the following correct to say.

when useing GetStartPath . It is not necessary to add the extra slash.
So following is correct?

openfile (myfile,"c:\program\text.txt","R")
but if I use a string
"c:\\program\\text.txt"
x$="c:\\program\\text.txt"
open (myfile,x$,"R")
Is that what you mean?
Texas pete

Ionic Wind Support Team

openfile (myfile,"c:\\program\\text.txt","R") <--Still a literal string, YOU typed it into the code.

GetStartPath() + "file.txt" <-- No slashes needed as GetStartPath includes the trailing one.

filename = GetFolderPath(@CSIDL_COMMON_DOCUMENTS) + "\\coolstuff.txt"  <--  One slash needed in the literal string, as GetFolderPath doesn't include the trailing slash.

http://www.ionicwind.com/guides/emergence/language_topics_constants_and_literals.htm

Quote
A string literal is text enclosed in quotes. The compiler supports string escape sequences to insert special ASCII values into the string without having to use CHR$ to generate them. String literals are stored in the executable when compiled.

And..

Quote
All escape sequences begin with a single backslash ' \ '. Because of this in order to have a backslash in the string itself you need to use a double backslash ' \\ '. This is important to remember when working with filenames.

Myfile = "C:\\data\\inp.text"

If that is the bit that is confusing you, you have to take it in the context of the users guide section "Constants and Literals",   It didn't mean you had to convert all \ to \\ in a string variable. 

This:

Myfile = "C:\\file.text"

Doesn't put two slashes in the string, it converts the two slashes to a single one BEFORE storing it in the string variable.  Just as

text = "\tThis is indented"

Doesn't put \t in the string, it converts it to a TAB character.

text = "line one\nline two"

Puts a newline character in the string variable between line one and line two.

And just a FYI, escape sequences are not unique to Emergence and Aurora, they are used in almost all languages.  Other languages use a different character, DELPHI uses the # for example to insert ASCII character codes into a literal string.  PHP uses pretty much the same as C except they don't use double quotes so you have to use an escape for single quotes.  'Arnold once said: "I\'ll be back"'  Which I find most annoying when writing php scripts.

I adopted the ones used by C and C++ since they were the most common, and used in many languages.

Paul.
Ionic Wind Support Team

TexasPete

Thanks Paul I will reread constants and literals again.
Thanks Texas Pete
This was right out of the book and I could not get it to work.
I did change the file name to test.txt.

OPENCONSOLE
DEF myfile:FILE
DEF ln:STRING
IF(OPENFILE(myfile,"C:\\test.txt","R") = 0)
   IF(READ(myfile,ln) = 0)
            PRINT ln
   ENDIF
   CLOSEFILE myfile
   PRINT "File read successfully"
ELSE
   PRINT "File could not be opened"
ENDIF
PRINT "Press Any Key To Close"
DO:UNTIL INKEY$ <> ""
CLOSECONSOLE
END

LarryMc

It will only work (as written) if you have a file named 'test.txt' in the root directory of your 'c' drive.

That isn't the place to be storing files.

Larry
LarryMc
Larry McCaughn :)
Author of IWB+, Custom Button Designer library, Custom Chart Designer library, Snippet Manager, IWGrid control library, LM_Image control library

Ionic Wind Support Team

What didn't work?  The example reads 1 line from a text file located on the root of the drive and prints in a console.

That example, in context of the docs, was just to demonstrate the READ statement, not as something you could just cut and paste to read multiple lines of text.  The editor.eba sample has code that reads an entire text file, up to 32K, which is in the context of showing it in an edit control


SUB doopen
filename = filerequest("Load File",win,1)
if(len(filename) > 0)
buffer = ""
if( openfile(file1,filename,"R") = 0)
do
if(read(file1,ln) = 0)
if len(buffer) < (32766-257)
buffer = buffer + ln + chr$(13) + chr$(10)
endif
endif
until eof(file1)
closefile file1
setcontroltext win,1,buffer
endif
endif
RETURN
endsub


It all depends on what you are going to DO with the line once you have read it.  The editor.eba sample was written in old BASIC style, to make it easier to understand.  Personally I don't code that way, but more complex examples are hard for new users to understand.  SetControlText/GetControlText is easy for newbies.  An actual read/write from an edit control to a file in a commercial application would never use a hard coded buffer limited to 32K like that.   Instead a dynamic buffer, allocated in memory, is commonly used to read the file once the length of the file is determined.  Writing depends on where the data is coming from.

Paul.
Ionic Wind Support Team

TexasPete

Paul ,
Maybe I am reporting the wrong error. I was able to get the following code to read a text file.

autodefine "ON"
OPENCONSOLE
DEF STARTPATH:STRING
STARTPATH=GETSTARTPATH
STARTPATH=STARTPATH+"\\test.txt"
print STARTPATH
def  myfile as file
DEF Textline:STRING
DEF E:INT
'-------Empty Html Document the Array-------------
Lines =1
IF(OPENFILE(myfile,STARTPATH,"R") = 0)
   do   
   if ((READ myfile,Textline)=0)
    print Textline
   'HTMLDOCUMENT[lines]=TextLine:Lines=Lines+1
   endif   
until eof(myfile)
CLOSEFILE myfile
   PRINT "File read successfully"
ELSE
   PRINT "File could not be opened"
ENDIF
'-------------------------------
PRINT "Press Any Key To Close"
DO:UNTIL INKEY$ <>""
CLOSECONSOLE
END

At the end I get a please report error to microsoft error message.
Should I be getting this message.
Thanks
Texas Pete

Ionic Wind Support Team

I will try again to make this clear to you.


Now that will work for text files that don't have lines longer than 255 characters.  Which is the maximum length of a STRING variable.  If you want to be able to read longer lines then define a longer string

DEF ln[1024] AS ISTRING


You don't need to EOF check if all you are doing is reading text lines, Use the code I gave you please.

If you are trying to read HTML then take note of the fact that a lot of HTML doesn't contain newlines, in fact it is all on one long single line.  That is the nature of html.

Also learn to use the debugger.  Instead of asking here "why am I getting an error" you could compile it in debug mode, and find out the exact line it is failing on.  Most likely you are attempting to read a line longer than 255 characters.

Paul.
Ionic Wind Support Team

aurelCB

Try this if you need autoload

'Try this
def win:window
def left,top,width,height,hprinter:int
def startpg,endpg,copies,collate:int
def filename,ln,printer:string
def file1:FILE
def buffer[32766]:ISTRING
run = 0
'Open our main window, get its client size and create the control
openwindow win,0,0,640,400,@SIZE|@MINBOX|@MAXBOX|@NOAUTODRAW,0,"EDITOR V1.2",&mainwindow
getclientsize win,left,top,width,height
control win,@EDIT,"",left,top,width,height,@CTEDITMULTI|@HSCROLL|@VSCROLL,1
BEGINMENU win
MENUTITLE "&File"
MENUITEM "&Load File\tCtrl+L",0,1
MENUITEM "&Save\tCtrl+S",0,2
MENUITEM "&Print\tAlt+P",0,4
MENUITEM "&Quit\tCtrl+C",0,3
MENUTITLE "&Options"
MENUITEM "Change Font\tF4",0,5
ENDMENU

'add our keyboard accelerators
ADDACCELERATOR win,@FCONTROL|@FVIRTKEY,ASC("L"),1
ADDACCELERATOR win,@FCONTROL|@FVIRTKEY,ASC("S"),2
ADDACCELERATOR win,@FCONTROL|@FVIRTKEY,ASC("C"),3
ADDACCELERATOR win,@FALT|@FVIRTKEY,ASC("P"),4
ADDACCELERATOR win,@FVIRTKEY,0x73,5:'F4 key changes font
SETCONTROLCOLOR win,1,0,RGB(255,255,255)


'gosub autoload test file---------------
Gosub doopen
'---------------------------------------

run = 1
waituntil run=0
closewindow win
end

'--------------------------------------
'process @IDCLOSEWINDOW to quit the program
sub mainwindow
select @MESSAGE
case @IDCLOSEWINDOW
run = 0
case @IDCREATE
Centerwindow win
case @IDSIZE
'size the edit control to match the client size of the window
'we use CONTROLEXISTS to verify the existance of the edit control
'because the first @IDSIZE message is sent while the window is being created
'but before we have a chance to add the edit control.
if CONTROLEXISTS(win,1)
getclientsize win,left,top,width,height
setsize win,left,top,width,height,1
endif
case @IDMENUPICK
select @MENUNUM
case 5
GOSUB changefont
case 4
'dump the edit control to the printer
GOSUB doprint
case 3
'quit the program
run = 0
case 2
'save the file
GOSUB dosave
case 1
'open a file
GOSUB doopen
endselect
endselect
return
endsub

'------------- DOOPEN ----------------
SUB doopen
'select filename/ try change filename
filename = "c:\\test.txt"

buffer = ""
IF( openfile(file1,filename,"R") = 0)
do
if(read(file1,ln) = 0)
if len(buffer) < (32766-257)
buffer = buffer + ln + chr$(13) + chr$(10)
endif
endif
until eof(file1)
closefile file1
setcontroltext win,1,buffer
ELSE
Messagebox win,"Filename Not found: " + filename,"NOT FOUND"
ENDIF

RETURN
ENDSUB

'------------- DOSAVE -----------------
SUB dosave
filename = filerequest("Save File",win,0)
if(len(filename) > 0)
if(openfile(file1,filename,"W") = 0)
buffer = getcontroltext(win,1)
write file1,buffer
closefile file1
endif
endif
RETURN
endsub
'------------- DOPRINT ----------------
'prints the contents of the edit control
'using straight text printing.
'This method won't work for GDI only printers
'--------------------------------------
SUB doprint
startpg = 1
endpg = 1
copies = 1
collate = 1
printer = PRTDIALOG(win,startpg,endpg,copies,collate)
hprinter = OPENPRINTER(printer,"Document","TEXT")
if(hprinter)
buffer = getcontroltext(win,1)
WRITEPRINTER hprinter, buffer
CLOSEPRINTER hprinter
endif
RETURN
endsub
'------------- CHANGEFONT -------------
SUB changefont
DEF size,weight,flags,col:int
DEF fontname:string
size = 12
weight = 400
flags = 0
col = 0
fontname = FONTREQUEST(win,size,weight,flags,col)
if(fontname <> "")
SETFONT win,fontname,size,weight,flags,1
endif
SETCONTROLCOLOR win,1,col,RGB(255,255,255)
RETURN
endsub

fasecero

QuoteAlso learn to use the debugger

This is a very good advice. Before using EB i didn't have any idea of what a debugger do and now it has become something indispensable for me. In case of errors it will indicates exactly where. If I cannot find even in this way the mistake(s), I try with STOP or DEBUGPRINT in the suspicious places. :)

billhsln

February 01, 2009, 08:34:38 PM #12 Last Edit: February 01, 2009, 08:36:36 PM by billhsln
Your code revised to handle larger input, which is what usually aborts EBasic code when reading Text files, at least that is what it has always done to me.

autodefine "OFF"

DEF STARTPATH:STRING
DEF  myfile:file
DEF Textline[2048]:ISTRING
DEF Lines:INT

OPENCONSOLE

STARTPATH = GETSTARTPATH
STARTPATH = STARTPATH + "\\test.txt"
print STARTPATH
'-------Empty Html Document the Array-------------
Lines = 1
IF (OPENFILE(myfile,STARTPATH,"R") = 0)
  WHILE (READ(myfile,Textline)=0)
    print Textline
  WEND   
  CLOSEFILE myfile
  PRINT "File read successfully"
ELSE
  PRINT "File could not be opened"
ENDIF
'-------------------------------
PRINT "Press Any Key To Close"
DO:UNTIL INKEY$ <>""
CLOSECONSOLE
END


Give this a try.

Bill
When all else fails, get a bigger hammer.

TexasPete

Thanks everyone,
I think I will be able to finish what I am trying to do now.
Bill I didnt think about TextLine needing to be bigger. I have found out there are quite a few differences between eb and the other basics. Every one I promise that I have read the manual. I have probably printed 200 pages in just the last week. I think when I finish this I will put together a short list fact page about some of the differences for others who might venture this way.
Aurel thanks for the code I will look into that today.

Thanks all
Texas pete