Whatever message this page gives is out now! Go check it out!

cffile action = "write"

Last update:
May 18, 2026

Description

Writes a text file on the server, based on dynamic content. You can create static HTML files from the content, or log actions in a text file.

Syntax

<cffile 
action = "write" 
file = "full pathname" 
output = "content" 
addNewLine = "yes|no" 
attributes = "file attributes list" 
charset = "character set option" 
fixnewline = "yes|no" 
mode = "permission">
Note: You can specify this tag's attributes in an attributeCollection attribute whose value is a structure. Specify the structure name in the attributeCollection attribute and use the tag's attribute names as structure keys.

See also

History

See the History section of the main cffile tag page.

Attributes

Attribute
Req/Opt
Default
Description
action
Required
Type of file manipulation that the tag performs.
file
Required
Pathname of the file to write. If not an absolute path (starting with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function.
output
Required
Content of the file to be created.
addNewLine
Optional
yes
  • yes: appends newline character to text written to file.
  • no
attributes
Optional
Applies to Windows. A comma-delimited list of attributes to set on the file.

If omitted, the file's attributes are maintained.Each value must be specified explicitly. For example, if you specify attributes = "readOnly", all other attributes are overwritten.
  • readOnly
  • hidden
  • normal
charset
Optional
JVM default file character set
The character encoding in which the file contents is encoded. The following list includes commonly used values:
fixnewline
Optional
no
  • yes: changes embedded line-ending characters in string variables to operating-system specific line endings.
  • no: does not change embedded line-ending characters in string variables.
mode
Optional
Applies only to UNIX and Linux. Permissions. Octal values of UNIX chmod command. Assigned to owner, group, and other, respectively; for example:
  • 644: assigns read/write permission to owner; read permission to group and other.
  • 777: assigns read/write/execute permission to all.

Example

This example creates a file with information a user entered in an HTML insert form:
<cffile action = "write" 
file = "c:\files\updates\#Form.UpdateTitle#.txt" 
output = "Created By: #Form.FullName# 
Date: #Form.Date# 
#Form.Content#">
If the user submitted a form with the following:
UpdateTitle = "FieldWork" 
FullName = "World B. Frueh" 
Date = "10/30/01" 
Content = "We had a wonderful time in Cambridgeport."
ColdFusion would create a file named FieldWork.txt in the c:\files\updates\ directory and the file would contain the following text:
Created By: World B. Frueh 
Date: 10/30/01 
We had a wonderful time in Cambridgeport.
This example shows the use of the mode attribute for UNIX. It creates the file /tmp/foo with permissions rw-r-r- (owner = read/write, group = read, other = read):
<cffile action = "write" 
file = "/tmp/foo" 
mode = 644>
This example appends to the file and sets permissions to read/write (rw) for all:
<cffile action = "append" 
destination = "/home/tomj/testing.txt" 
mode = 666 
output = "Is this a test?">
This example uploads a file and gives it the permissions owner/group/other = read/write/execute):
cffile action = "upload" 
fileField = "fieldname" 
destination = "/tmp/program.exe" 
mode = 777>
This example uses the fixnewline attribute to changes embedded line-ending characters in xmlString, which is derived from xmlData, to operating-system specific line endings.
<cfxml variable="xmlData"> 
<docroot> 
<payload type="string">This is some plain text</payload> 
</docroot> 
</cfxml> 
<cfset xmlString = toString(xmlData)> 

<cfset key = createUUID()> 
<cfset encString=encrypt(xmlString, key)> 
<cffile action="write" addnewline="yes" 
file="C:\ColdFusion9\wwwroot\test\store.dat" 
output="#encString#" fixnewline="yes"> 
<cffile action="read" file="C:\ColdFusion9\wwwroot\test\store.dat" 
variable="retrievedString"> 
<cfset decString=decrypt(retrievedString, key)> 
<cfdump var="#decString#"> 
<cfset newXML = xmlParse(decString)> 
<cfdump var="#newXML#">
ColdFusion supports using cffile to write an image, for example:
<!--- Create a new cfimage. ---> 
<cfset myImage=ImageNew("",200,200)> 
<!--- Draw a square on the image. ---> 
<cfset ImageDrawRect(myImage,10,10,100,100)> 
<!--- Use cffile to write the cfimage to a JPG. ---> 
<cffile action="write" output="#myImage#" file="c:\cfpix\square.jpg">

