0% found this document useful (0 votes)
1 views25 pages

File Operations (Cont)

The document provides an overview of file handling in C++, focusing on file pointers, reading and writing functions, and random access files. It explains how to manipulate file pointers using functions like seekg() and tellg(), and demonstrates the use of read() and write() for binary data. Additionally, it outlines a method for deleting records from a file by copying non-target records to a temporary file before renaming it.

Uploaded by

aa.raxmanovv
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)
1 views25 pages

File Operations (Cont)

The document provides an overview of file handling in C++, focusing on file pointers, reading and writing functions, and random access files. It explains how to manipulate file pointers using functions like seekg() and tellg(), and demonstrates the use of read() and write() for binary data. Additionally, it outlines a method for deleting records from a file by copying non-target records to a temporary file before renaming it.

Uploaded by

aa.raxmanovv
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/ 25

C++ Files and Streams

(cont.)
Contents
 FilePointers
 Function for manipulation of file pointer
 read() and write() function
 How to delete record from a file

2
File Pointers
1. Each file have two associated pointers known as
the file pointers.

2. One of them is called the input pointer (or get pointer) and the
other is called the output pointer (or put pointer).

3. The input pointer is used for reading the contents of a given file
location

4. The output pointer is used for writing to a given file location.


Default Actions
1. To open a file in read-only mode, the input pointer is
automatically set at the beginning so that we can read the file
from the start.
2. Similarly, when we open a file in write-only mode, the
existing contents are deleted and output pointer is set at the
beginning.This enables us to write to the file from the start .
3. If we want to open an existing file to add more data, the file is
opened in ‘append’ mode.
Action on File Pointers while Opening a File
Function for manipulation of file pointer
When we want to move file pointer to desired position then use
these function for manage the file pointers.

seekg () = moves get pointer (input) to a specified location

seekp () = moves put pointer (output) to a specified location

tellg () = gives the current position of the get pointer

tellp () = gives the current position of the put pointer


Example,
Infile.seekg(10) ;

This statement moves the file pointer to the byte number 10.
The bytes in the a file are numbered beginning from zero. Therefore, the pointer
will be pointing to the 11th byte in the file.

Consider the following statements:


ofstream fileout;
Fileout.open(“hello”,ios::app);
Int p=fileout.tellp();

On execution of these statement, The pointer is moved to the end of the file “hello”
and the value of p Will represent number of bytes in the file.
‘Seek’ functions
seekg() and seekp() can also be used with two arguments as follows:
Seekg(offset,refposition); , seekp(offset,refposition)

Offset represents the number of bytes the file pointer is to be moved from the
location specified by the parameter ref position.

Reference position takes one of the following three constants defined in the ios class

ios::beg start of the file


ios:: cur current position of the pointer
ios::end end of the file
1. //Example of using seekg() and tellg() functions
2. #include <fstream>
3. using namespace std;
4. int main() {
5. ofstream outFile("example.txt");
6. outFile << "This is a test sentence." << endl;
7. outFile.close();
8. ifstream inFile("example.txt");
9. char ch;
10. inFile.seekg(5); // Set the get pointer to the 6th character
11. inFile.get(ch);
12. cout << "Character at position 5: " << ch << endl;
13. inFile.seekg(0, ios::end); // Set the get pointer to the end of the file
14. cout << "File size: " << inFile.tellg() << " bytes" << endl;
15. inFile.close();
16. return 0;
17. }
1. //Example of using tellg() function
2. #include <iostream>
3. #include <fstream>
4. using namespace std;
5. int main() {
6. ofstream outFile("example.txt");
7. outFile << "This is a test sentence." << endl;
8. outFile.close();
9. ifstream inFile("example.txt");
10. cout << "Current position of get pointer: " << inFile.tellg() << endl;
11. inFile.seekg(10); // Move the get pointer to position 10
12. cout << "Current position of get pointer after seekg(): " << inFile.tellg() << endl;
13. inFile.close();
14. return 0;
15. }
fout . seekg(0, ios :: beg)
-- go to start
fout . seekg(0, ios :: cur)
-- stay at current position
fout . seekg(0, ios :: end)
-- go to the end of file
fout . seekg(m, ios :: beg)
-- move to m+1 byte in the
file
fout . seekg(m, ios :: cur) -- go forward by m bytes
from the current position
fout . seekg(-m, ios :: cur) -- go backward by m bytes
from the current
position
fout . seekg(-m, ios :: end) -- go backward by m bytes
from the end
read() and write() function
1. The functions read() and write () , unlike the functions put() and get() ,
handle the data in binary form.
2. Values are stored in the disk file in the same format in which they are
stored in the internal memory.
3. An int take two bytes to store its value in the binary form irrespective of
its size. But a 4 digit int will take 4 bytes to store it in the character form.
4. The binary format is more accurate for storing the numbers as they are
stored in the exact internal representation.
5. There are no conversions while saving the data and therefore saving is
much faster.
file.read ((char *)&V , sizeof (V));
file.write ((char *)&V , sizeof (V));

These function take two arguments. The first is the address of the
variable V , and the second is the length of that variable in bytes .
The address of variable must be cast to type char * (i.e pointer to
character type) .

To output objects of other types, we must convert the


