C++ Programming Code Examples
C++ > File Operations Code Examples
C++ Programming Code to Merge Two Files
/* C++ Programming Code to Merge Two Files
To merge two files in C++ programming, you have to ask to the user to enter the three file name with extension. Now first open the two file and start copying the content of first file to the third file(target file) after this start appending the content of second file to the third file (target file) as shown here in the following program.
Following C++ program merge two files and store the content of both file into another file. So the following C++ program ask to the user to enter three file names. First file name and second file name (say file1.txt and file2.txt), then Third file name that is used to store the content of the two file (say filet.txt). So the following C++ program merge the two file and write it into the third file :
C++ Program - Merge Two Files */
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>
#include<stdlib.h>
void main()
{
clrscr();
ifstream ifiles1, ifiles2;
ofstream ifilet;
char ch, fname1[20], fname2[20], fname3[30];
cout<<"Enter first file name (with extension like file1.txt) : ";
gets(fname1);
cout<<"Enter second file name (with extension like file2.txt) : ";
gets(fname2);
cout<<"Enter name of file (with extension like file3.txt) which will store the contents of the two files (fname1 and fname1) : ";
gets(fname3);
ifiles1.open(fname1);
ifiles2.open(fname2);
if(ifiles1==NULL || ifiles2==NULL)
{
perror("Error Message ");
cout<<"Press any key to exit...\n";
getch();
exit(EXIT_FAILURE);
}
ifilet.open(fname3);
if(!ifilet)
{
perror("Error Message ");
cout<<"Press any key to exit...\n";
getch();
exit(EXIT_FAILURE);
}
while(ifiles1.eof()==0)
{
ifiles1>>ch;
ifilet<<ch;
}
while(ifiles2.eof()==0)
{
ifiles2>>ch;
ifilet<<ch;
}
cout<<"The two files were merged into "<<fname3<<" file successfully..!!";
ifiles1.close();
ifiles2.close();
ifilet.close();
getch();
}
Check whether eofbit is set. Returns true if the eofbit error state flag is set for the stream. This flag is set by all standard input operations when the End-of-File is reached in the sequence associated with the stream. Note that the value returned by this function depends on the last operation performed on the stream (and not on the next). Operations that attempt to read at the End-of-File fail, and thus both the eofbit and the failbit end up set. This function can be used to check whether the failure is due to reaching the End-of-File or to some other reason.
It is a predefined function in "conio.h" (console input output header file) used to clear the console screen. It is a predefined function, by using this function we can clear the data from console (Monitor). Using of clrscr() is always optional but it should be place after variable or function declaration only. It is often used at the beginning of the program (mostly after variable declaration but not necessarily) so that the console is clear for our output.
Get string from stdin. Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached. The newline character, if found, is not copied into str. A terminating null character is automatically appended after the characters copied to str. Notice that gets is quite different from fgets: not only gets uses stdin as source, but it does not include the ending newline character in the resulting string and does not allow to specify a maximum size for str (which can lead to buffer overflows). On success, the function returns str.
Get type name. name() returns a null-terminated character sequence that may identify the type. The particular representation pointed by the returned value is implementation-defined, and may or may not be different for different types. This function does not accept any parameter.
In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop. The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.
Logical Operators are used to compare and connect two or more expressions or variables, such that the value of the expression is completely dependent on the original expression or value or variable. We use logical operators to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0. Assume variable A holds 1 and variable B holds 0:
The cout is a predefined object of ostream class. It is connected with the standard output device, which is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to display the output on a console. On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout. The "c" in cout refers to "character" and "out" means "output". Hence cout means "character output". The cout object is used along with the insertion operator << in order to display a stream of characters.
The exit function terminates the program normally. Automatic objects are not destroyed, but static objects are. Then, all functions registered with atexit are called in the opposite order of registration. The code is returned to the operating system. An exit code of 0 or EXIT_SUCCESS means successful completion. If code is EXIT_FAILURE, an indication of program failure is returned to the operating system. Other values of code are implementation-defined. Calls all functions registered with the atexit() function, and destroys C++ objects with static storage duration, all in last-in-first-out (LIFO) order. C++ objects with static storage duration are destroyed in the reverse order of the completion of their constructor. (Automatic objects are not destroyed as a result of calling exit().)
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.
In C++ programming we are using the iostream standard library, it provides cin and cout methods for reading from input and writing to output respectively. To read and write from a file we are using the standard C++ library called fstream. Let us see the data types define in fstream library is: • ofstream: This data type represents the output file stream and is used to create files and to write information to files. • ifstream: This data type represents the input file stream and is used to read information from files. • fstream: This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.
In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.
Print error message. Interprets the value of errno as an error message, and prints it to stderr (the standard error output stream, usually the console), optionally preceding it with the custom message specified in str. errno is an integral variable whose value describes the error condition or diagnostic information produced by a call to a library function (any function of the C standard library may set a value for errno, even if not explicitly specified in this reference, and even if no error happened), see errno for more info. The error message produced by perror is platform-depend. If the parameter str is not a null pointer, str is printed followed by a colon (:) and a space. Then, whether str was a null pointer or not, the generated error description is printed followed by a newline character ('\n').
A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.
Open file. Opens the file identified by argument filename, associating it with the stream object, so that input/output operations are performed on its content. Argument mode specifies the opening mode. If the stream is already associated with a file (i.e., it is already open), calling this function fails. The file association of a stream is kept by its internal stream buffer: Internally, the function calls rdbuf()->open(filename,mode). The function clears the stream's state flags on success (setting them to goodbit). In case of failure, failbit is set.
The getch() is a predefined non-standard function that is defined in conio.h header file. It is mostly used by the Dev C/C++, MS- DOS's compilers like Turbo C to hold the screen until the user passes a single value to exit from the console screen. It can also be used to read a single byte character or string from the keyboard and then print. It does not hold any parameters. It has no buffer area to store the input character in a program. The getch() function does not accept any parameter from the user. It returns the ASCII value of the key pressed by the user as an input.
Your program should always generates a new sequence of random number. You need to set a seed to random generator according to the current time. It can be done in the following
Program should display all 'random elements' of array and minimum and maximum number in array on screen. Array size is fixed to 100 to change the size just change the 'Value of size'
We have to enter some set of numbers. Now to find occurrence of positive, negative, zero from the given set of numbers, just check all the numbers using for loop whether number