einaros
dangrmous wrote: |
I'm looking to create a new text file. I am in second term C++ so we're not using the MFC or anything. We have covered opening, reading, closing ifstream and ostream objects from fstream.h , but nothing about how to create a file if one's not there. Is this possible
|
|
Yeah, ifstream's open lets you specify how to open the file, and what happens if it already exists or doesn't exist at all.
ifstream f; f.open("filename", openmode);
Where openmode can be (and this is just about a direct paste from the MSDN page, so in the future, consider poking around there such as Sam suggests
):
ios_base::app, to seek to the end of a stream before each insertion.
ios_base::ate, to seek to the end of a stream when its controlling object is first created.
ios_base::binary, to read a file as a binary stream, rather than as a text stream.
ios_base::in, to permit extraction from a stream.
ios_base::out, to permit insertion to a stream.
ios_base::trunc, to delete contents of an existing file when its controlling object is created.
To create a new file you can use ifstream::open without any openmode, which will default to ios_base::out. If the file already exists, it will be truncated.
dangrmous wrote: |
Also - anyone know how to insert an eof into a file through a text editor or something in Windows I am given to understand the eof flag is represented by a ctrl-Z but I can't insert this using textedit. In the mean time I'm using a pipe symbol '|' as my eof flag which is much less elegant.
|
|
An EOF isn't generally something you can insert (anymore). It's not an entity that's present in your file at all, but rather a state indicated to your application when reading hits the end of the file's size. If you wish to create a file with a certain length, without inputing any particular data, you can open a new file for writing, and seek ahead using theFileStreem.seekp(numberOfBytesToSkipAhead);, output a random character (or e.g. a null), and finally close it.
In TextPad / UltraEdit and similar applications you can e.g. switch to hex mode, and input a bunch of null's, then save it. The EOF is "placed" (not entirely true, since it's not present as such) at the end of the file.