Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


C++ Programming Code Examples

C++ > File Operations Code Examples

C++ Code to List Files in Current Directory

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/* C++ Code to List Files in Current Directory To list and display/print all the files present inside the current directory in C++ programming, use a pointer say dir of DIR and the pointer say pdir of dirent to open and read directory to print all the files present in the directory as shown here in the following program. Following C++ program ask to the user to press any key to list all the files present inside the current directory. Here all the files display along with serial number like (1=FirstFileName.extension, 2=SecondFileName.extension, 3=ThirdFileName.extension, etc) and it will be separated by comma: C++ Program - List Files in Current Directory */ #include<iostream.h> #include<conio.h> #include<dirent.h> void main() { clrscr(); int done, i=1; DIR *dir; dirent *pdir; cout<<"Press any key to list and view all the files in the current directory : \n"; getch(); dir=opendir("."); while(pdir=readdir(dir)) { cout<<i<<"="pdir->d_name<<", "; i++; } closedir(dir); getch(); }
Standard Output Stream (cout) in C++
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.
Syntax for cout in C++
cout << var_name; //or cout << "Some String";
The syntax of the cout object in C++: cout << var_name; Or cout << "Some String";
<<
is the insertion operator
var_name
is usually a variable, but can also be an array element or elements of containers like vectors, lists, maps, etc. 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 << operator can be used more than once with a combination of variables, strings, and manipulators. cout is used for displaying data on the screen. The operator << called as insertion operator or put to operator. The Insertion operator can be overloaded. Insertion operator is similar to the printf() operation in C. cout is the object of ostream class. Data flow direction is from variable to output device. Multiple outputs can be displayed using cout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* standard output stream (cout) in C++ language */ #include <iostream> using namespace std; int main() { string str = "Do not interrupt me"; char ch = 'm'; // use cout with write() cout.write(str,6); cout << endl; // use cout with put() cout.put(ch); return 0; }
Pointers in C++ Language
The pointer in C++ language is a variable, it is also known as locator or indicator that points to an address of a value. In C++, a pointer refers to a variable that holds the address of another variable. Like regular variables, pointers have a data type. For example, a pointer of type integer can hold the address of a variable of type integer. A pointer of character type can hold the address of a variable of character type. You should see a pointer as a symbolic representation of a memory address. With pointers, programs can simulate call-by-reference. They can also create and manipulate dynamic data structures. In C++, a pointer variable refers to a variable pointing to a specific address in a memory pointed by another variable.
Syntax for Pointers in C++
int *ip; // pointer to an integer double *dp; // pointer to a double float *fp; // pointer to a float char *ch // pointer to character
• Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions. • We can return multiple values from function using pointer. • It makes you able to access any memory location in the computer's memory. Dynamic memory allocation: In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used. Arrays, Functions and Structures: Pointers in C language are widely used in arrays, functions and structures. It reduces the code and improves the performance. & (ampersand sign): Address operator - Determine the address of a variable. * (asterisk sign): Indirection operator - Access the value of an address. The pointer in C++ language can be declared using * (asterisk symbol).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/* pointer is a variable in C++ that holds the address of another variable */ #include <iostream> using namespace std; int main () { int var = 20; // actual variable declaration. int *ip; // pointer variable ip = &var; // store address of var in pointer variable cout << "Value of var variable: "; cout << var << endl; // print the address stored in ip pointer variable cout << "Address stored in ip variable: "; cout << ip << endl; // access the value at the address available in pointer cout << "Value of *ip variable: "; cout << *ip << endl; return 0; }
readdir() Function in C++
Read a directory entry. Returns a pointer to a dirent structure describing the next directory entry in the directory stream associated with dir. A call to readdir() overwrites data produced by a previous call to readdir() or __readdir2() on the same directory stream. Calls for different directory streams do not overwrite each other's data. Each call to readdir() updates the st_atime (access time) field for the directory. A dirent structure contains the character pointer d_name, which points to a string that gives the name of a file in the directory. This string ends in a terminating NULL, and has a maximum of NAME_MAX characters.
Syntax for readdir() Function in C++
#include <dirent.h> struct dirent *readdir(DIR *dirp);
dirp
A pointer to the directory stream to be read. Save the data from readdir(), if required, before calling closedir(), because closedir() frees the data. If the contents of a directory have changed since the directory was opened (files added or removed); a call should be made to rewinddir() so that subsequent readdir() requests can read the new contents. Special behavior for XPG4: If entries for dot or dot-dot exist, one entry will be returned for dot and one entry will be returned for dot-dot; otherwise they will not be returned. After a call to fork(), either the parent or child (but not both) may continue processing the directory stream using __readdir2(), readdir(), rewinddir(), or seekdir(). If both the parent and child processes use these functions, the result is undefined. Special behavior for XPG4.2: If the entry names a symbolic link, the value of d_ino member in dirent structure is unspecified. If successful, readdir() returns a pointer to a dirent structure describing the next directory entry in the directory stream. When readdir() reaches the end of the directory stream, it returns a NULL pointer. If unsuccessful, readdir() returns a NULL pointer and sets errno to one of the following values:
EOVERFLOW
One of the values in the structure to be returned cannot be represented correctly. The readdir() function may fail if:
EBADF
The dirp argument does not refer to an open directory stream.
ENOENT
The current position of the directory stream is invalid. The readdir_r() function may fail if:
EBADF
The dirp argument does not refer to an open directory stream. The environment variable _EDC_SUSV3 can be used to control the behavior of readdir() with respect to detecting an EOVERFLOW condition. By default, readdir() will not detect that values in the structure returned can be represented correctly. When _EDC_SUSV3 is set to 1, readdir() will check for overflow conditions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/* The readdir() function reads the next directory entry from the directory specified by dirp, which is the value returned by a call to opendir(). You can call readdir() repeatedly to list all of the entries contained in the directory specified by the pathname given to opendir(). The closedir() function must be called to close the directory stream and free the memory allocated by opendir(). */ /* Read a directory entry by readdir() function code example */ #include <stdio.h> #include <stdlib.h> #include <dirent.h> int main( void ) { DIR* dirp; struct dirent* direntp; dirp = opendir( "/home/fred" ); if( dirp == NULL ) { perror( "can't open /home/fred" ); } else { for(;;) { direntp = readdir( dirp ); if( direntp == NULL ) break; printf( "%s\n", direntp->d_name ); } closedir( dirp ); } return EXIT_SUCCESS; }
While Loop Statement in C++
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.
Syntax for While Loop Statement in C++
while (condition) { // body of the loop }
• A while loop evaluates the condition • If the condition evaluates to true, the code inside the while loop is executed. • The condition is evaluated again. • This process continues until the condition is false. • When the condition evaluates to false, the loop terminates. Do not forget to increase the variable used in the condition, otherwise the loop will never end!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/* While Loop Statement in C++ language */ // program to find the sum of positive numbers // if the user enters a negative number, the loop ends // the negative number entered is not added to the sum #include <iostream> using namespace std; int main() { int number; int sum = 0; // take input from the user cout << "Enter a number: "; cin >> number; while (number >= 0) { // add all positive numbers sum += number; // take input again if the number is positive cout << "Enter a number: "; cin >> number; } // display the sum cout << "\nThe sum is " << sum << endl; return 0; }
clrscr() Function in C++
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* clrscr() function is also a non-standard function defined in "conio.h" header. This function is used to clear the console screen. 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.*/ #include<iostream.h> #include<conio.h> void main() { int a=10, b=20; int sum=0; clrscr(); // use clrscr() after variable declaration sum=a+b; cout<<"Sum: "<<sum; //clear the console screen clrscr(); getch(); }
opendir() Function in C++
open a directory file. The opendir() function is used in conjunction with the functions readdir() and closedir() to obtain the list of file names contained in the directory specified by dirname. The path indicated by dirname can be either relative to the current working directory, or it can be an absolute path name. The file <dirent.h> contains definitions for the structure dirent and the DIR type. In QNX the dirent structure contains a stat structure in the d_stat member. To speed up applications, which often want both the name and the stat data, a resource manager may return the stat information at the same time the readdir() function is called.
Syntax for opendir() Function in C++
#include <dirent.h> DIR *opendir( const char *dirname );
dirname
The path of the directory to be opened. It can be relative to the current working directory, or an absolute path. However, since the support of this feature is left to the discretion of various resource managers, every program must use the following test to determine if the d_stat member contains valid data: d_stat.st_status & _FILE_USED This test must be performed after every readdir() call. If the d_stat member doesn't contain valid data, and the data is needed then the application should construct the file's pathname and call stat() or lstat(), as appropriate. More than one directory can be read at the same time using the opendir(), readdir(), rewinddir() and closedir() functions. The result of using a directory stream after one of the exec... or spawn ... family of functions is undefined. After a call to the fork() function, either the parent or the child (but not both) may continue processing the directory stream using readdir() or rewinddir() or both. If both the parent and child processes use these functions, the result is undefined. Either or both processes may use closedir(). Function returns a pointer to a DIR structure if successful. This pointer is required for subsequent calls to readdir() to retrieve the file names specified by dirname. The opendir() function returns NULL if dirname is not a valid pathname. If unsuccessful, opendir() returns a NULL pointer and sets errno to one of the following values:
EACCES
Search permission is denied for a component of dirname, or read permission is denied for dirname.
EBADFSYS
While attempting to open the named directory, a component of the path prefix was found to be corrupted. You'll need to invoke appropriate systems-administration procedures to correct this situation before proceeding.
EINTR
The opendir() operation was interrupted by a signal.
EMFILE
Too many file descriptors are currently in use by this process.
ELOOP
Too many levels of symbolic loops (or prefix aliases): an infinite loop is assumed after SYMLOOP_MAX symbolic links or prefixes are encountered.
ENAMETOOLONG
The length of the argument dirname exceeds PATH_MAX, or a pathname component is longer than NAME_MAX.
ENFILE
Too many files are currently open in the system.
ENOENT
The named directory doesn't exist.
ENOMEM
Not enough memory
ENOTDIR
A component of dirname is not a directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
/* opendir() function opens a directory so that it can be read with readdir() or __readdir2(). dirname is a string giving the name of the directory you want to open. The first readdir() or __readdir2() call reads the first entry in the directory. If successful, opendir() returns a pointer to a DIR object. This object describes the directory and is used in subsequent operations on the directory, in the same way that FILE objects are used in file I/O operations. If unsuccessful, opendir() returns a NULL pointer. */ /* Open a directory by opendir() function code example */ #include <stdio.h> #include <stdlib.h> #include <dirent.h> int main( void ) { DIR* dirp; struct dirent* direntp; dirp = opendir( "/home/fred" ); if( dirp == NULL ) { perror( "can't open /home/fred" ); } else { for(;;) { direntp = readdir( dirp ); if( direntp == NULL ) break; printf( "%s\n", direntp->d_name ); } closedir( dirp ); } return EXIT_SUCCESS; }
getch() Function in C++
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.
Syntax for getch() Function in C++
#include <conio.h> int getch(void);
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. We use a getch() function in a C/ C++ program to hold the output screen for some time until the user passes a key from the keyboard to exit the console screen. Using getch() function, we can hide the input character provided by the users in the ATM PIN, password, etc. • getch() method pauses the Output Console until a key is pressed. • It does not use any buffer to store the input character. • The entered character is immediately returned without waiting for the enter key. • The entered character does not show up on the console. • The getch() method can be used to accept hidden inputs like password, ATM pin numbers, etc.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* wait for any character input from keyboard by getch() function code example. The getch() function is very useful if you want to read a character input from the keyboard. */ // C code to illustrate working of // getch() to accept hidden inputs #include<iostream.h> #include<conio.h> void main() { int a=10, b=20; int sum=0; clrscr(); sum=a+b; cout<<"Sum: "<<sum; getch(); // use getch() befor end of main() }
main() Function in C++
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.
Syntax for main() Function in C++
void main() { ............ ............ }
void
void is a keyword in C++ language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
main
main is a name of function which is predefined function in C++ library. In place of void we can also use int return type of main() function, at that time main() return integer type value. 1) It cannot be used anywhere in the program a) in particular, it cannot be called recursively b) its address cannot be taken 2) It cannot be predefined and cannot be overloaded: effectively, the name main in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that a function called "main" cannot be declared with C language linkage in any namespace). 3) It cannot be defined as deleted or (since C++11) declared with C language linkage, constexpr (since C++11), consteval (since C++20), inline, or static. 4) The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;. 5) Execution of the return (or the implicit return upon reaching the end of main) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling std::exit with the same argument as the argument of the return. (std::exit then destroys static objects and terminates the program). 6) (since C++14) The return type of the main function cannot be deduced (auto main() {... is not allowed). 7) (since C++20) The main function cannot be a coroutine.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* simple code example by main() function in C++ */ #include <iostream> using namespace std; int main() { int day = 4; switch (day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; case 3: cout << "Wednesday"; break; case 4: cout << "Thursday"; break; case 5: cout << "Friday"; break; case 6: cout << "Saturday"; break; case 7: cout << "Sunday"; break; } return 0; }
#include Directive in C++
#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.
Syntax for #include Directive in C++
#include "user-defined_file"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
#include <header_file>
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories. Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor. • In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename. • In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename. • You can use only comment after filename otherwise it will give error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* using #include directive in C language */ #include <stdio.h> int main() { /* * C standard library printf function * defined in the stdio.h header file */ printf("I love you Clementine"); printf("I love you so much"); printf("HappyCodings"); return 0; }
C++ Files and Streams
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. To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file.
Opening a File
A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only. File streams in C++ are basically the libraries that are used in the due course of programming. The programmers generally use the iostream standard library in the C++ programming as it provides the cin and cout methods that are used for reading from the input and writing to the output respectively. In order to read and write from a file, the programmers are generally using the standard C++ library that is known as the fstream. Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second argument of the open() member function defines the mode in which the file should be opened. ios::app Append mode. All output to that file to be appended to the end. ios::ate Open a file for output and move the read/write control to the end of the file. ios::in Open a file for reading. ios::out Open a file for writing. ios::trunc If the file already exists, its contents will be truncated before opening the file.
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination. Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program using the stream insertion operator (<<) just as you use that operator to output information to the screen. The only difference is that you use an ofstream or fstream object instead of the cout object.
Reading from a File
You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cin object. 'ifstream' data type of 'fstream' library is used to read the files of C++. But before reading, there are several tasks which are performed sequentially like opening the file, reading and closing it. Different data types are used for the specific purpose. We can simply read the information from the file using the operator ( >> ) with the name of the file. We need to use the fstream or ifstream object in C++ in order to read the file. Reading of the file line by line can be done by simply using the while loop along with the function of ifstream 'getline()'.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
/* C++ files and streams */ /* writing to a file and reading from a file in C++ language */ #include <fstream> #include <iostream> using namespace std; int main () { char data[100]; // open a file in write mode. ofstream outfile; outfile.open("afile.dat"); cout << "Writing to the file" << endl; cout << "Enter your name: "; cin.getline(data, 100); // write inputted data into the file. outfile << data << endl; cout << "Enter your age: "; cin >> data; cin.ignore(); // again write inputted data into the file. outfile << data << endl; // close the opened file. outfile.close(); // open a file in read mode. ifstream infile; infile.open("afile.dat"); cout << "Reading from the file" << endl; infile >> data; // write the data at the screen. cout << data << endl; // again read the data from the file and display it. infile >> data; cout << data << endl; // close the opened file. infile.close(); return 0; }
closedir() Function in C++
close a directory. The closedir() function closes the directory stream associated with dirp. A successful call to closedir() also closes the underlying file descriptor associated with dirp. The directory stream descriptor dirp is not available after this call.
Syntax for closedir() Function in C++
#include <dirent.h> int closedir(DIR *dirp);
dirp
A directory pointer for the directory you want to close. The closedir() function returns 0 on success. On error, -1 is returned, and errno is set appropriately. The result of using a directory stream after calling one of the exec*() or spawn*() family of functions is undefined. After a call to the fork() function, either the parent or the child (but not both) may continue processing the directory stream using the readdir() and rewinddir() functions. If both the parent and child processes use these functions, the result is undefined. Either or both processes may call the closedir() function. The closedir() function may fail if:
EBADF
The dirp argument does not refer to an open directory stream.
EINTR
The closedir() function was interrupted by a signal.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/* The closedir() function shall close the directory stream referred to by the argument dirp. Upon return, the value of dirp may no longer point to an accessible object of the type DIR. If a file descriptor is used to implement type DIR, that file descriptor shall be closed. */ /* close a directory stream by closedir() function code example */ bool doDir(std::string dir) { dirent* pDirent; DIR *pDir; pDir = opendir(dir.c_str()); if(!pDir) { std::cout << "cannot open dir: " << dir.c_str() << '\n'; return false; } while((pDirent = readdir(pDir))) { if(pDirent->d_type == DT_DIR) std::cout << dir.c_str() << pDirent->d_name << '\n'; } closedir(pDir); return true; }


This C++ Program checks whether a directed graph is weakly connected or not. We can do "DFS" V times starting from every vertex. If any DFS, doesn't visit all vertices, then graph
First ask to enter the array size then it will ask to enter the array elements, then it will finally ask to enter a number to be search in array to check whether it is present in the array or not
To convert "Hexadecimal" number to "binary" number in C++, you have to ask to the user to enter the hexadecimal number to convert it into binary number to display the equivalent