FileToStr(), StrToFile()
This pair of functions makes it much easier to move text in and out of files. They don't actually add new capabilities to the language, but they replace large chunks of code to set up files and copy strings in and out of them.
Usage |
cFileContents = FileToStr( cFileName ) nCharsWritten = StrToFile( cFileContents, cFileName [ , lAdditive | nFlag ] ) |
Parameter |
Value |
Meaning |
cFileContents |
Character |
The string read from or written to a text file. |
cFileName |
Character |
The name of the text file to be read or written. |
lAdditive |
.T. |
Add cFileContents to an existing text file. |
.F. |
Overwrite cFileName with cFileContents, if it already exists. If SAFETY is ON and the file exists, the user is prompted before overwriting. |
|
nFlag |
0 |
Overwrite cFileName with cFileContents, if it already exists. If SAFETY is ON and the file exists, the user is prompted before overwriting. |
1 |
Add cFileContents to an existing text file. |
|
2 |
Include the Unicode Byte Order Mark at the beginning of the file. Assumes cFileContents is already in Unicode format. |
|
4 |
Include the UTF-8 Byte Order Mark at the beginning of the file. Assumes cFileContents is already in UTF-8 format. |
|
nCharsWritten |
Numeric |
The number of characters (bytes) written to the text file. |
Virtually every parameter named nFlag in VFP is additive, letting you make multiple choices and add their specified values together. This one isn't. Despite the use of binary values (1 for overwrite, 2 for Unicode, 4 for UTF-8), the only values accepted for nFlag are the ones in the table above. Specifying either the Unicode or UTF-8 settings overwrites an existing file |
If you specify an existing file in StrToFile(), but answer "No" to the Overwrite dialog, the function returns cFileContents, instead of something sensible like zero. (The function is smart enough to return 0 if the file you specify is read-only, though, but not smart enough to check whether it's read-only before prompting you to overwrite it.) |
You can move data in and out of files other than text files with these functions, if you're careful. For example, you can copy an entire table to a single string variable and even write it back out to create a new table, as long as it doesn't include any of the field types that need an FPT file (such as memo or general). (Of course, in that case, you can also copy the FPT file to a string and write it back out to a new FPT file, using these functions. Same thing for an index file.) We expect to use these functions most, though, for parsing tasks. In fact, we used FileToStr() to help write this book—we read in and parsed information from the Help file to create a table of all the language elements we needed to write about. |
Example |
* Here's an unusual way of copying a whole table cData = FileToStr("MyTable.DBF") =StrToFile(cData,"MyNewTable.DBF") |
See Also |