Need a project done?

C++ Programming Developer

Search This Blog

Reading link list from File in C++

To Read a link list from file, we've adopted the following procedure:
1. Write each node individually to a file in the function of getData().
2. Read Each node from file one by one and insert it in the link list .


//Reading link list from File in C++

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <conio.h>
#include <Windows.h>
using namespace std;

class linkList{
public:
void getData();
void insert(linkList **head, linkList **tail); // insert at tail
void printAll(linkList *head); // Display all records.
private:
char name[100];
int rollNo;
linkList *next;
};
//````````````````````````````````````````````````````````````````````````````````````````````````````````````
void linkList::getData(){
cout << "Enter Name: "; cin >> name;
cout << "Enter Roll Number: "; cin >> rollNo;
next = NULL;
ofstream os("nodes of my link list.dat", ios::binary | ios::out | ios::app);
os.write( reinterpret_cast <char*> (this), sizeof(*this) );
os.close();
}
//````````````````````````````````````````````````````````````````````````````````````````````````````````````
void linkList::insert(linkList **head, linkList **tail){ // insert at tail
if (*head == NULL && *tail == NULL){
*head = (this);
*tail = (this);
}
else{
(*tail)->next = this;
*tail = this;
}
}
//````````````````````````````````````````````````````````````````````````````````````````````````````````````
void linkList::printAll(linkList *head){
for (linkList *temp = head; temp!=NULL; temp=temp->next){
cout << "Name: " << temp->name << endl
<<  "Roll Number: " << temp->rollNo << endl << endl;
}
}
//````````````````````````````````````````````````````````````````````````````````````````````````````````````
/////////////////////////////////////////////////// Main() //////////////////////////////////////
int main(){
linkList *pointerOfLinkList  = 0, *head = 0, *tail = 0;

ifstream is;
while (true){
cout << "1. Insert Node\n"
<< "2. Print All\n"
<< "0. Press IT to load link list from file.\t";
int opt; cin >> opt;

switch(opt){
case 1:
pointerOfLinkList = new linkList;
pointerOfLinkList->getData();
pointerOfLinkList->insert(&head,&tail);
cout << "Inserted" << endl;
break;
case 2:
pointerOfLinkList->printAll(head);
break;
case 8:
break;
case 9:
break;
case 0:
is.open("nodes of my link list.dat", ios::binary | ios::in);

pointerOfLinkList = new linkList;
is.read(reinterpret_cast<char*>(pointerOfLinkList),sizeof(*pointerOfLinkList));
while (!is.eof()){
pointerOfLinkList->insert(&head,&tail);
pointerOfLinkList = new linkList;
is.read(reinterpret_cast<char*>(pointerOfLinkList),sizeof(*pointerOfLinkList));
}
is.close();
break;
default:
cout << "Wrong Key pressed" << endl;
}
_getch();
system("cls");
}
return 0;
}

Insert at tail Link List


//Program to insert at tail in Link List using Classes.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <conio.h>
#include <Windows.h>
using namespace std;

class linkList{
public:
void getData();
void insert(linkList **head, linkList **tail); // insert at tail
void printAll(linkList *head); // Display all records.
private:
char name[100];
int rollNo;
linkList *next;
};
//````````````````````````````````````````````````````````````````````````````````````````````````````````````
void linkList::getData(){
cout << "Enter Name: "; cin >> name;
cout << "Enter Roll Number: "; cin >> rollNo;
next = NULL;
}
//````````````````````````````````````````````````````````````````````````````````````````````````````````````
void linkList::insert(linkList **head, linkList **tail){ // insert at tail
if (*head == NULL && *tail == NULL){
*head = (this);
*tail = (this);
}
else{
(*tail)->next = this;
*tail = this;
}
}
//````````````````````````````````````````````````````````````````````````````````````````````````````````````
void linkList::printAll(linkList *head){
for (linkList *temp = head; temp!=NULL; temp=temp->next){
cout << "Name: " << temp->name << endl
<<  "Roll Number: " << temp->rollNo << endl << endl;
}
}
//````````````````````````````````````````````````````````````````````````````````````````````````````````````
/////////////////////////////////////////////////// Main() //////////////////////////////////////
int main(){
linkList *pointerOfLinkList  = 0, *head = 0, *tail = 0;


while (true){
cout << "1. Insert Node\n"
<< "2. Print All\n"
<< "0. Exit\t";
int opt; cin >> opt;

switch(opt){
case 1:
pointerOfLinkList = new linkList;
pointerOfLinkList->getData();
pointerOfLinkList->insert(&head,&tail);
cout << "Inserted" << endl;
break;
case 2:
pointerOfLinkList->printAll(head);
break;
case 8:
break;
case 9:
break;
case 0:
return 0;
default:
cout << "Wrong Key pressed" << endl;
}
_getch();
system("cls");
}
return 0;
}

