Writing to a File - Exercise

Contact Us or call 1-877-932-8228
Writing to a File - Exercise

Writing to a File

Duration: 15 to 25 minutes.

In this exercise you will write code to append entries to the RunningLog.txt.

  1. Open FilesAndDirs/Exercises/AddEntry.cfm in your editor.
  2. Write code to save the entry in Logs/RunningLog.txt.

Code Sample:

FilesAndDirs/Exercises/AddEntry.cfm
<html>
<head>
  <title>Running Log</title>
</head>
<body>

<!---
	Check to see if the form has been submitted.
--->
<cfif WRITE_CONDITION_HERE>
<!---
	Write code to append the entry to Logs/RunningLog.txt
--->
	<h1 align="center">Entry added</h1>
	<a href="RunningLog.cfm">Running Log</a>
</cfif>

<h1 align="center">Add Entry</h1>
<cfoutput><form method="post" action="#CGI.SCRIPT_NAME#"></cfoutput>
<input type="hidden" name="submitted" value="true">
<table>
<tr>
	<td>Date:</td>
	<td><input type="text" name="date" size="20"></td>
</tr>
<tr>
	<td>Distance:</td>
	<td><input type="text" name="distance" size="20"></td>
</tr>
<tr>
	<td>Time:</td>
	<td><input type="text" name="time" size="20"></td>
</tr>
<tr>
	<td>Comments:</td>
	<td><input type="text" name="comments" size="50"></td>
</tr>
<tr>
	<td colspan="2" align="right">
		<input type="submit" name="Add Entry">
	</td>
</tr>
</table>
</form>

</body>
</html>

Add errror handling (not shown in solution).

Solution:

FilesAndDirs/Solutions/AddEntry.cfm
<html>
<head>
  <title>Running Log</title>
</head>
<body>

<cfif isDefined("FORM.submitted")>
	<cfset RunningLogPath = ExpandPath("Logs/RunningLog.txt")>
	<cfset Tab = chr(9)>
	<cfset outputstring = "#FORM.date##Tab##FORM.distance##Tab##FORM.time##Tab##FORM.comments#">
	
	<cffile action="append" file="#RunningLogPath#" output="#outputstring#" addnewline="yes">
	<h1 align="center">Entry added</h1>
	<a href="RunningLog.cfm">Running Log</a>
</cfif>

<h1 align="center">Add Entry</h1>
---- C O D E   O M I T T E D ----

Next