Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

EX:NO:10

MANIPULATE A TEXT FILE

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
fstream file; //object of fstream class

//opening file "sample.txt" in out(write) mode


file.open("sample.txt",ios::out);

if(!file)
{
cout<<"Error in creating file!!!"<<endl;
return 0;
}

cout<<"File created successfully."<<endl;


//write text into file
file<<"ABCD.";
//closing the file
file.close();

//again open file in read mode


file.open("sample.txt",ios::in);

if(!file)
{
cout<<"Error in opening file!!!"<<endl;
return 0;
}

//read untill end of file is not found.


char ch; //to read single character
cout<<"File content: ";

while(!file.eof())
{
file>>ch; //read single character from file
cout<<ch;
}

file.close(); //close file


return 0;
}
OUTPUT:

File created successfully.


File content: ABCD.

EX NO 11

SEQUENTIAL I/O OPERATIONS ON A FILE

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

int main()
{
char fname[20], ch;
ifstream fin; // create an input stream

cout << "Enter the name of the file: ";


cin.get(fname, 20);
cin.get(ch);

fin.open(fname, ios::in); // open file


if (!fin) // if fin stores zero, i.e., a false value
{
cout << "An error occurred in opening the file.\n";
return 0;
}

while (fin) // When eof is reached, fin equals 0


{
fin.get(ch); // Read a character
cout << ch; // Display the character
}

return 0;
}

OUTPUT

EX NO 12

TO FIND THE BIGGEST NO USING COMMAND LINE ARGUMENTS

#include <stdio.h>
#include <limits.h> /* for INT_MIN */

int main (int argc, char **argv) {

int max = INT_MIN; /* initialize max to lowest integer in range of int */


if (argc == 1) { /* validate args provided (recall argv[0] is program name) */
fputs ("error: no arguments provided.\n"
"usage: ./program number number [...]\n", stderr);
return 1;
}

for (int i = 1; i < argc; i++) { /* loop over all arguments */


int n = 0; /* int to hold arg conversion */
if (sscanf (argv[i], "%d", &n) == 1) { /* convert arg to int/validate */
if (n > max) /* if good int, compare against max */
max = n; /* update max if n is larger */
}
else /* conversion failed */
fprintf (stderr, "error: not an integer '%s'\n", argv[i]);
}

printf ("\nmax of arguments: %d\n", max);


}

You might also like