Writing to Text Files
Windows only
Problem
You need to write to a text file from my general utility plugin.
Solution
Rhino C/C++ SDK does not have any special functions or classes to help you read or write text files.
With that said, there are a number of ways to read and write text files in C/C++.
- Use the C-runtime library’s
fopen
,fputs
,fwrite
andfclose
functions. - You can use the
iostream
library’sofstream
class. - You can use Win32’s
CreateFile
,WriteFile
, andCloseHandle
functions. - You can use MFC’s
CFile
andCStdioFile
classes.
Sample
Here is a simple example that uses the C-runtime library.
/*
Description:
Writes a string to a text file
Parameters:
text - [in] The string to write
filename - [in] The name of the file to write. If the file does not
exist, it will be created. If the file does exist,
it will be overwritten.
Returns:
true if successful, false otherwise.
*/
bool WriteStringToFile( const wchar_t* text, const wchar_t* filename )
{
bool rc = false;
if( (text && text[0]) && (filename && filename[0]) )
{
FILE* fp = _wfopen( filename, L"w" );
if( fp )
{
size_t num_write = wcslen( text );
size_t num_written = fwrite( text, sizeof(wchar_t), num_write, fp );
fclose( fp );
rc = ( num_written == num_write );
}
}
return rc;
}