Advertisement

Writing to Files

Started by February 21, 2000 10:01 PM
5 comments, last by C++ Freak 24 years, 6 months ago
I have everything loaded just fine but I want to write to the file now. I am wondering which function I should use. I only know of one, called LinePrint. I don''t know how to use it. The MSDN library doesn''t offer much help on how to use it. Thanks for the help. Visit http://members.xoom.com/ivanickgames
Visit http://members.xoom.com/ivanickgames
I seem to recall that you didn''t use C++ inspite of your nick.

In C you can use fprintf(), which works the same way as printf().

FILE *File = fopen("FileName.txt","wt");float AValue = 3.14159f;fprintf(File, "Some text on the line %f\n", AValue);fclose(File); 


If you''re using C++ you can use the class ofstream like this:

ofstream File("FileName.txt");float AValue = 3.14159f;File << "Some text on the line " << AValue << endl; 
Advertisement
You can use fprintf

int fprintf( FILE *stream, const char *format [, argument ]...);

#include
#include
FILE *stream;
void main( void )
{
int i = 10;
double fp = 1.5;
char s[] = "this is a string";
char c = ''\n'';
stream = fopen( "fprintf.out", "w" );
fprintf( stream, "%s%c\n", s, c );
fprintf( stream, "%d\n", i );
fprintf( stream, "%f\n", fp );
fclose( stream );
}
But It''s basically not readable if you don''t match the reading-in format you used for the 1st part

ZoomBoy
A 2D RPG with skills, weapons, and adventure.
See my character editor, Tile editor and diary at
http://www.geocities.com/Area51/Atlantis/7739/

I''m still doin'' it like so:
char[x] String;//...int handle = open ("filename", O_CREAT / O_WRONLY / O_BINARY);write (handle, String, sizeof (String));close (handle); 


That''s it!

If you don''t mind using a little C you can use the function
fwrite(char *pointer_to_array, int size_of element,
int number_of_elements, FILE *file_pointer);

where the FILE struct is declared in stdio.h
oh yes, you can get a pointer to a file by using fopen eg:

FILE *fp = fopen("emptyfile.dat","wb");
where the wb string stands for write in binary mode. If you did want to write in ascii mode (as the first two posts mentioned) you would just use the string "w".

This method is nice if you want to do a binary write, which is generally a good idea unless you''re deliberately outputting something that needs to be human-readable.
-david
Read "The C Programming Language."

- mallen22@concentric.net
- http://www.cfxweb.net/mxf/
Advertisement
Thanks for all the replys! I finally got it working.

Visit http://members.xoom.com/ivanickgames
Visit http://members.xoom.com/ivanickgames

This topic is closed to new replies.

Advertisement