Real-world uses of cffile action="write"

Automated daily sales report generation

A retail management system needs to generate daily sales summary reports in CSV format for accounting department review and archival purposes.
Problem statement
The accounting team requires end-of-day sales reports that include transaction summaries, total revenue, and tax calculations. These reports must be saved as CSV files to a network shared folder where they can be imported into the accounting software. Manual report generation is time-consuming and error-prone, and the data needs to be formatted consistently for automated import processes.
<cfquery name="qDailySales" datasource="retailDB">
    SELECT 
        transaction_date,
        product_id,
        product_name,
        quantity,
        unit_price,
        total_amount,
        tax_amount
    FROM sales_transactions
    WHERE CAST(transaction_date AS DATE) = CAST(GETDATE() AS DATE)
    ORDER BY transaction_date
</cfquery>

<cfset reportContent = "Date,Product ID,Product Name,Quantity,Unit Price,Total,Tax#Chr(13)#Chr(10)#">

<cfloop query="qDailySales">
    <cfset reportContent &= "#DateFormat(transaction_date, 'yyyy-mm-dd')#,">
    <cfset reportContent &= "#product_id#,">
    <cfset reportContent &= '"#product_name#",'>
    <cfset reportContent &= "#quantity#,">
    <cfset reportContent &= "#NumberFormat(unit_price, '9.99')#,">
    <cfset reportContent &= "#NumberFormat(total_amount, '9.99')#,">
    <cfset reportContent &= "#NumberFormat(tax_amount, '9.99')##Chr(13)#Chr(10)#">
</cfloop>

<cfset fileName = "sales_report_#DateFormat(Now(), 'yyyymmdd')#.csv">
<cfset filePath = "\\network\shared\accounting\daily_reports\#fileName#">

<cffile action="write" 
        file="#filePath#" 
        output="#reportContent#" 
        charset="utf-8"
        mode="644">

<cflog text="Daily sales report generated: #fileName#" type="information">

Custom application error logging system

An enterprise web application needs a centralized error logging mechanism that writes detailed error information to dated log files for debugging and compliance auditing.
Problem statement
<cffunction name="logApplicationError" access="public" returntype="void">
    <cfargument name="errorStruct" type="struct" required="true">
    <cfargument name="userContext" type="struct" required="false" default="#StructNew()#">
    
    <cfset var logDirectory = ExpandPath("/logs/application_errors")>
    <cfset var logFileName = "error_log_#DateFormat(Now(), 'yyyy-mm-dd')#.log">
    <cfset var logFilePath = "#logDirectory#/#logFileName#">
    
    <!--- Ensure directory exists --->
    <cfif NOT DirectoryExists(logDirectory)>
        <cfdirectory action="create" directory="#logDirectory#">
    </cfif>
    
    <!--- Build detailed error log entry --->
    <cfset var logEntry = "">
    <cfset logEntry &= "========================================#Chr(13)#Chr(10)#">
    <cfset logEntry &= "Timestamp: #DateFormat(Now(), 'yyyy-mm-dd')# #TimeFormat(Now(), 'HH:mm:ss')##Chr(13)#Chr(10)#">
    <cfset logEntry &= "Error Type: #arguments.errorStruct.type#" & Chr(13) & Chr(10)>
    <cfset logEntry &= "Error Message: #arguments.errorStruct.message#" & Chr(13) & Chr(10)>
    <cfset logEntry &= "Error Detail: #arguments.errorStruct.detail#" & Chr(13) & Chr(10)>
    
    <cfif StructKeyExists(arguments.userContext, "userID")>
        <cfset logEntry &= "User ID: #arguments.userContext.userID#" & Chr(13) & Chr(10)>
    </cfif>
    
    <cfif StructKeyExists(arguments.userContext, "sessionID")>
        <cfset logEntry &= "Session ID: #arguments.userContext.sessionID#" & Chr(13) & Chr(10)>
    </cfif>
    
    <cfset logEntry &= "Request URL: #CGI.SCRIPT_NAME#?#CGI.QUERY_STRING#" & Chr(13) & Chr(10)>
    <cfset logEntry &= "Remote IP: #CGI.REMOTE_ADDR#" & Chr(13) & Chr(10)>
    <cfset logEntry &= "User Agent: #CGI.HTTP_USER_AGENT#" & Chr(13) & Chr(10)>
    <cfset logEntry &= "========================================" & Chr(13) & Chr(10) & Chr(13) & Chr(10)>
    
    <!--- Append to log file --->
    <cffile action="write" 
            file="#logFilePath#" 
            output="#logEntry#" 
            addnewline="no"
            charset="utf-8"
            mode="644">
