Chapter 18-Streams Computation with Files

Example-stdfile.cpp, Page no-728

In [2]:
fout=open("student.out", "w")
name=raw_input("Enter Name: ")
marks=raw_input("Enter Marks Secured: ")
fout.write(name+'\n')
fout.write(marks+'\n')
name=raw_input("Enter Name: ")
marks=raw_input("Enter Marks Secured: ")
fout.write(name+'\n')
fout.write(marks+'\n')
Enter Name: Rajkumar
Enter Marks Secured: 95
Enter Name: Tejaswi
Enter Marks Secured: 90

Example-stdread.cpp, Page no-729

In [3]:
fin=open("student.out", "r")
name = fin.readline()
print "Name:", name,
marks=fin.readline()
print "Marks Secured:",marks,
name = fin.readline()
print "Name:", name,
marks=fin.readline()
print "Marks Secured:",marks
Name: Rajkumar
Marks Secured: 95
Name: Tejaswi
Marks Secured: 90

Example-fdisp.cpp, Page no-732

In [1]:
filename=raw_input("Enter Name of the File: ")
try:
    ifile=open(filename, "r")
    ch=ifile.read()
    print ch
except IOError:
    print "Error opening", filename
Enter Name of the File: mytype.cpp
Error opening mytype.cpp

Example-keyin.cpp, Page no-733

In [1]:
ofile=open("key.txt", "w")
print "Enter characters ..<Ctrl-Z followed by carriage-return to stop"
ch=raw_input()
while(ch):
    ofile.write(ch)
    ch=raw_input()
ofile.close()
Enter characters ..<Ctrl-Z followed by carriage-return to stop
1
2
3
4

Example-stdwr.cpp, Page no-734

In [1]:
def student_write(count):
    fout=open("student.out", "w")
    if not(fout):
        print "Error: student.out cannot be opened in write mode"
        return
    for i in range(count):
        name=raw_input("Enter Name: ")
        marks=raw_input("Enter Marks Secured: ")
        fout.write(name+'\n')
        fout.write(marks+'\n')
    fout.close()
def student_read():
    fin=open("student.out", "r")
    if not(fin):
        print "Error: student.out cannot be opened in read mode"
        return
    for i in range(3):
        name=fin.readline()
        marks=fin.readline()
        if name=='': #to check end of file
            break
        print "Name:", name,
        print "Marks Secured:", marks,
    fin.close()
count = int(raw_input("How many students? "))
print "Enter student details to be stored..."
student_write(count)
print "Student details processed from the file..."
student_read()
How many students? 3
Enter student details to be stored...
Enter Name: Mangala
Enter Marks Secured: 75
Enter Name: Chatterjee
Enter Marks Secured: 99
Enter Name: Rao-M-G
Enter Marks Secured: 50
Student details processed from the file...
Name: Mangala
Marks Secured: 75
Name: Chatterjee
Marks Secured: 99
Name: Rao-M-G
Marks Secured: 50

Example-payfile.cpp, Page no-737

In [1]:
f1=123.45
f2=34.65
f3=56
out_file=open("pay.txt", "w")
out_file.write('{0:6.2f}'.format(f1))
out_file.write('{0:6.2f}'.format(f2))
out_file.write('{0:6.2f}'.format(f3))

Example-fsize.cpp, Page no-739

In [1]:
import sys
                                     
if not(len(sys.argv)==2):             
    print "Usage: fsize <filename>"
else:
                                #Open a file
    infile=open(sys.argv[1],'r')

                                #In case file cannot open
    if(not(infile)):
        print "Error opening", sys.argv[1]
    else:
                                #Read file
        infile.seek(end)
        print "File Size=", infile.tell()
Usage: fsize <filename>

Example-putget.cpp, Page no-741

In [1]:
File=open("student.txt",  "w")
string=raw_input("Enter String: ")
File.write(string)
File.seek(0)
print "Output string:",
File=open("student.txt",  "r")
string=File.read()
print string
Enter String: Object-Computing with C++
Output string: Object-Computing with C++

Example-fwr.cpp, Page no-743

In [1]:
num1=530
num2=1050.25
out_file=open("number.bin", "w")
out_file.write(str(num1)+'\n')
out_file.write(str(num2)+'\n')
out_file.close()
in_file=open("number.bin", "r")
num1=in_file.readline()
num2=in_file.readline()
print num1, num2
in_file.close()
530
1050.25

Example-objsave.cpp, Page no-744

In [1]:
MAXNAME=40
class Person:
    __name=str
    __age=int
    def write(self, os):
        os.write(self.__name+'\n')
        os.write(str(self.__age)+'\n')
    def read(self,Is):
        self.__name=Is.readline()
        self.__age=Is.readline()
def fOutput(fos, b):
    b.write(fos)
def fInput(fos, b):
    b.read(fos)
def Input(b):
    b._Person__name=raw_input("Name: ")
    b._Person__age=int(raw_input("Age: "))
def Output(b):
    print b._Person__name,
    print b._Person__age,
p_obj=Person()
ofile=open("person.txt", "w")
while(1):
    Input(p_obj)
    fOutput(ofile, p_obj)
    ch=str(raw_input("Another? "))
    if ch.upper()!='Y':
        break
ofile.close()
ifile=open("person.txt", "r")
print "The objects written to the file were:.."
while 1:
    fInput(ifile, p_obj)
    Output(p_obj)
    if p_obj._Person__name=='':
        break
Name: Tejaswi
Age: 5
Another? y
Name: Savithri
Age: 23
Another? n
The objects written to the file were:..
Tejaswi
5
Savithri
23
 

