Click to search Andy Jarrett.co.uk RSS feed

Loading Twitter

cffile in cfscript quick cheat sheet

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

Open and close a file

view plain print about
1myFile = expandPath( "somefile.txt" );
2fileObj = fileRead( myFile );
3writeOutput(fileObj);
4// OR
5myFile = expandPath( "somefile.txt" );
6fileObj = fileOpen( myFile, "read" );
7fileClose( fileObj ); // Once a file is closed you cannot access the object

Write to a file

view plain print about
1myFile = expandPath( "somefile.txt" );
2data = "I'm going to create a file object";
3FileWrite( "fileObj", data );
4newFileObj = FileRead( "fileObj" );
5writeDump(var=newFileObj);
6// OR write direct to file
7myFile = expandPath( "somefile.txt" );
8data = "I'm going to write to direct to file";
9FileWrite(myFile, data);

Append a line to a file

view plain print about
1myFile = expandPath( "somefile.txt" );
2fileObj = FileOpen( myFile, "append");
3fileWriteLine(fileObj,"This line is new.");
4fileClose(fileObj);

Output a text file to the screen

view plain print about
1myFile = expandPath( "somefile.txt" );
2fileObj = fileOpen( myFile, "read" );
3while( NOT fileIsEOF( fileObj ) ){
4line = fileReadLine( fileObj );
5WriteOutput( "#line# <br/>" );
6}
7FileClose( fileObj );

Copy/Move and delete a file

view plain print about
1myFile = expandPath( "somefile.txt" );
2myCopyFile = expandPath( "somefile2.txt" );
3fileCopy( myFile, myCopyFile); // fileMove() works the same
4writeOutput( fileExists( myCopyFile ) ); // Check copy worked
5fileDelete( myCopyFile );
6writeOutput( fileExists( myCopyFile ) ); // Check delete worked

Comments Comments (1) | Print Print | Send Send | 2003 Views

If you like what you see on the website and/or this post has helped you out in some way please consider donating to help keep me in beer vodka. The donations are made through Paypal, which accepts almost any credit card or eCheck.

(Comment Moderation is enabled. Your comment will not appear until approved.)
This may fall into the category of "No Duh", but you can also use these functions in tag based CF as well. I don't like how verbose cffile is - so if I want to simply read in a file, I may do:

<cfset contents = fileRead("..")>
BlogCFC by Raymond Camden + Twitter @AndyJ + ColdFusion jobs + Contact Me + Snippets/Downloads + RSS .