The <cffile> tag is used for working with files. The action attribute of <cffile> dictates what action will be performed on the file in question. The table below describes the different actions that can be performed.
|read||Reads a text file on the server into a local variable.|
|read binary||Reads a binary file on the server into a local variable.|
|write||Writes a text file to the server.|
|append||Appends text to a text file on the server.|
|move||Moves a file on the server from one directory to another.|
|rename||Renames (or moves) a file on the server.|
|copy||Copies a file on the server.|
|delete||Deletes a file from the server.|
|upload||Saves a file to a directory the server.|
When reading from a file, <cffile> requires three attributes:
|action||Must be set to read.|
|file||The absolute path to the file to be read.|
|variable||The variable to hold the contents of the file.|
In this lesson, we will be working with FilesAndDirs/Logs/RunningLog.txt, which is a tab-delimited text file. Each line is formatted as follows:
The file is divided into "columns" using tabs (chr(9)) and rows using hard returns (chr(10)chr(13)). The file is shown below.
11/10/07 3 miles 26:34 Man, am I out of shape 11/12/07 3.1 miles 28:23 I'm still sore from last time 11/24/07 2.5 miles 23:44 It's like I haven't run for two weeks 12/24/07 4.1 miles 34:02 I'll be in shape by Christmas!
The code below reads and displays the file in the browser.
<html> <head> <title>Running Log</title> </head> <body> <h1>Running Log</h1> <a href="AddEntry.cfm">Add Entry</a><hr/> <cfset RunningLogPath = ExpandPath("Logs/RunningLog.txt")> <cfset CrLf = chr(10) & chr(13)> <cfif FileExists(RunningLogPath)> <cffile action="read" file="#RunningLogPath#" variable="myfile"> <cfloop list="#myfile#" index="run" delimiters="#CrLf#"> <cfoutput>#run#<br/></cfoutput> </cfloop> <cfelse> You have apparently never been running. </cfif> </body> </html>
Let's look at the ColdFusion code step by step.
First, we create a variable that holds the absolute path to RunningLog.txt. Remember,
file attribute of
<cffile> requires an absolute path to the file.
Next, we create a variable called
CrLf that holds a carriage return/line feed. We'll use this
as the delimiter when we loop through the lines in the file.
Next, we use the
FileExists() function to check to see if RunningLog.txt exists.
If it does exist, we'll loop through it outputting the lines to the page. Otherwise, we output
"You have apparently never been running."
Next, we use the
<cffile> tag to read the contents of the file into the
Finally, we loop through the file using the
CrLf variable as the delimiter.