Initialize Static Array in C++


Initialize Static Array in C++ program is given below:

#include <iostream>
using namespace std;

class myClass{
private:
static int array[100]; //Static Array in C++
public:
void display();
};
////////////////////////////////////////////////////////////////
int myClass::array[100] = {0}; //Initialize Static Array in C++

void myClass::display(){
for (int i = 0; i<100; i++){
cout << "array[" << i << "] = " << array[i] << endl;
}
}
//``````````````````````````````````````````````````````````````

int main(){
myClass obj;
obj.display();
return 0;
}

Convert int to string C++

Convert int to string in C++. Following program converts an int to string in C++.
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

string int_to_string(const int& port) {
    stringstream ss;
    ss << port;
    return ss.str();
}

int main() {
    int port = 114;
    cout << int_to_string(port) << endl;
}

Printing random lines from file C++

Printing random lines from file in C++ program is given below:

#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
using namespace std;

int main(){
ofstream os("a.txt");
for (int i = 0; i<=999; i++){
os << i << endl;
}
os.close();

ifstream is("a.txt");

char c;
string line;
while (!is.eof()){
while (c != '\n'){
is.seekg(rand()%1000);
c = is.get();
}
getline(is,line);
cout << line << endl; //Printing lines randomly from file.
c = '0';
Sleep(300);
}
return 0;
}


Though lines are being printed randomly but there is repetition.

Copy one file to another file C++

'Copy one file to another file in C++' program is given below.
You have to write copy c:/source.txt c:/destination.txt to copy contents of file source.txt to destination.txt.

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void Write(string, string);

int main(){
cout << "Write: copy srcfile destfile.cpp\nYou can give complete path as well.\n\n";
string s1, s2, s3;
cin >> s1 >> s2 >> s3;
if (strcmp(s1.c_str(),"copy") != 0){
cout << s1 << " is not a valid command. Only valid command for this program is copy." << endl;
}
Write(s2,s3);
return 0;
}
void Write(string s1, string s2){
char line[100];
ifstream is(s1.c_str());
ofstream os(s2.c_str());

if (is.is_open() && os.is_open()){
while (!is.eof()){
is.getline(line,100,'\n');
os << line << endl;
}
}
else{
if (!is.is_open()){
cout << endl << s1 <<" couldn't be opened. Creat and write something in a.txt, and try again." << endl;
}
else{
cout << endl << s2 <<" couldn't be opened. Creat and write something in a.txt, and try again." << endl;
}
}
}

Visit a simpler program:

Copy contents of One File to another C++

'Copy file in C++' program is given below.
Copies content of file 'a' to file 'b'.

#include <iostream>
#include <fstream>
using namespace std;

int main(){
char line[100];

ifstream is("a.txt");
ofstream os("b.txt");

if (is.is_open()){
while (!is.eof()){
is.getline(line,100,'\n');
os << line << endl;
}
}
else{
cout << "a.txt couldn't be opened. Creat and write something in a.txt, and try again." << endl;
}

return 0;
}

See a better program:
Copy one file to another file C++

Finding a word from File C++


#include <iostream>
#include <fstream>
using namespace std;

int main(){
ofstream os("test.txt");
os << "1. Hi." << endl <<"2. By mom!" << endl << endl << "4. YES I did it." << endl << "5. I'm fine." << endl << "6. I'm writing different lines to the file, OK?";

os.close();

cout << "My file contains following data:\n";
cout << "1. Hi." << endl <<"2. By mom!" << endl << endl << "4. YES I did it." << endl << "5. I'm fine." << endl << "6. I'm writing different lines to the file, OK?";

cout << "\n\nEnter a word to find from it: ";
char word[50]; cin.getline(word,50,'\n');

//Calculating number of characters in word.
for ( int sizeOfWord = 0; word[sizeOfWord]!='\0'; sizeOfWord++);

//searching the word.
ifstream is("test.txt");

char sentence[200];
int line_no = 1;
int i = 0;
bool found = false;
while (!is.eof()){
is.getline(sentence,200,'\n');

for (int j = 0; sentence[j]!='\0'; j++){
if (sentence[j] == word[i]){
++i;
}
else{
i = 0;
}
if (i >= sizeOfWord){
cout << "Found at line: " << line_no << endl;
found = true;
}
}

line_no++;
}
if (!found){
cout << "NOT found." << endl;
}
return 0;
}

