Andy Jarrett // Code. Develop. Manage.

Using CFFILE within CFScript

Welcome to this quick guide on using CFFILE within cfscript. Whether you're new to CFML or just looking to brush up on file operations, this post will provide you with some useful snippets and explanations.

First time using CFFILE within cfscript, so I thought I should document this for myself and anyone else.

Open and close a file

// Define the path to the file
myFile = expandPath("somefile.txt");

// Read the file content directly
fileObj = fileRead(myFile);
writeOutput(fileObj);

// OR

// Open the file in read mode
myFile = expandPath("somefile.txt");
fileObj = fileOpen(myFile, "read");

// Close the file after reading
fileClose(fileObj);

// Once a file is closed you cannot access the object

Write to a file

// Define the path to the file
myFile = expandPath("somefile.txt");

// Create data to be written
data = "I'm going to create a file object";

// Write data to the file object
FileWrite("fileObj", data);

// Read the newly written file content
newFileObj = FileRead("fileObj");
writeDump(var=newFileObj);

// OR write direct to file

// Define the path to the file again
myFile = expandPath("somefile.txt");
data = "I'm going to write directly to the file";

// Write data directly to the file
FileWrite(myFile, data);

Append a line to a file

// Define the path to the file
myFile = expandPath("somefile.txt");

// Open the file in append mode
fileObj = FileOpen(myFile, "append");

// Write a new line to the file
fileWriteLine(fileObj, "This line is new.");

// Close the file after appending
fileClose(fileObj);

Output a text file to the screen

// Define the path to the file
myFile = expandPath("somefile.txt");

// Open the file in read mode
fileObj = fileOpen(myFile, "read");

// Read the file line by line until the end
while(NOT fileIsEOF(fileObj)){
  line = fileReadLine(fileObj);
  WriteOutput("#line#");
}

// Close the file after reading
FileClose(fileObj);

Copy/Move and delete a file

// Define the paths to the source and destination files
myFile = expandPath("somefile.txt");
myCopyFile = expandPath("somefile2.txt");

// Copy the file to a new location
fileCopy(myFile, myCopyFile);

// fileMove() works the same way
writeOutput(fileExists(myCopyFile)); // Check if the copy worked

// Delete the copied file
fileDelete(myCopyFile);
writeOutput(fileExists(myCopyFile)); // Check if the delete worked
I’m here, learning and working away. If you liked this content and want to keep me going, consider buying me a coffee.
Your support keeps this site running and the coffee brewing! ☕️