Как работать с обработкой файлов в C ++

Опубликовано: 30 Ноября, 2021

Предварительное условие: обработка файлов с помощью классов C ++

В C ++ файлы в основном обрабатываются с использованием трех классов fstream, ifstream, ofstream, доступных в файле заголовка fstream. В этом посте мы обсудим, как хранить данные с помощью обработки файлов.

Идея состоит в том, чтобы взять пример базы данных книг и реализовать ее на C ++. Ниже используются функциональные возможности:

  • Как вставить книжную запись
  • Как просмотреть всю книжную запись
  • Как искать книжную запись
  • Как удалить книжную запись
  • Как обновить книжную запись

Ниже представлена реализация операций обработки файлов:

C ++

// C++ program for implementing the above
// mentioned functionalities
#include <bits/stdc++.h>
#include <conio.h>
#include <fstream>
using namespace std;
// Book class
class Book {
private :
int bookid;
// Max book title size 20
char title[20];
price; float
public :
// Default Constructor
Book()
{
bookid = 0;
strcpy (title, "no title" );
price = 0;
}
// Function for taking book data
void getBookData()
{
cout << "Enter bookid, title, "
<< " price: " ;
cin >> bookid;
cin.ignore();
cin.getline(title, 19);
cin >> price;
}
// Function for showing book data
void showBookData()
{
cout << " "
<< bookid
<< " " << title << " " << price;
}
int storeBook();
void viewAllBooks();
void searchBook( char *);
void deleteBook( char *);
void updateBook( char *);
};
// Function for update book data
void Book::updateBook( char * t)
{
fstream file;
// Open the file
file.open( "myfile3.txt" ,
ios::in | ios::out | ios::ate | ios::binary);
file.seekg(0);
file.read(( char *) this , sizeof (* this ));
// Read the file
while (!file.eof()) {
if (! strcmp (t, title)) {
getBookData();
file.seekp(file.tellp() - sizeof (* this ));
file.write(( char *) this , sizeof (* this ));
}
file.read(( char *) this , sizeof (* this ));
}
// Close the file
file.close();
}
// Function for delete book data
void Book::deleteBook( char * t)
{
ifstream fin;
ofstream fout;
fin.open( "myfile3.txt" ,
ios::app | ios::binary);
if (!fin)
cout << " File not found" ;
else {
fout.open( "tempfile.txt" ,
ios::app | ios::binary);
fin.read(( char *) this , sizeof (* this ));
// Until end of file is not reached
while (!fin.eof()) {
if ( strcmp (title, t))
fout.write(( char *) this , sizeof (* this ));
fin.read(( char *) this , sizeof (* this ));
}
fin.close();
fout.close();
remove ( "myfile3.txt" );
rename ( "tempfile.txt" , "myfile3.txt" );
}
}
// Function to search the Book
void Book::searchBook( char * t)
{
int counter = 0;
ifstream fin;
fin.open( "myfile3.txt" ,
ios::in | ios::binary);
// If file is not found
if (!fin)
cout << "File not found" ;
else {
fin.read(( char *) this , sizeof (* this ));
// Until end of file is not reached
while (!fin.eof()) {
if (! strcmp (t, title)) {
showBookData();
counter++;
}
fin.read(( char *) this , sizeof (* this ));
}
if (counter == 0)
cout << "No record found" ;
fin.close();
}
}
// Function to view all the Book
void Book::viewAllBooks()
{
ifstream fin;
// Open function open file named
// myfile.txt
fin.open( "myfile3.txt" , ios::in | ios::binary);
if (!fin)
cout << "File not found" ;
else {
fin.read(( char *) this , sizeof (* this ));
// Until end of file is
// not reached
while (!fin.eof()) {
showBookData();
// read is object of ifstream
// class which is used for
// read data of file
fin.read(( char *) this , sizeof (* this ));
}
fin.close();
}
}
// Function to implement the store of
// all the books
int Book::storeBook()
{
if (bookid == 0 && price == 0) {
cout << "book data not"
<< " initialized" ;
return (0);
}
else {
ofstream fout;
// In the below line open function
// used to open files. If the file
// does not exist then it will
// create the file "myfile.txt"
fout.open( "myfile3.txt" , ios::app | ios::binary);
// Write function is used for
// data to write in the file
fout.write(( char *) this , sizeof (* this ));
fout.close();
return (1);
}
}
// Function to display the menu of the
// current menu-driver
int menu()
{
int choice;
cout << " Book Management" ;
cout << " 1.Insert book record" ;
cout << " 2.View all book record" ;
cout << " 3.Search book record" ;
cout << " 4.Delete book record" ;
cout << " 5.Update book record" ;
cout << " 6.Exit" ;
cout << " Enter your choice : " ;
cin >> (choice);
return (choice);
}
// Driver Code
int main()
{
// Object of the class Book
Book b1;
char title[20];
while (1) {
system ( "cls" );
switch (menu()) {
case 1:
b1.getBookData();
b1.storeBook();
cout << " Record inserted" ;
break ;
case 2:
b1.viewAllBooks();
break ;
case 3:
cout << " Enter title of "
<< "book to search : " ;
cin.ignore();
cin.getline(title, 19);
b1.searchBook(title);
break ;
case 4:
cout << " Enter book title "
<< "for delete record : " ;
cin.ignore();
cin.getline(title, 19);
b1.deleteBook(title);
break ;
case 5:
cout << " Enter book title "
<< "to update record : " ;
cin.ignore();
cin.getline(title, 19);
b1.updateBook(title);
break ;
case 6:
cout << " Thanks for using" ;
cout << " Press any key to exit" ;
getch();
exit (0);
default :
cout << "Invalid input" ;
}
getch();
}
}

Выход:

  • Вывод для вставки книжной записи с использованием варианта 1:

  • Вывод после повторной вставки книжной записи с использованием варианта 1:

  • Выход для вставки записи 3, 4, и мы можем показать запись, используя выбор 2. Просмотреть все записи книги. Если в качестве префикса bookid добавлен «0», то он игнорируется, как мы видим на изображении ниже:

  • Выведите поисковую книгу fpr, используя ее название, используя вариант 3:

  • Вывод для обновления ранее вставленных данных, как показано ниже:

  • Теперь, наконец, это можно увидеть на изображении ниже. «Java» обновляется как «JAVA», а идентификатор книги - 4, а цена - «350» . Предыдущие данные java-книги можно увидеть на 3-м изображении. Запись для C ++ удалена, поэтому ниже не отображается:

Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .

Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.