Friday, March 31, 2023

BCA and B.Sc Programs - Programming in C++ Lab - Bharathiar University - Practical Program 11-Write a C++ Program to create a File and to display the contents of that file with line numbers.

 

Bharathiar University

Programming in C++ Lab
C++ Program 11
Write a C++ Program to create a File and to display the contents of that file with line numbers.

In this page

  • C++ Source Code for MS Dos Turbo C++
  • C++ Source Code for Visual studio code
Source code for Turbo C++
#include<iostream.h>
#include<fstream.h>
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
    char fname[30], str[100];
    fstream fp;
    int i=0;
    clrscr();
    cout<<"Enter the Name of File: ";
    gets(fname);
    fp.open(fname, fstream::out);
    if(!fp)
    {
cout<<"\nError Occurred!";
    return 0;
    }
    cout<<"Enter the Data: ";
    gets(str);
    while(strlen(str)>0)
    {
fp<<str;
fp<<'\n';
gets(str);
    }
    fp.close();
    fp.open(fname, fstream::in);
    if(!fp)
    {
cout<<"\nError Occurred!";
return 0;
    }
    cout<<"\nContent of "<<fname<<":-\n";
    fp.getline(str, 1000);
    while(strlen(str)>0)
   {
      
     cout<<++i<<".";
     cout << str << endl;
     fp.getline(str, 1000);
   
   }
    fp.close();
    getch();
    return 0;
}

Output:


Output.txt file





Source code for Visual studio code

#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string.h>
using namespace std;
int main()
{
    char fname[30], str[50],ch;
    fstream fp;
    int i=0;
    cout<<"Enter the Name of File: ";
    gets(fname);
    fp.open(fname, fstream::out);
    if(!fp)
    {
        cout<<"\nError Occurred!";
        return 0;
    }
    cout<<"Enter the Data: ";
    gets(str);
    while(strlen(str)>0)
    {
        fp<<str;
        fp<<"\n";
        gets(str);
    }
    fp.close();
    fp.open(fname, fstream::in);
    if(!fp)
    {
        cout<<"\nError Occurred!";
        return 0;
    }
     cout<<"\nContent of "<<fname<<":-\n";
    fp.getline(str, 1000);
    while(strlen(str)>0)
   {
     
     cout<<++i<<".";
     cout << str << endl;
     fp.getline(str, 1000);
    
   }
   
    fp.close();
    cout<<endl;
    return 0;
}

Output:

test.txt file

No comments:

Post a Comment

Program 12 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 12 Implement a telephone directory using files

  BCA Object Oriented Programming using C++ Practical Madras University  Program 12  Implement a telephone directory using files SOURCE CODE...