pointers to those objects to type const char*
Random Access Files
Random access files are files in which records can be accessed in any order
1. Also called direct access files
2. More efficient than sequential access files
Random Access Files
1. The Random Access File class contains the same read(),
write() and close() methods as Input and Output Stream.
2. Also contains seek() that lets you select a beginning
position within the file before reading or writing data.
3. Includes capabilities for reading and writing.
4. With a random-access file, you can seek to the desired
position and then read and write an amount of bytes.
1. #include <iostream> // For input/output operations
2. #include <fstream> // For file stream operations
3. using namespace std;
4. // Define a base class Person
5. class Person {
6. protected:
7. string name; // Member variable to store name
8. int age; // Member variable to store age
9. public:
10. // Function to get data from user input
11. void getData() {
12. cout << "Name: ";
13. cin >> name;
14. cout << "Age: ";
15. cin >> age;
16. }
17. // Function to display the stored data
18. void showData() {
19. cout << "Name: " << name << endl;
20. cout << "Age: " << age << endl;
21. }
22. };
23. int main() {
24. Person per; // Create a Person object
25. per.getData(); // Get user input
26. // Create an output file stream to write binary data to "PERSON"
27. ofstream outfile("PERSON", ios::binary);
28. // Write the contents of the 'per' object to the binary file
29. outfile.write((char*)(&per), sizeof(per));
30. outfile.close(); // Close the output file
31. // Create an input file stream to read binary data from "PERSON"
32. ifstream infile("PERSON", ios::binary);
33. // Read data back into the 'per' object
34. infile.read((char*)(&per), sizeof(per));
35. per.showData(); // Display the read data
36. infile.close(); // Close the input file (corrected from outfile.close())
37. return 0;
38. }
1. #include <iostream>
2. #include <fstream>
3. using namespace std;
4. class Person {
5. protected:
6. string name;
7. int age;
8. public:
9. void getData() {
10. cout << "Name";
11. cin >> name;
12. cout << "Age";
13. cin >> age;
14. }
15. void showData() {
16. cout << "Name" << name << endl;
17. cout << "Age" << age << endl;
18. }
19. };
20. int main() {
21. Person per;
22. char ch = 'y';
23. fstream file;
24. file.open("person.dat", ios::trunc | ios::in | ios::out | ios::binary);
25. cout << "Enter person data:" << endl;
26. cout << "Enter Y or y to enter data" << endl;
27. while (ch == 'Y' || ch == 'y') {
28. per.getData();
29. file.write((char*)&per, sizeof(per));
30. cin >> ch;
31. }
32. file.seekg(0);
33. cout << "hi" << endl;
34. while ((file.read((char*)&per, sizeof(per)))) {
35. per.showData();
36. }
37. cout << endl;
38. file.close();
39. return 0;}
1. #include <iostream>
2. #include <fstream>
3. using namespace std;
4. class Person {
5. private:
6. string name;
7. int age;
8. public:
9. void getData() {
10. cout << "Name";
11. cin >> name;
12. cout << "Age";
13. cin >> age; }
14. void showData() {
15. cout << "Name" << name << endl;
16. cout << "Age" << age << endl;
17. }
18. };
19. int main() {
20. Person per;
21. ifstream infile;
22. infile.open("person.DAT", ios::in | ios::binary);
23. infile.seekg(0, ios::end);
24. int endposition = infile.tellg();
25. int n = endposition / sizeof(Person);
26. cout << "\n There are----:" << n << " person in file"<<endl;
27. cout << "enter person number:";
28. cin >> n;
29. int position = (n - 1) * sizeof(Person);
30. infile.seekg(position);
31. infile.read((char*)&per, sizeof(per));
32. per.showData();
33. cout << endl;
34. infile.close();
35. return 0;
36. }
How to delete record from a file
To delete a record, following procedure is carried out :
1. Firstly, determine the position of the record to be deleted, by
performing a search in the file.
2. Keep copying the records other than the record to be delete in a
temporary file say temp.dat.
3. Do not copy the record to be deleted to temporary file, temp.dat.
And Copy rest of the records to temp.dat.
4. Delete original file say oop2.dat as :
remove(“oop2.dat");
rename("temp.dat", “oop2.dat");
1. #include<iostream>
2. #include<fstream>
3. #include<string>
4. using namespace std;
5. class student
6. { int U_ID;
7. public:
8. void getdata()
9. { cout << "Roll:";
10. cin >> U_ID; }
11. void display()
12. {
13. cout << "Roll:" << U_ID << endl;
14. }
15. int U_ID1()
16. {
17. return U_ID;
18. }
19. };
20. void writefile(){
21. student a;
22. ofstream fout("student.dat", ios::binary);
23. for (int i = 1; i <= 3; i++)
24. { a.getdata();
25. fout.write((char*)&a, sizeof(a)); }
26. }
27. void readfile(){
28. student a;
29. ifstream fin("student.dat", ios::binary);
30. while (fin.read((char*)&a, sizeof(a)))
31. { a.display(); }
32. }
33. void deletefile(int r){ //takes roll number that needs to be deleted
34. student a;
35. ofstream fout("temp.dat", ios::binary);
36. ifstream fin("student.dat", ios::binary);
37. while (fin.read((char*)&a, sizeof(a)))
38. if (a.U_ID1() != r)
39. fout.write((char*)&a, sizeof(a));
40. fin.close();
41. fout.close();
39. remove("student.dat");
40. rename("temp.dat", "student.dat");}
41. int main(){
42. student a;
43. int n;
44. writefile();
45. cout << "enter the U_ID. to be deleted: ";
46. cin >> n;
47. deletefile(n);
48. cout << "Record Deleted\n";
49. readfile();
50. return 0;
51. }

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy