Page 1 of 1

Very simple editor to show local file read/write

Posted: Sat Jul 02, 2016 9:55 am
by hotcore

Code: Select all

; ------------------------------------------------------------------------------------
;  Little file editor
; ------------------------------------------------------------------------------------

title.s = "Little File Editor"
XIncludeFile "..\includes\default.sb"
Global inFile.s

Procedure FileRead(Status, Filename$, File, Size)
  If Status = #PB_Status_Loaded
    buffer.s = ""
    While Not Eof(4)
      char.c = ReadCharacter(4)
      buffer = buffer + Chr(char)
    Wend
    CloseFile(4)
    SetGadgetText(1, buffer)
  ElseIf Status = #PB_Status_Error
    Debug "Error when loading the file: " + Filename$
  EndIf
EndProcedure

Procedure FileOpen()
  If NextSelectedFile()
    inFile = SelectedFileID()
    ReadFile(4, inFile, @FileRead(), #PB_LocalFile)
  EndIf
EndProcedure

Procedure FileOpenReq()
  OpenFileRequester("*.txt", @FileOpen())
EndProcedure

Procedure FileSave()
  buffer.s = GetGadgetText(1)
  If CreateFile(5, inFile, #PB_UTF8)                ; we re-create a new text file
    For i = 1 To Len(buffer)
      WriteCharacter(5, Asc(Mid(buffer,i,1)), #PB_UTF8)  ; write a char at a time
    Next
    ExportFile(5, "text/plain")
    CloseFile(5)                      
  EndIf


EndProcedure
  
; ------------------------------------------------------------------------------------
;  Main program
; ------------------------------------------------------------------------------------
OpenWindow(0, 0, 0, 520, 590, title)

EditorGadget(1, 10, 10, 500, 500)
ButtonGadget(2, 10, 520, 220, 30, "Open a text file ..")
ButtonGadget(3, 250, 520, 220, 30, "Save as text file ..")

BindGadgetEvent(2, @FileOpenReq())
BindGadgetEvent(3, @FileSave())

Re: Very simple editor to show local file read/write

Posted: Sat Jul 02, 2016 10:17 am
by Arbrakaan
Works great, thanks for sharing !

Re: Very simple editor to show local file read/write

Posted: Sat Jul 02, 2016 1:44 pm
by hotcore
I did a small update in the code to remove extraoneous variuable.
Note that writing the file effectively is a download in the browser!