Microsoft Visual C++ (often abbreviated as MSVC) is a commercial integrated development environment (IDE) product engineered by Microsoft for the C, C++, and C++/CLI programming languages. It has tools for developing and debugging C++ code, especially code written for the Microsoft Windows API, the DirectX API, and the Microsoft .NET Framework.
The predecessor to Visual C++ was called Microsoft C/C++. There was also a Microsoft QuickC 2.5 and a Microsoft QuickC for Windows 1.0.
Visual C++ 1.0, which included MFC 2.0, was the first version of Visual C++, released in 1992, available in both 16-bit and 32-bit versions.
Visual C++ 1.5, which included MFC 2.5, added OLE 2.0 and ODBC support to MFC. It was 16-bit only and was the first version of Visual C++ that came only on CD-ROM.
Visual C++ 1.52c was a patched version of 1.5, but deserves its own entry since it is the last, and arguably most popular, development platform for Microsoft Windows 3.x. It is available through Microsoft Developer Network.
Visual C++ 2.0, which included MFC 3.0, was the first version to be 32-bit only. In many ways, this version was ahead of its time because Windows 95, then codenamed "Chicago", was not released, and Windows NT had only a small market share. As a result, this release was almost a "lost generation". Updates available through subscription included version 2.1 and 2.2. Microsoft included and updated Visual C++ 1.5 as part of the 2.x releases up to 2.1, which included Visual C++ 1.52, and both 16-bit and 32-bit version of the Control Development Kit (CDK) were included. Visual C++ 2.x also supported Win32s development. It is available through Microsoft Developer Network. There was a Visual C++ 2.0 RISC Edition for MIPS and Alpha processors, as well as a cross-platform edition for the Macintosh (68000 instruction set).
Visual C++ 4.0, which included MFC 4.0, was designed for Windows 95 and Windows NT. To allow support of legacy (Windows 3.x/DOS) projects, 4.0 came bundled with the Visual C++ 1.52 installation CD. Updates available through subscription included Visual C++ 4.1, which came with the Microsoft Game SDK (later released separately as the DirectX SDK), and Visual C++ 4.2. 4.2 did not support Windows 3.x (Win32s) development. This was the final version with a cross-platform edition for the Macintosh available and it differed from the 2.x version in that it also allowed compilation for the PowerPC instruction set.
Visual C++ 5.0, which included MFC 4.21, was a major upgrade from 4.2.
Visual C++ 6.0 (commonly known as VC6), which included MFC 6.0, was released in 1998. The release was somewhat controversial since it did not include an expected update to MFC. Visual C++ 6.0 is still quite popular and often used to maintain legacy projects. There are however issues with this version under Windows XP, especially under the debugging mode (ex: the values of static variables do not display). The debugging issues can be solved with a patch called the "Visual C++ 6.0 Processor Pack" downloadable from http://msdn2.microsoft.com/en-us/vstudio/aa718349.aspx; This page stresses that Users must also be running Windows 98, Windows NT 4.0, or Windows 2000.'
Visual C++ .NET 2002 (known also as Visual C++ 7.0), which included MFC 7.0, was released in 2002 with support for link time code generation and debugging runtime checks, .NET 1.0 and Visual C# and Managed C++. The new user interface used many of the hot keys and conventions of Visual Basic, which accounted for some of its unpopularity among C++ developers.
Visual C++ .NET 2003 (known also as Visual C++ 7.1), which included MFC 7.1, was released in 2003 along with.NET 1.1 and was a major upgrade to Visual C++ .NET 2002. It was considered a patch to Visual C++ .NET 2002. Accordingly, the English language upgrade version of Visual Studio .NET 2003 shipped for minimal cost to owners of the English language version of Visual Studio .NET 2002. This is the last version to support Windows 95 as a target.
eMbedded Visual C++ in various versions was used to develop for some versions of the Windows CE operating system. Initially it replaced a development environment consisting of tools added onto Visual C++ 6.0. eMbedded Visual C++ was replaced as a separate development environment by Microsoft Visual Studio 2005.
Visual C++ 2005 (known also as Visual C++ 8.0), which included MFC 8.0, was released in November 2005. This version supports .NET 2.0 and dropped Managed C++ for C++/CLI. It also introduced OpenMP. With Visual C++ 2005, Microsoft also introduced Team Foundation Server. Visual C++ 8.0 has problems compiling MFC AppWizard projects that were created using Visual Studio 6.0, so maintenance of legacy projects can be continued with the original IDE if rewriting was not feasible.
Visual C++ 2008 (known also as Visual C++ 9.0) was released in November 2007. This version supports .NET 3.5, and it is currently the latest stable release. By default, all applications compiled against the Visual C++ 2008 Runtimes (static and dynamic linking) will only work under Windows 2000 and later.[1]
Visual C++ 2010 (known also as Visual C++ 10.0) will be released in the 2009-2010 timeframe. It is currently in development, and available only in the form of a Community Technology Preview. The Visual C++ team is considering using a SQL Server Compact database to store information about the source code, including IntelliSense information, for better IntelliSense and code-completion support.[2] This version adds a modern C++ parallel computing library called the Parallel Patterns Library, partial support for C++0x, and significantly improved IntelliSense. This version is built around .NET 4.0, but still supports compiling to Machine Code.
Current editions
There are four current versions of Visual C++ available:
Microsoft Visual C++ 2008 Express Edition
Microsoft Visual Studio 2008 Standard
Microsoft Visual Studio 2008 Professional
Microsoft Visual Studio 2008 Team System
Visual C++ is included in Visual Studio.
Microsoft Visual C++ 2008 Express is available as a free download at the MSDN site.
Microsoft Visual C++ 2005 Express is available as a free download at the MSDN site under "Previous Version".
Visual C++ 2008 Express
This Microsoft Visual C++ (or Visual C++ 9.0) is available in two flavors: as a part of Microsoft Visual Studio and as a standalone "Express Edition" product. Both should be available for MSDN subscribers and were released officially in November of 2007.
Microsoft Visual C++ 2008 Express Edition is available from the Microsoft Developer Network (MSDN) web site as a free download.
Friday, June 12, 2009
Tuesday, June 9, 2009
Dev C++
Dev-C++ is a free integrated development environment (IDE) distributed under the GNU General Public License for programming in C/C++. It is bundled with MinGW, a free compiler. The IDE is written in Delphi.
The project is hosted by SourceForge. Dev-C++ was originally developed by programmer Colin Laplace. Dev-C++ runs exclusively on Microsoft Windows.
Bloodshed Dev-C++ is a full-featured Integrated Development Environment (IDE) for the C/C++ programming language. It uses the MinGW port of the GCC (GNU Compiler Collection) as its compiler. Dev-C++ can also be used in combination with Cygwin or any other GCC-based compiler.[1]
The program itself has a look-and-feel similar to that of the more widely-used Microsoft Visual Studio. One additional aspect of Dev-C++ is its use of DevPaks, packaged extensions on the programming environment with additional libraries, templates, and utilities. DevPaks often contain, but are not limited to, GUI utilities, including popular toolkits such as GTK+, wxWidgets, and FLTK. Other DevPaks include libraries for more advanced function use.
Dev-C++ is generally considered a Windows-only program. There is also a Linux version available, but it is in alpha and has not been updated since July 2002.
Devpaks
Devpaks.org is a site from which users of Dev-C++ can download additional libraries, or packages of code that increase the scope and functionality of Dev-C++, such as graphics, compression, animation, sound support and many more. On the site, Devpaks are defined as "Libraries (especially open source libraries) are typically distributed as sources. This is convenient, but it can be difficult or time consuming to compile such a library. So the creators of Dev-C++ introduced devpak -- development package, which contains precompiled version of a library, so even a beginner can use them. Dev-C++ also includes several tools for downloading, installing and creating packages." Users can create Devpaks and host them free on the site. Also, they are not limited to use with Dev C++. The site says "A typical devpak will work with any MinGW distribution (with any IDE for MinGW). Simply rename the file from something.devpak to something.tar.bz2 and open it with an archiver (e.g. 7-zip). You will see one file with some meta information (name, version, author etc.) and a directory. Simply unpack the contents of the directory to your MinGW directory tree. The Code::Blocks IDE has plugin for installing and manipulating devpaks." (All quotes from this paragraph are quoted from Devpaks.org)
Development status
The project is no longer noticeably active, with no news posted nor any updated versions released since February 22, 2005. However there is a development team that has taken the Dev-C++ IDE and added new features such as support for multiple compilers and a RAD designer for wxWidgets applications. This IDE can be found under the name wxDev-C++.
The project is hosted by SourceForge. Dev-C++ was originally developed by programmer Colin Laplace. Dev-C++ runs exclusively on Microsoft Windows.
Bloodshed Dev-C++ is a full-featured Integrated Development Environment (IDE) for the C/C++ programming language. It uses the MinGW port of the GCC (GNU Compiler Collection) as its compiler. Dev-C++ can also be used in combination with Cygwin or any other GCC-based compiler.[1]
The program itself has a look-and-feel similar to that of the more widely-used Microsoft Visual Studio. One additional aspect of Dev-C++ is its use of DevPaks, packaged extensions on the programming environment with additional libraries, templates, and utilities. DevPaks often contain, but are not limited to, GUI utilities, including popular toolkits such as GTK+, wxWidgets, and FLTK. Other DevPaks include libraries for more advanced function use.
Dev-C++ is generally considered a Windows-only program. There is also a Linux version available, but it is in alpha and has not been updated since July 2002.
Devpaks
Devpaks.org is a site from which users of Dev-C++ can download additional libraries, or packages of code that increase the scope and functionality of Dev-C++, such as graphics, compression, animation, sound support and many more. On the site, Devpaks are defined as "Libraries (especially open source libraries) are typically distributed as sources. This is convenient, but it can be difficult or time consuming to compile such a library. So the creators of Dev-C++ introduced devpak -- development package, which contains precompiled version of a library, so even a beginner can use them. Dev-C++ also includes several tools for downloading, installing and creating packages." Users can create Devpaks and host them free on the site. Also, they are not limited to use with Dev C++. The site says "A typical devpak will work with any MinGW distribution (with any IDE for MinGW). Simply rename the file from something.devpak to something.tar.bz2 and open it with an archiver (e.g. 7-zip). You will see one file with some meta information (name, version, author etc.) and a directory. Simply unpack the contents of the directory to your MinGW directory tree. The Code::Blocks IDE has plugin for installing and manipulating devpaks." (All quotes from this paragraph are quoted from Devpaks.org)
Development status
The project is no longer noticeably active, with no news posted nor any updated versions released since February 22, 2005. However there is a development team that has taken the Dev-C++ IDE and added new features such as support for multiple compilers and a RAD designer for wxWidgets applications. This IDE can be found under the name wxDev-C++.
Turbo c++
Turbo C++ is a C++ compiler and integrated development environment (IDE) originally from Borland. It is currently distributed by Embarcadero Technologies, which acquired all of Borland's compiler tools with the purchase of its CodeGear division in 2008. The original Turbo C++ product line was put on hold after 1994, and was revived in 2006 as an introductory-level IDE, essentially a stripped-down version of their flagship C++ Builder. Turbo C++ 2006 was released on September 5, 2006 and is available in 'Explorer' and 'Professional' editions. The Explorer edition is free to download and distribute while the Professional edition is a commercial product. The professional edition is no longer available for purchase from Borland.
Historical versions
The first release of Turbo C++ was made available during the MS-DOS reign on personal computers. It came up in versions 1.0, running on OS/2 and version 1.01, released on February 28, 1991 [1], running on MS-DOS. The latter was able to generate both COM and EXE programs, and was shipped with Borland's Turbo Assembler compiler for Intel x86 processors. The initial version of the Turbo C++ compiler was based on a front end developed by TauMetric (TauMetric was later acquired by Sun Microsystems and their front end was incorporated in Sun C++ 4.0, which shipped in 1994).This compiler supported the AT&T 2.0 release of C++.
Turbo C++ 3.0 was released in 1991 (shipping on November 20), and came in amidst expectations of the coming release of Turbo C++ for Microsoft Windows. Initially released as an MS-DOS compiler, 3.0 supported C++ templates, Borland's inline assembler, and generation of MS-DOS mode executables for both 8086 real-mode & 286-protected (as well as the Intel 80186.) 3.0's implemented AT&T C++ 2.1, the most recent at the time. The separate Turbo Assembler product was no longer included, but the inline-assembler could stand in as a reduced functionality version.
Soon after the release of Windows 3.0, Borland updated Turbo C++ to support Windows application development. The Turbo C++ 3.0 for Windows product was quickly followed by Turbo C++ 3.1 (and then Turbo C++ 4.5). It's possible that the jump from version 1.x to version 3.x was in part an attempt to link Turbo C++ release numbers with Microsoft Windows versions; however, it seems more likely that this jump was simply to synchronize Turbo C and Turbo C++, since Turbo C 2.0 (1989) and Turbo C++ 1.0 (1990) had come out roughly at the same time, and the next generation 3.0 was a merger of both the C and C++ compiler.
Starting with version 3.0, Borland segmented their C++ compiler into two distinct product-lines: "Turbo C++" and "Borland C++". Turbo C++ was marketed toward the hobbyist and entry-level compiler market, while Borland C++ targeted the professional application development market. Borland C++ included additional tools, compiler code-optimization, and documentation to address the needs of commercial developers. Turbo C++ 3.0 could be upgraded with separate add-ons, such as Turbo Assembler and Turbovision 1.0.
Version 4.0 was released in November 1993 and was notable (among other things) for its robust support of templates. In particular, Borland C++ 4 was instrumental in the development of the Standard Template Library, expression templates, and the first advanced applications of template metaprogramming. With the success of the Pascal-evolved product "Delphi", Borland ceased work on their Borland C++ suite and concentrated on C++ Builder for Windows. C++ Builder shared Delphi's front-end application framework, but retained the Borland C++ back-end compiler. Active development on Borland C++/Turbo C++ was suspended until 2006 (see below.)
Legacy software
Turbo C++ v1.01 and Turbo C v2.0 can be downloaded, free of charge, from Borland's Antique Software website.
Turbo C++ 3.0 (DOS) was included in the Turbo C++ Suite 1.0, which is no longer sold by Borland. Turbo C++ 3.0 (DOS) can be downloaded from http://vetusware.com.
Historical versions
The first release of Turbo C++ was made available during the MS-DOS reign on personal computers. It came up in versions 1.0, running on OS/2 and version 1.01, released on February 28, 1991 [1], running on MS-DOS. The latter was able to generate both COM and EXE programs, and was shipped with Borland's Turbo Assembler compiler for Intel x86 processors. The initial version of the Turbo C++ compiler was based on a front end developed by TauMetric (TauMetric was later acquired by Sun Microsystems and their front end was incorporated in Sun C++ 4.0, which shipped in 1994).This compiler supported the AT&T 2.0 release of C++.
Turbo C++ 3.0 was released in 1991 (shipping on November 20), and came in amidst expectations of the coming release of Turbo C++ for Microsoft Windows. Initially released as an MS-DOS compiler, 3.0 supported C++ templates, Borland's inline assembler, and generation of MS-DOS mode executables for both 8086 real-mode & 286-protected (as well as the Intel 80186.) 3.0's implemented AT&T C++ 2.1, the most recent at the time. The separate Turbo Assembler product was no longer included, but the inline-assembler could stand in as a reduced functionality version.
Soon after the release of Windows 3.0, Borland updated Turbo C++ to support Windows application development. The Turbo C++ 3.0 for Windows product was quickly followed by Turbo C++ 3.1 (and then Turbo C++ 4.5). It's possible that the jump from version 1.x to version 3.x was in part an attempt to link Turbo C++ release numbers with Microsoft Windows versions; however, it seems more likely that this jump was simply to synchronize Turbo C and Turbo C++, since Turbo C 2.0 (1989) and Turbo C++ 1.0 (1990) had come out roughly at the same time, and the next generation 3.0 was a merger of both the C and C++ compiler.
Starting with version 3.0, Borland segmented their C++ compiler into two distinct product-lines: "Turbo C++" and "Borland C++". Turbo C++ was marketed toward the hobbyist and entry-level compiler market, while Borland C++ targeted the professional application development market. Borland C++ included additional tools, compiler code-optimization, and documentation to address the needs of commercial developers. Turbo C++ 3.0 could be upgraded with separate add-ons, such as Turbo Assembler and Turbovision 1.0.
Version 4.0 was released in November 1993 and was notable (among other things) for its robust support of templates. In particular, Borland C++ 4 was instrumental in the development of the Standard Template Library, expression templates, and the first advanced applications of template metaprogramming. With the success of the Pascal-evolved product "Delphi", Borland ceased work on their Borland C++ suite and concentrated on C++ Builder for Windows. C++ Builder shared Delphi's front-end application framework, but retained the Borland C++ back-end compiler. Active development on Borland C++/Turbo C++ was suspended until 2006 (see below.)
Legacy software
Turbo C++ v1.01 and Turbo C v2.0 can be downloaded, free of charge, from Borland's Antique Software website.
Turbo C++ 3.0 (DOS) was included in the Turbo C++ Suite 1.0, which is no longer sold by Borland. Turbo C++ 3.0 (DOS) can be downloaded from http://vetusware.com.
Friday, June 5, 2009
File Handling
C++ provides the following classes to perform output and input of characters to/from files:
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
These classes are derived directly or indirectly from the classes istream, and ostream. We have already used objects whose types were these classes: cin is an object of class istream and cout is an object of class ostream. Therfore, we have already been using classes that are related to our file streams. And in fact, we can use our file streams the same way we are already used to use cin and cout, with the only difference that we have to associate these streams with physical files. Let's see an example:
// basic file operations
#include
#include
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
OUTPUT:
[file example.txt]
Writing this to a file
This code creates a file called example.txt and inserts a sentence into it in the same way we are used to do with cout, but using the file stream myfile instead.
But let's go step by step:
Open a file
The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream object (an instantiation of one of these classes, in the previous example this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it.
In order to open a file with a stream object we use its member function open():
open (filename, mode);
Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:
ios::in Open for input operations.
ios::out Open for output operations.
ios::binary Open in binary mode.
ios::ate Set the initial position at the end of the file.
If this flag is not set to any value, the initial position is the beginning of the file.
ios::app All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.
ios::trunc If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.
All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open():
ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary);
Each one of the open() member functions of the classes ofstream, ifstream and fstream has a default mode that is used if the file is opened without a second argument:
class default mode parameter
ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out
For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to the open() member function.
The default value is only applied if the function is called without specifying any value for the mode parameter. If the function is called with any value in that parameter the default mode is overridden, not combined.
File streams opened in binary mode perform input and output operations independently of any format considerations. Non-binary files are known as text files, and some translations may occur due to formatting of some special characters (like newline and carriage return characters).
Since the first task that is performed on a file stream object is generally to open a file, these three classes include a constructor that automatically calls the open() member function and has the exact same parameters as this member. Therefore, we could also have declared the previous myfile object and conducted the same opening operation in our previous example by writing:
ofstream myfile ("example.bin", ios::out | ios::app | ios::binary);
Combining object construction and stream opening in a single statement. Both forms to open a file are valid and equivalent.
To check if a file stream was successful opening a file, you can do it by calling to member is_open() with no arguments. This member function returns a bool value of true in the case that indeed the stream object is associated with an open file, or false otherwise:
if (myfile.is_open()) { /* ok, proceed with output */ }
Closing a file
When we are finished with our input and output operations on a file we shall close it so that its resources become available again. In order to do that we have to call the stream's member function close(). This member function takes no parameters, and what it does is to flush the associated buffers and close the file:
myfile.close();
Once this member function is called, the stream object can be used to open another file, and the file is available again to be opened by other processes.
In case that an object is destructed while still associated with an open file, the destructor automatically calls the member function close().
Text files
Text file streams are those where we do not include the ios::binary flag in their opening mode. These files are designed to store text and thus all values that we input or output from/to them can suffer some formatting transformations, which do not necessarily correspond to their literal binary value.
Data output operations on text files are performed in the same way we operated with cout:
// writing on a text file
#include
#include
using namespace std;
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
} [file example.txt]
OUTPUT:
This is a line.
This is another line.
Data input from a file can also be performed in the same way that we did with cin:
// reading a text file
#include
#include
#include
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
OUTPUT:
This is a line.
This is another line.
This last example reads a text file and prints out its content on the screen. Notice how we have used a new member function, called eof() that returns true in the case that the end of the file has been reached. We have created a while loop that finishes when indeed myfile.eof() becomes true (i.e., the end of the file has been reached).
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
These classes are derived directly or indirectly from the classes istream, and ostream. We have already used objects whose types were these classes: cin is an object of class istream and cout is an object of class ostream. Therfore, we have already been using classes that are related to our file streams. And in fact, we can use our file streams the same way we are already used to use cin and cout, with the only difference that we have to associate these streams with physical files. Let's see an example:
// basic file operations
#include
#include
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
OUTPUT:
[file example.txt]
Writing this to a file
This code creates a file called example.txt and inserts a sentence into it in the same way we are used to do with cout, but using the file stream myfile instead.
But let's go step by step:
Open a file
The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream object (an instantiation of one of these classes, in the previous example this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it.
In order to open a file with a stream object we use its member function open():
open (filename, mode);
Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:
ios::in Open for input operations.
ios::out Open for output operations.
ios::binary Open in binary mode.
ios::ate Set the initial position at the end of the file.
If this flag is not set to any value, the initial position is the beginning of the file.
ios::app All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.
ios::trunc If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.
All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open():
ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary);
Each one of the open() member functions of the classes ofstream, ifstream and fstream has a default mode that is used if the file is opened without a second argument:
class default mode parameter
ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out
For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to the open() member function.
The default value is only applied if the function is called without specifying any value for the mode parameter. If the function is called with any value in that parameter the default mode is overridden, not combined.
File streams opened in binary mode perform input and output operations independently of any format considerations. Non-binary files are known as text files, and some translations may occur due to formatting of some special characters (like newline and carriage return characters).
Since the first task that is performed on a file stream object is generally to open a file, these three classes include a constructor that automatically calls the open() member function and has the exact same parameters as this member. Therefore, we could also have declared the previous myfile object and conducted the same opening operation in our previous example by writing:
ofstream myfile ("example.bin", ios::out | ios::app | ios::binary);
Combining object construction and stream opening in a single statement. Both forms to open a file are valid and equivalent.
To check if a file stream was successful opening a file, you can do it by calling to member is_open() with no arguments. This member function returns a bool value of true in the case that indeed the stream object is associated with an open file, or false otherwise:
if (myfile.is_open()) { /* ok, proceed with output */ }
Closing a file
When we are finished with our input and output operations on a file we shall close it so that its resources become available again. In order to do that we have to call the stream's member function close(). This member function takes no parameters, and what it does is to flush the associated buffers and close the file:
myfile.close();
Once this member function is called, the stream object can be used to open another file, and the file is available again to be opened by other processes.
In case that an object is destructed while still associated with an open file, the destructor automatically calls the member function close().
Text files
Text file streams are those where we do not include the ios::binary flag in their opening mode. These files are designed to store text and thus all values that we input or output from/to them can suffer some formatting transformations, which do not necessarily correspond to their literal binary value.
Data output operations on text files are performed in the same way we operated with cout:
// writing on a text file
#include
#include
using namespace std;
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
OUTPUT:
This is a line.
This is another line.
Data input from a file can also be performed in the same way that we did with cin:
// reading a text file
#include
#include
#include
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
OUTPUT:
This is a line.
This is another line.
This last example reads a text file and prints out its content on the screen. Notice how we have used a new member function, called eof() that returns true in the case that the end of the file has been reached. We have created a while loop that finishes when indeed myfile.eof() becomes true (i.e., the end of the file has been reached).
Thursday, June 4, 2009
Dynamic Memory Allocation
Consider a array declaration
int marks[100];
Such a declaration would typically be used if 100 student's marks were to be stored in memory. The moment we make this declaration 200 bytes are reserved in the memory for storing 100 integers in it. However it mayso happen that when we actally run the program, we might be interested in storing only 60 students marks.Even in this case 200 bytes would get reserved in the memory, which would result in wastage of memory.
Other way round there always exist a possibility that when you run the program you need to store more than 100 students marks. In this case the array would fall short in size. Moreover there is no way to increase or decrease the array size during execution of the program. In other words,when we use array, static memory allocation takes place. What if we want to allocate memory only at the time of execution? This is dome using standard library functions malloc() and calloc(). Since these functions allocate memory on the fly(during execution) they are often known as 'dynamic memory allocation functions'. Let us now see a program, which uses the concept of dynamic memory allocation.
#include
main()
{
int n,avg,i,*p,sum=0;
cout<<"Enter the number of students";
cin>>n;
p=(int *)malloc(n*2);
if(p==NULL)
{cout<<"memory allocation unsuccessful";
exit();
}
for(i=0;i cout<for(i=0;i sum=sum+*(p+i);
avg=sum/n;
cout<<"average marks"< }
Here we have first asked for the number of students whose marks are to be entered and then allocated only as much memory as it is really required to store these marks. Not a byte more, not a byte less. The allocation job is done using the standard library function malloc().malloc() returns a NULL if memory allocation is unsuccessful. If successful it returns the address of the memory chunk that is allocated. We have collected this address in an integer pointer p. Since malloc() returns a void pointer we have typecasted it into a integer pointer. In the first for loop using simple pointer arithmatic we have stored the marks entered form the keyboard into the memory that has been allocated. In the second for loop we have accessed the same values to find the average marks
The calloc()function works exactly similar to malloc() except for the fact that it needs two arguments. for example,
int *p;
p=(int*)calloc(10,2);
Here 2 indicates that we wish to allocate memory for storing integers,(since an integer takes 2 bytes entity) and 10 indicates that we want to reserve space for storing 10 integers. Another minor difference between malloc() and calloc() is that, by default, the memory allocated by malloc() contains garbage values, whereas that allocated by calloc() contains all zeros. While using these functins it is necessary to include the file at the beginning of the program.
int marks[100];
Such a declaration would typically be used if 100 student's marks were to be stored in memory. The moment we make this declaration 200 bytes are reserved in the memory for storing 100 integers in it. However it mayso happen that when we actally run the program, we might be interested in storing only 60 students marks.Even in this case 200 bytes would get reserved in the memory, which would result in wastage of memory.
Other way round there always exist a possibility that when you run the program you need to store more than 100 students marks. In this case the array would fall short in size. Moreover there is no way to increase or decrease the array size during execution of the program. In other words,when we use array, static memory allocation takes place. What if we want to allocate memory only at the time of execution? This is dome using standard library functions malloc() and calloc(). Since these functions allocate memory on the fly(during execution) they are often known as 'dynamic memory allocation functions'. Let us now see a program, which uses the concept of dynamic memory allocation.
#include
main()
{
int n,avg,i,*p,sum=0;
cout<<"Enter the number of students";
cin>>n;
p=(int *)malloc(n*2);
if(p==NULL)
{cout<<"memory allocation unsuccessful";
exit();
}
for(i=0;i
avg=sum/n;
cout<<"average marks"<
Here we have first asked for the number of students whose marks are to be entered and then allocated only as much memory as it is really required to store these marks. Not a byte more, not a byte less. The allocation job is done using the standard library function malloc().malloc() returns a NULL if memory allocation is unsuccessful. If successful it returns the address of the memory chunk that is allocated. We have collected this address in an integer pointer p. Since malloc() returns a void pointer we have typecasted it into a integer pointer. In the first for loop using simple pointer arithmatic we have stored the marks entered form the keyboard into the memory that has been allocated. In the second for loop we have accessed the same values to find the average marks
The calloc()function works exactly similar to malloc() except for the fact that it needs two arguments. for example,
int *p;
p=(int*)calloc(10,2);
Here 2 indicates that we wish to allocate memory for storing integers,(since an integer takes 2 bytes entity) and 10 indicates that we want to reserve space for storing 10 integers. Another minor difference between malloc() and calloc() is that, by default, the memory allocated by malloc() contains garbage values, whereas that allocated by calloc() contains all zeros. While using these functins it is necessary to include the file
Subscribe to:
Posts (Atom)