Reading Random lines from a text file C++


Calculate Time of program C++

Time in C++:
Following program calculates time of program execution in C++:

 #include <iostream>  
 #include <ctime>  
 #include <windows.h>  
 using namespace std;  
   
 int main(){  
      double start_time = clock();  
      Beep(500,1000); //BEEP FOR 1 SECOND will be produced. //YOUR CODE HERE.  
      double end_time = clock();  
        
   
      double time_taken = end_time - start_time;  
      double time_taken_in_seconds = time_taken/CLOCKS_PER_SEC;  
   
      cout << "Time taken during program execution is " << time_taken_in_seconds << " Second(s)"<< endl;  
        
      return 0;  
 }  

Sorting Linked List C++

'Sorting linked list in ascending order' program is given below:


#include <iostream>
using namespace std;
/////////////////////////////////////////////////////////////////////////////////////////////
struct node{
int data;
node *next;
};
/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
class ll{
public:
ll();
void insert();
void print();
private:
node *head, *tail;
};
/////////////1////////////////////////////////////////////////////////////////////////////////
ll::ll(){
head = tail = 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////
void ll::insert(){
node *temp = new node;
temp->next = NULL;
cout << "Id: ";  cin >> temp->data;
if (head == 0 && tail == 0){
head = temp;
tail = temp;
}
else{
if (temp->data <= head->data){
//Insert at head
temp->next = head;
head = temp;
}
else{
if (temp->data >= tail->data){
//insert at tail
tail->next = temp;
tail = temp;
}
else{// Insert some where in the middle.
node *p = head;
while (temp->data > p->data){//finding where to insert.
p = p->next;
}
//we've to insert at node before p.
//so
for (node *b = head; b->next != p; b = b->next);
//insert after bth node.
temp->next = b->next;
b->next = temp;
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void ll::print(){
for (node *p = head; p!=NULL; p=p->next){
cout << p->data << endl;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
//*******************************************************************************************
int main(){
ll o;
cout << "Do you want to insert? (y/n)  "; char opt; cin >> opt;

while (opt == 'y' || opt == 'Y'){
o.insert();
cout << "Do you want to insert? (y/n)  "; cin >> opt;
}

o.print();

return 0;
}
//*******************************************************************************************

Wacmian Numbers program C++


#include <iostream>
#include <cmath>
using namespace std;

int getInt(char);

int main(){
long int sum[100] = {0};
int u = 0;
char a[100] = "";
cout << "WACMIAN Number: "; cin >> a;

while (a[0]!='#' || a[1] != '\0'){


if (a[0] != '#' || a[1] != '\0'){

for (int j = 0; a[j]!= '\0'; j++);
j--;

for (int i = j, base = 0; i >= 0; i--, base++){
sum[u] += getInt(a[i])*pow(6,base);
}
if (a[0] != '#')
u++;
}
cout << "WACMIAN Number: "; cin >> a;
}

cout << endl << "OUTPUT:\n";
for (int i =0; i <= u; i++){
if (a[0] == '#' && sum[i] == 0 && i==u)
break;
cout << sum[i] << endl;
}


return 0;
}

int getInt(char u){
switch (u){
case '%':
return 0;
case ')':
return 1;
case '~':
return 2;
case '@':
return 3;
case '?':
return 4;
case '\\':
return 5;
case '$':
return -1;
default:
cout << "Wrong input." << endl;
exit(0);
}
}

Sound in C++


#include <windows.h>

int main()
{
    Beep(1568, 200);
    Beep(1568, 200);
    Beep(1568, 200);
    Beep(1245, 1000);
    Beep(1397, 200);
    Beep(1397, 200);
    Beep(1397, 200);
    Beep(1175, 1000);
   
    return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#include <iostream.h>
#include <windows.h>

void scale(void)
{ Beep(523,400); // 523 hertz (C5) for 400 milliseconds
 Beep(587,400);
 Beep(659,400);
 Beep(698,400);
 Beep(784,400);
 Beep(698,400);
 Beep(659,400);
 Beep(587,400);
 Beep(523,400);
}


int main()
{

 scale();
 cout << "Scale completed.\n";
 
 return 0;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////




"Don't let anyone ever make you feel like you don't deserve what you want."