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
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
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
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);
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
1myFile = expandPath( "somefile.txt" );
2fileObj = FileOpen( myFile, "append");
3fileWriteLine(fileObj,"This line is new.");
4fileClose(fileObj);
2fileObj = FileOpen( myFile, "append");
3fileWriteLine(fileObj,"This line is new.");
4fileClose(fileObj);
Output a text file to the screen
1myFile = expandPath( "somefile.txt" );
2fileObj = fileOpen( myFile, "read" );
3while( NOT fileIsEOF( fileObj ) ){
4line = fileReadLine( fileObj );
5WriteOutput( "#line# <br/>" );
6}
7FileClose( fileObj );
2fileObj = fileOpen( myFile, "read" );
3while( NOT fileIsEOF( fileObj ) ){
4line = fileReadLine( fileObj );
5WriteOutput( "#line# <br/>" );
6}
7FileClose( fileObj );
Copy/Move and delete a file
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
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
| Tweet |
| 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. |
<cfset contents = fileRead("..")>