</cffunction>

Dynamic configuration file management

A multi-tenant SaaS application needs to dynamically generate and update customer-specific configuration files when clients modify their settings through the admin panel.
Problem statement
Each customer tenant requires custom configuration settings (API keys, feature flags, branding options) that must be persisted to JSON configuration files. These files are read by various application modules at runtime. When administrators update settings via the web interface, the configuration files must be immediately updated without requiring application restarts. The system needs to maintain configuration versioning for rollback capabilities.
<cffunction name="updateTenantConfiguration" access="public" returntype="boolean">
    <cfargument name="tenantID" type="numeric" required="true">
    <cfargument name="configSettings" type="struct" required="true">
    
    <cfset var configDir = ExpandPath("/config/tenants")>
    <cfset var configFile = "#configDir#/tenant_#arguments.tenantID#_config.json">
    <cfset var backupFile = "#configDir#/tenant_#arguments.tenantID#_config_backup_#DateFormat(Now(),'yyyymmdd')#_#TimeFormat(Now(),'HHmmss')#.json">
    
    <cftry>
        <!--- Backup existing configuration --->
        <cfif FileExists(configFile)>
            <cffile action="copy" 
                    source="#configFile#" 
                    destination="#backupFile#">
        </cfif>
        
        <!--- Prepare configuration structure --->
        <cfset var configOutput = {
            "tenantID" = arguments.tenantID,
            "lastUpdated" = DateFormat(Now(), "yyyy-mm-dd") & " " & TimeFormat(Now(), "HH:mm:ss"),
            "apiEndpoint" = arguments.configSettings.apiEndpoint,
            "apiKey" = arguments.configSettings.apiKey,
            "features" = {
                "advancedReporting" = arguments.configSettings.advancedReporting,
                "customBranding" = arguments.configSettings.customBranding,
                "ssoEnabled" = arguments.configSettings.ssoEnabled
            },
            "branding" = {
                "companyName" = arguments.configSettings.companyName,
                "logoURL" = arguments.configSettings.logoURL,
                "primaryColor" = arguments.configSettings.primaryColor
            },
            "limits" = {
                "maxUsers" = arguments.configSettings.maxUsers,
                "maxStorage" = arguments.configSettings.maxStorage
            }
        }>
        
        <!--- Convert to JSON and write to file --->
        <cfset var jsonConfig = SerializeJSON(configOutput)>
        
        <cffile action="write" 
                file="#configFile#" 
                output="#jsonConfig#" 
                charset="utf-8"
                mode="644">
        
        <!--- Log the configuration update --->
        <cflog text="Configuration updated for tenant #arguments.tenantID#" 
               type="information" 
               file="tenant_config">
        
        <cfreturn true>
        
        <cfcatch type="any">
            <cflog text="Failed to update configuration for tenant #arguments.tenantID#: #cfcatch.message#" 
                   type="error" 
                   file="tenant_config">
            <cfreturn false>
        </cfcatch>
    </cftry>
</cffunction>

Export customer data for GDPR compliance

