_WRITEFILE

From QB64 Phoenix Edition Wiki
Revision as of 23:46, 15 February 2024 by RhoSigma (talk | contribs) (Created page with "{{DISPLAYTITLE: _WRITEFILE}} The '''_WRITEFILE''' function writes a string into a new file, overwriting an existing file of the same name. It does OPEN, PUT and CLOSE the file in one run. It's the counterpart to _READFILE$. {{PageSyntax}} : {{Parameter|success%}} = _WRITEFILE({{Parameter|fileSpec$}}, {{Parameter|contents$}}) {{PageParameters}} * {{Parameter|success%}} is an INTEGER return value, it shows whether the write operation was success...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

The _WRITEFILE function writes a string into a new file, overwriting an existing file of the same name. It does OPEN, PUT and CLOSE the file in one run. It's the counterpart to _READFILE$.


Syntax

success% = _WRITEFILE(fileSpec$, contents$)


Parameters

  • success% is an INTEGER return value, it shows whether the write operation was successful (-1) or not (0). Any file related ERROR may occur.
    • To avoid errors you should use _PATHEXISTS before calling this function to make sure a used path exists.
  • fileSpec$ is the name of the file to write as literal or variable STRING, if required inclusive a full or relative path.
  • contents$ is the literal or variable STRING which its contents shall be written into the file.


Description

  • Sometimes you may be in need to quickly dump a huge amount of data into a file without much fuss, e.g. the results of the pack/unpack functions _DEFLATE$ and _INFLATE$ or when copying a file in conjunction with the _READFILE$ function.
  • In earlier versions of QB64(PE) you had to implement that saving process manually all the time or create a reusable custom FUNCTION for it.
  • Now _WRITEFILE will simplify this, it's mainly a convenience function to wrap the following code sequence in one handy function:
fh = FREEFILE
OPEN fileSpec$ FOR OUTPUT AS #fh: CLOSE #fh
OPEN fileSpec$ FOR BINARY AS #fh
PUT #fh, , contents$
CLOSE #fh


Availability


Examples

Example
Implementing a simple file copy routine using _READFILE$ and _WRITEFILE.
s$ = "Makefile"
d$ = "Makefile - Copy"

r$ = CopyFile$(s$, d$)

IF r$ = "" THEN
    PRINT "Sucessfully copied '"; s$; "' to '"; d$; "'."
ELSE
    PRINT r$
END IF

END

FUNCTION CopyFile$ (src$, dst$)
    CopyFile$ = "" 'empty = success, otherwise error message
    buffer$ = _READFILE$(src$)
    IF buffer$ = "" AND _FILEEXISTS(src$) = 0 THEN
        CopyFile$ = "ERROR: Source file doesn't exist."
    ELSE
        succ% = _WRITEFILE(dst$, buffer$)
        IF NOT succ% THEN
            CopyFile$ = "ERROR: Couldn't write destination file."
        END IF
    END IF
END FUNCTION


See also



Navigation:
Main Page with Articles and Tutorials
Keyword Reference - Alphabetical
Keyword Reference - By usage