Reading C-Style Strings

To read C-style strings, you can use the getline function. (This is an overload version of the getline function discussed in the previous section.) This getline member function is defined as:

std::istream& getline(char *buffer, int len, char delim = '\n')

The parameters to this function are:

buffer
A C-style string in which to store the data that has been read.

len
Length of the buffer in bytes. The function reads up to len-1 bytes of data into the buffer. (One byte is reserved for the terminating null character \0.) This parameter is usually sizeof(buffer).

delim
The character used to signal end-of-line.

This function returns a reference to the input file. The function reads up to and including the end-of-line character ('\n'). The end-of-line character is not stored in the buffer. (An end-of-string ('\0') is store in to terminate the string.)

For example:

char buffer[30];
 
std::cin.getline(buffer, sizeof(buffer));

Output Files

The functions for output files are similar to input files. For example, the declaration:

std::ofstream out_file("out.dat");

creates a file named out.dat and lets you write to the file using the file variable out_file.

Actually, the constructor can take two additional arguments. The full definition of the output file constructor is:

std::ofstream::ofstream(const char *name, int mode=std::ios::out, 
                   int prot = filebuf::openprot);

The parameters for this function are:

name
The name of the file.

mode
A set of flags ORed together that determine the open mode. The flag std::ios::out is required for output files. Other flags are listed in Table 16-2. (The std::ios:: prefix is used to indicate the scope of the constant. This operator is discussed in more detail in Chapter 21.)

prot
File protection. This is an operating system-dependent value that determines the protection mode for the file. In Unix the protection defaults to 0644 (read/write owner, group read, others read). For MS-DOS/Windows this defaults to 0 (normal file).

Table 16-2: Open flags

Flag

Meaning

std::ios::app

Append data to the end of the output file.

std::ios::ate

Go to the end of the file when opened.

std::ios::in

Open for input (must be supplied to the open member function of std::ifstream variables).

std::ios::out

Open file for output (must be supplied to the open member function of std::ofstream variables).

std::ios::binary

Binary file (if not present, the file is opened as an ASCII file). See the later section "Binary I/O" for a definition of a binary file.

std::ios::trunc

Discard contents of existing file when opening for write.

std::ios::nocreate

Fail if the file does not exist. (Output files only. Opening an input file always fails if there is no file.)

std::ios::noreplace

Do not overwrite existing file. If a file exists, cause the open to fail.

For example, the statement:

std::ofstream out_file("data.new", std::ios::out|std::ios::binary|std::ios::nocreate|
                    std::ios::app);

appends (std::ios::app) binary data (std::ios::binary) to an existing file (std::ios::nocreate) named data.new.

Example 16-2 contains a short function that writes a message to a log file. The first thing the function does is to open the file for output (std::ios::out), appending (std::ios::app), with the writing to start at the end of the file (std::ios::ate). It then writes the message and closes the file (the destructor for out_file performs the close).

This function was designed to be simple, which it is. But also we didn't care about efficiency, and as a result this function is terribly inefficient. The problem is that we open and close the file every time we call log_message. Opening a file is an expensive operation, and things would go much faster if we opened the file only once and remembered that we had it open in subsequent calls.

Example 16-2: log/log.cpp

#include <iostream>
#include <fstream>
 
void log_message(const string& msg)
{
    std::ofstream out_file("data.log", 
             std::ios::out|std::ios::app|std::ios::ate);
    if (out_file.bad(  ))
        return; /* Where do we log an error if there is no log */
    out_file << msg << endl;
}

Page:  1   2   3   4   5   6   7   8   9   Next 



Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • The first phase of API management was about realizing the business value of APIs. This next wave of API management enables the hyper-connected enterprise to drive and scale their businesses as API models become more complex and sophisticated. Today, real world product launches begin with an API program and strategy in mind. This API-first approach to development will only continue to increase, driven by an increasingly interconnected web of devices, organizations, and people. To support this rapid growth, …

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds