C, C++ & C# in easy steps by Mike McGrath

C, C++ & C# in easy steps by Mike McGrath

Author:Mike McGrath
Language: eng
Format: epub
Publisher: In Easy Steps
Published: 2023-07-07T00:00:00+00:00


Writing a file

The ability to read and write files from a program provides a useful method of maintaining data on the computer’s hard disk. The format of the data may be specified as human-readable plain text format or machine-readable binary format.

The standard C++ <fstream> library provides functions for working with files, which can be made available by adding an #include <fstream> directive at the start of the program.

For each file that is to be opened, a filestream object must first be created. This will be either an “ofstream” (output filestream) object, for writing data to the file, or an “ifstream” (input filestream) object, for reading data from the file. The ofstream object is used like the cout function that writes to standard output, and the ifstream object works like the cin function that reads from standard input.

The declaration of a filestream object for writing output begins with the ofstream keyword, then a chosen name for that particular filestream object followed by parentheses nominating the text file to write to. So, the declaration syntax looks like this:

ofstream object-name ( “file-name” ) ;

The argument nominating the text file may optionally contain the full file path, such as “C:\data\log.txt” or “/home/user/log.txt”, otherwise the program will seek the file within the directory in which the program resides.

Before writing output to a file, the program should always first test that the filestream object has actually been created. Typically, this is performed by an if statement that allows the program to write output only when the test is successful.

If a nominated file already exists, it will by default be overwritten without warning. Otherwise, a new file will be created and written.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.