0% found this document useful (0 votes)
11 views

Append Data in a File

How

Uploaded by

aliabeed323
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Append Data in a File

How

Uploaded by

aliabeed323
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

FACULTY OF ELECTRONIC ENGINEERING TECHNOLOGY

Spring Term :2021-2022


Subject: CP II 4 th SEMESTER

Append Data in a File


The question is, write a program in C++ that receives the name of file and data, to
append the given data inside the given file. The answer to this question is the
program given below:
Example 1 :
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
int main()
{
char filename[20], str[500];
fstream fp;
cout<<"Enter File's Name: ";
gets(filename);
fp.open(filename, fstream::app);
if(!fp)
{
cout<<"\nFile doesn't exist or Access
denied!";
return 0;
}
cout<<"Enter the Data: ";
gets(str);
while(strlen(str)>0)
{
fp<<"\n";
fp<<str;
gets(str);
}
fp.close();
cout<<endl;
return 0;
FACULTY OF ELECTRONIC ENGINEERING TECHNOLOGY
Spring Term :2021-2022
Subject: CP II 4 th SEMESTER
}

Example 2 :

#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
int main()
{
char filename[20], str[500], ch;
fstream fp;
cout<<"Enter File's Name: ";
gets(filename);
fp.open(filename, fstream::app);
if(!fp)
{
cout<<"\nFile doesn't exist or Access denied!";
return 0;
}
else
cout<<"\nThe file is available in the directory";
cout<<"\nEnter the Data: ";
gets(str);
while(strlen(str)>0)
{
fp<<"\n";
fp<<str;
gets(str);
}
cout<<"\nEntered data appended to the file successfully!";
fp.close();
cout<<"\nWant to see the content of file ? (y/n) ";
cin>>ch;
if(ch=='y')
{
fstream fp;
FACULTY OF ELECTRONIC ENGINEERING TECHNOLOGY
Spring Term :2021-2022
Subject: CP II 4 th SEMESTER
fp.open(filename, fstream::in);
cout<<"-----"<<filename<<"--------\n";
while(fp>>noskipws>>ch)
cout<<ch;
fp.close();
}
cout<<endl;
return 0;
}
Example 3 :
#include <iostream>
#include <fstream>
using namespace std;
void save(char * string)
{
fstream myFile("test.txt", fstream::out | fstream::app);
if(myFile.is_open())
{
myFile.write(string, 100);
myFile << "\n";
}
else
{ cout << "Error writing to file"; }
}
int main()
{
char string[100] = {};
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 100; j++)
{
string[j] = i + 48; //48 is the ASCII value for zero
}
save(string);
}
cin >> string[0]; //Pause
return 0;
}

You might also like