A customer relationship management (CRM) system needs to provide customers with a complete export of their personal data in a human-readable format to comply with GDPR data portability requirements.
Problem statement
Under GDPR regulations, customers have the right to receive all their personal data held by the company in a structured, commonly used, and machine-readable format. The system must generate comprehensive data exports that include customer profiles, communication history, purchase records, and preferences. These exports must be generated on-demand, secured, and available for download within 30 days.
<cffunction name="generateGDPRDataExport" access="public" returntype="string">
    <cfargument name="customerID" type="numeric" required="true">
    
    <cfset var exportDir = ExpandPath("/secure_exports/gdpr")>
    <cfset var exportFileName = "customer_data_export_#arguments.customerID#_#CreateUUID()#.txt">
    <cfset var exportFilePath = "#exportDir#/#exportFileName#">
    
    <!--- Ensure directory exists --->
    <cfif NOT DirectoryExists(exportDir)>
        <cfdirectory action="create" directory="#exportDir#">
    </cfif>
    
    <!--- Retrieve customer data from database --->
    <cfquery name="qCustomer" datasource="crmDB">
        SELECT * FROM customers WHERE customer_id = <cfqueryparam value="#arguments.customerID#" cfsqltype="cf_sql_integer">
    </cfquery>
    
    <cfquery name="qOrders" datasource="crmDB">
        SELECT * FROM orders WHERE customer_id = <cfqueryparam value="#arguments.customerID#" cfsqltype="cf_sql_integer">
    </cfquery>
    
    <cfquery name="qCommunications" datasource="crmDB">
        SELECT * FROM communications WHERE customer_id = <cfqueryparam value="#arguments.customerID#" cfsqltype="cf_sql_integer">
    </cfquery>
    
    <!--- Build export content --->
    <cfset var exportContent = "">
    <cfset exportContent &= "GDPR DATA EXPORT REPORT" & Chr(13) & Chr(10)>
    <cfset exportContent &= "Generated: #DateFormat(Now(), 'yyyy-mm-dd')# #TimeFormat(Now(), 'HH:mm:ss')#" & Chr(13) & Chr(10)>
    <cfset exportContent &= "Customer ID: #arguments.customerID#" & Chr(13) & Chr(10)>
    <cfset exportContent &= String(80, "=") & Chr(13) & Chr(10) & Chr(13) & Chr(10)>
    
    <!--- Personal Information --->
    <cfset exportContent &= "PERSONAL INFORMATION" & Chr(13) & Chr(10)>
    <cfset exportContent &= String(40, "-") & Chr(13) & Chr(10)>
    <cfloop query="qCustomer">
        <cfset exportContent &= "Name: #first_name# #last_name#" & Chr(13) & Chr(10)>
        <cfset exportContent &= "Email: #email#" & Chr(13) & Chr(10)>
        <cfset exportContent &= "Phone: #phone#" & Chr(13) & Chr(10)>
        <cfset exportContent &= "Address: #address#, #city#, #state# #zip#" & Chr(13) & Chr(10)>
        <cfset exportContent &= "Account Created: #DateFormat(created_date, 'yyyy-mm-dd')#" & Chr(13) & Chr(10)>
    </cfloop>
    <cfset exportContent &= Chr(13) & Chr(10)>
    
    <!--- Order History --->
    <cfset exportContent &= "ORDER HISTORY" & Chr(13) & Chr(10)>
    <cfset exportContent &= String(40, "-") & Chr(13) & Chr(10)>
    <cfloop query="qOrders">
        <cfset exportContent &= "Order ##: #order_id#" & Chr(13) & Chr(10)>
        <cfset exportContent &= "Date: #DateFormat(order_date, 'yyyy-mm-dd')#" & Chr(13) & Chr(10)>
        <cfset exportContent &= "Amount: $#NumberFormat(total_amount, '9.99')#" & Chr(13) & Chr(10)>
        <cfset exportContent &= "Status: #status#" & Chr(13) & Chr(10) & Chr(13) & Chr(10)>
    </cfloop>
    
    <!--- Communication History --->
    <cfset exportContent &= "COMMUNICATION HISTORY" & Chr(13) & Chr(10)>
    <cfset exportContent &= String(40, "-") & Chr(13) & Chr(10)>
    <cfloop query="qCommunications">
        <cfset exportContent &= "Date: #DateFormat(comm_date, 'yyyy-mm-dd')#" & Chr(13) & Chr(10)>
        <cfset exportContent &= "Type: #comm_type#" & Chr(13) & Chr(10)>
        <cfset exportContent &= "Subject: #subject#" & Chr(13) & Chr(10)>
        <cfset exportContent &= "Content: #content#" & Chr(13) & Chr(10) & Chr(13) & Chr(10)>
    </cfloop>
    
    <!--- Write to file --->
    <cffile action="write" 
            file="#exportFilePath#" 
            output="#exportContent#" 
            charset="utf-8"
            mode="600">
    
    <!--- Log the export request --->
    <cflog text="GDPR data export generated for customer #arguments.customerID#" 
           type="information" 
           file="gdpr_exports">
    
    <cfreturn exportFileName>
</cffunction>

Share this page

Was this page helpful?
We're glad. Tell us how this page helped.
We're sorry. Can you tell us what didn't work for you?
Thank you for your feedback. Your response will help improve this page.

On this page