Example-student.cpp, Page no-748

In [1]:
try:
    infile=open("student.in", "r")
except IOerror:
    print "Error: student.in file non-existent"
try:
    outfile=open("student.out", "w")
except IOerror:
    print "Error: unable to open student.out in write mode"
else:
    count=int(infile.readline())
    outfile.write("    Students Information Processing")
    outfile.write("\n----------------------------------------")
    for i in range(count):
        name=infile.readline()
        percentage=int(infile.readline())
        outfile.write("\nName: "+name)
        outfile.write("Percentage: "+str(percentage)+'\n')
        outfile.write("Passed in: ")
        if percentage>=70:
            outfile.write("First class with distinction")
        elif percentage>=60:
            outfile.write("First class")
        elif percentage>=50:
            outfile.write("Second class")
        elif percentage>=35:
            outfile.write("Third class")
        else:
            outfile.write("Sorry, Failed!")
        outfile.write('\n')
        outfile.write("----------------------------------------")
    infile.close()
    outfile.close()
    print "Contents of student.out:\n"
    infile=open("student.out", "r")
    Str=infile.read()
    print Str
    infile.close()
Contents of student.out:

    Students Information Processing
----------------------------------------
Name: Rajkumar
Percentage: 84
Passed in: First class with distinction
----------------------------------------
Name: Tejaswi
Percentage: 82
Passed in: First class with distinction
----------------------------------------
Name: Smrithi
Percentage: 60
Passed in: First class
----------------------------------------
Name: Anand
Percentage: 55
Passed in: Second class
----------------------------------------
Name: Rajshree
Percentage: 40
Passed in: Third class
----------------------------------------
Name: Ramesh
Percentage: 33
Passed in: Sorry, Failed!
----------------------------------------

Example-fio.cpp, Page no-751

In [1]:
READ_SIZE=6
reader=str
fstr=open("test.del", "w")
for i in range(10):
    fstr.write(str(i))
fstr.seek(2)
fstr.write("Hello")
fstr=open("test.del", "r")
fstr.seek(4)
reader=fstr.read(READ_SIZE)
print reader
llo789

Example-direct.cpp, Page no-752

In [1]:
from ctypes import Structure, c_char, c_int
class Person(Structure):
    _fields_=[('name',c_char*40),('age',c_int)]
    def write(self, os):
        os.write(self.__name+'\n')
        os.write(str(self.__age)+'\n')
    def read(self, Is):
        self.__name=Is.readline()
        self.__age=Is.readline()
def Input(b):
    b._Person__name=raw_input("Name: ")
    b._Person__age=int(raw_input("Age: "))
def Output(b):
    print "Name:",b._Person__name,
    print "Age:",b._Person__age,
p_obj=Person()
print "Database Creation..."
ofile=open("person.dat", "w")
count=0
while(1):
    print "Enter Object", count, "details..."
    Input(p_obj)
    count=count+1
    p_obj.write(ofile)
    ch=str(raw_input("Another? "))
    if ch.upper()!='Y':
        break
ofile.close()
iofile=open("person.dat", "r+b")
print "Database Access..."
while 1:
    obj_id=int(raw_input("Enter the object number to be accessed <-1 to end>: "))
    iofile.seek(0)
    if obj_id<0 or obj_id>=count:
        break
    for i in range(2*obj_id):
        iofile.readline()
    location=iofile.tell()
    iofile.seek(location)
    p_obj.read(iofile)
    Output(p_obj)
    ch=raw_input("Wants to Modify? ")
    if ch=='y' or ch=='Y':
        Input(p_obj)
        iofile.seek(location)
        p_obj.write(iofile)
iofile.close()
Database Creation...
Enter Object 0 details...
Name: Rajkumar
Age: 25
Another? y
Enter Object 1 details...
Name: Tejaswi
Age: 20
Another? y
Enter Object 2 details...
Name: Kalpana
Age: 15
Another? n
Database Access...
Enter the object number to be accessed <-1 to end>: 0
Name: Rajkumar
Age: 25
Wants to Modify? n
Enter the object number to be accessed <-1 to end>: 1
Name: Tejaswi
Age: 20
Wants to Modify? y
Name: Tejaswi
Age: 5
Enter the object number to be accessed <-1 to end>: 1
Name: Tejaswi
Age: 5
Wants to Modify? n
Enter the object number to be accessed <-1 to end>: -1

Example-outfile.cpp, Page no-758

In [2]:
outfile=open("sample.out", "w")
if not(outfile):
    print "Error: sample.out unable to open"
else:
    while(1):
        buff=raw_input()
        if buff=="end":
            break
        outfile.write(buff)
        if not(outfile):
            print "write operation fail"
            break
    outfile.close()
OOP is good
C++ is OOP
C++ is good
end

Example-1, Page no-762

In [1]:
space=tab=line=0
fin=open("File1.txt", "r")
#fin.write("F I L E\nHandling\nin	C++")
while 1:
    c=fin.read(1)
    if c==' ':
        space+=1
    if c=='\t':
        tab+=1
    if c=='\n':
        line+=1
    if c=='':
        break
print "Number of blank spaces =", space
print "Number of tabs =", tab
print "Number of lines =", line
Number of blank spaces = 3
Number of tabs = 1
Number of lines = 2

Example-2, Page no-763

In [1]:
fin=open("Sample.txt", "r")
#fin.write("File Handling in C++")
print "Here are the contents of the file, Sample.txt..."
c=fin.read()
print c
Here are the contents of the file, Sample.txt...
File Handling in C++