edit — чтение, манипулирование и запись в документ C ++ с использованием в основном fstream и массивов

Существует ли простое для понимания и объективное руководство по чтению, управлению записью потоков файлов C ++? Все, что было бы полезно на этом этапе.

Есть ли простая, простая модель, которую я могу использовать для чтения / записи / манипулирования списком элементов в текстовом документе, который состоит из строк, целых чисел, двойных чисел, символов и логических выражений?

Могу ли я загрузить файл, прочитать и выгрузить все в структурированный массив (или память), затем манипулировать структурным массивом (сортировать, перечислять, редактировать и т. Д.), А затем выкидывать все обратно в файл?

0

Решение

Как, если ваш файл отформатирован? В зависимости от формата вам придется читать его по-разному. Например, если у вас есть файл, который имеет такой формат

John 18
Kelly 19

Вы можете иметь код примерно так, чтобы прочитать его

struct Person{
string name;
int age;
}

//create a read operator for Person class
ostream& operator>>(ostream& stream, Person& p){
return stream >> p.name >> p.age;
}

bool mySortFunc(const Person& p1, const Person& p2){
return p1.name < p2.name; //sort by name
}

int main(){
ofstream file('names.txt');
std::vector<Person> people;
Person aPerson;
while( file >> aPerson ){
people.push_back(aPerson);
}

//now you have a list of person
std::sort(people.begin(),people.end(), mySortFunc);

//do more stuff
}

ничего из вышеперечисленного не скомпилировано, оно просто для того, чтобы дать вам представление. Надеюсь, поможет..

0

Другие решения

Чтение файлов:

std::ifstream file("file.txt");
std::string line;
while(std::getline(file, line)) {
std::cout << line << std::endl;
}

Таким образом, когда у вас есть строка из файла, вы можете разделить ее и проанализировать так, как вы хотите. Возможно, поместите строку (строку) в поток строк и проанализируйте целые числа:

std::stringstream ss(line);
ss >> num1 >> num2 >> num3;

Написание файлов:

int num1 = 1;
int num2 = 2;
int num3 = 3;
std::ofstream file("file.txt");
file << num1 << " " << num2 << " " << num3 << std::endl;
0

    // FileManipulation.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"#include "FileInterface.hpp"class FileInterface;
int _tmain(int argc, _TCHAR* argv[])
{
string         inputfile("D:\\input.txt"),outputfile("D:\\output.txt"),emp_name("sukumar"),emp_dept("seclore");
int emp_id(100),n=6;
ifstream infile1(inputfile.c_str());
double emp_sal(9342342.343);
try
{
FileInterface fintface(inputfile,outputfile);
if(!infile1.good())
{cout<<"file does not exist"<<endl;
while(n--)
{
cout<<"enter name"<<endl;fflush(stdin);
getline(cin,emp_name);
cout<<"enter dept"<<endl;fflush(stdin);
getline(cin,emp_dept);
cout<<"enter emp_id"<<endl;fflush(stdin);
cin>>emp_id;
cout<<"enter emp_sal"<<endl;fflush(stdin);
cin>>emp_sal;
fintface.write(emp_name,emp_dept,emp_id,emp_sal);
}
}
else
{
cout<<"file closed"<<endl;
}
fintface.empid_grt(102);
fintface.empid_less(102);
fintface.salary_grt(double(2000));
fintface.salary_less(double(2000));
fintface.emp_dep("seclore");
fintface.print_emp("sukumar");
fintface.print_emp(104);
}
catch(char * s)
{
cout<<s<<endl;
}
fflush(stdin);
cin.get();
return 0;

}

#ifndef FILE_INTERFACE_HPP
#define FILE_INTERFACE_HPP
#include<iostream>
#include<fstream>
#include<iomanip>
#include<string>
using namespace std;
class FileInterface
{
string inputf;
string outputf;
ifstream infile;
ofstream outfile;
bool empid_cmpare(int emp_id,bool greater);
bool salary_cmp(double salary,bool greater);
public:
FileInterface(string inputfile,string outputfile);
~FileInterface();
bool write(string emp_name,string dept,int emp_id,double salary);
bool empid_grt(int emp_id) ;
bool empid_less(int emp_id);
bool salary_grt(double salary);
bool salary_less(double salary);
bool emp_dep(string dept);
bool print_emp(int emp_id);
bool print_emp(string emp_name);
};
#endif //FILE_INTERFACE_HPP

#include "FileInterface.hpp"#include <windows.h>
FileInterface::FileInterface(string inputfile,string outputfile)
{
inputf=inputfile;
outputf=outputfile;
infile.open(inputf.c_str(),ifstream::in|ifstream::out|ifstream::app);
if(infile.good())
{
infile.close();
}
outfile.open(outputf.c_str(),ofstream::in|ofstream::out|ofstream::app);
if(outfile.good())
{
outfile.close();
if(remove((char*)outputf.c_str())!=0)
cout<<"error in deleting output file"<<endl;
}
}
FileInterface::~FileInterface()
{
}
bool FileInterface::write(string emp_name,string dept,int emp_id,double salary)
{
outfile.open(inputf.c_str(),ofstream::in|ofstream::out|ofstream::app);
if(outfile.fail())
{
cout<<"Error opening FILE in write"<<endl;
throw "Error in file";
}
else
{
outfile<<fixed<<showpoint;
outfile<<left;
outfile<<setw(20)<<emp_name;
outfile<<right;
outfile<<setw(20)<<dept;
outfile<<setw(10)<<emp_id;
outfile<<setw(20)<<setprecision(2)<<salary<<endl;
outfile.close();
}
return true;
}
bool FileInterface::empid_cmpare(int emp_id,bool greater)
{
string emp_name,emp_dept;
int id;
double sal;
fstream infile;
if(infile.is_open())
infile.close();
infile.open(inputf.c_str(),ifstream::in);
if(infile.fail())
{
cout<<"Error opening inFILE in empid_cmpare"<<endl;
throw "Error in file";
}
outfile.open(outputf.c_str(),ofstream::in|ofstream::out|ofstream::app);
if(outfile.fail())
{
cout<<"Error opening outFILE in empid_cmpare"<<endl;
throw "Error in file";
}
outfile<<fixed<<showpoint;
while(!infile.eof())
{
infile>>emp_name;
infile>>emp_dept;
infile>>id;
infile>>sal;
if(greater&&(id>=emp_id))
{
outfile<<left;
outfile<<setw(20)<<emp_name;
outfile<<right;
outfile<<setw(20)<<emp_dept;
outfile<<setw(10)<<id;
outfile<<setw(20)<<sal<<endl;
}
else if(!greater&&id<emp_id)
{
outfile<<left;
outfile<<setw(20)<<emp_name;
outfile<<right;
outfile<<setw(20)<<emp_dept;
outfile<<setw(10)<<id;
outfile<<setw(20)<<sal<<endl;
}
}
infile.close();
if(infile.is_open())
cout<<"file still open"<<endl;
outfile.close();
if(outfile.is_open())
cout<<"file still open"<<endl;
return true;
}
bool FileInterface::empid_grt(int emp_id)
{
return empid_cmpare(emp_id,true);
}
bool FileInterface::empid_less(int emp_id)
{
return empid_cmpare(emp_id,false);
}
bool FileInterface::salary_cmp(double salary,bool greater)
{
string emp_name,emp_dept;
int id;
double sal;
fstream infile;
infile.open(inputf.c_str(),ifstream::in);
if(infile.fail())
{
cout<<"Error opening inFILE in salary_cmp"<<endl;
throw "Error in file";
}
outfile.open(outputf.c_str(),ofstream::in|ofstream::out|ofstream::app);
if(outfile.fail())
{
cout<<"Error opening outFILE in salary_cmp"<<endl;
throw "Error in file";
}
outfile<<fixed<<showpoint;
while(!infile.eof())
{
infile>>emp_name;
infile>>emp_dept;
infile>>id;
infile>>sal;
if(greater&&(sal>=salary))
{
outfile<<left;
outfile<<setw(20)<<emp_name;
outfile<<right;
outfile<<setw(20)<<emp_dept;
outfile<<setw(10)<<id;
outfile<<setw(20)<<sal<<endl;
}
else if(sal<salary)
{
outfile<<left;
outfile<<setw(20)<<emp_name;
outfile<<right;
outfile<<setw(20)<<emp_dept;
outfile<<setw(10)<<id;
outfile<<setw(20)<<sal<<endl;
}
}
infile.close();
outfile.close();
return true;
}

bool FileInterface::salary_grt(double salary)
{
return salary_cmp(salary,true);
}
bool FileInterface::salary_less(double salary)
{
return salary_cmp(salary,false);
}
bool FileInterface::emp_dep(string dept)
{
string emp_name,emp_dept;
int id;
double sal;
fstream infile;
infile.open(inputf.c_str(),ifstream::in);
if(infile.fail())
{
cout<<"Error opening inFILE in emp_dep"<<endl;
throw "Error in file";
}
outfile.open(outputf.c_str(),ofstream::in|ofstream::out|ofstream::app);
if(outfile.fail())
{
cout<<"Error opening outFILE in emp_dep"<<endl;
throw "Error in file";
}
outfile<<fixed<<showpoint;
while(!infile.eof())
{
infile>>emp_name;
infile>>emp_dept;
infile>>id;
infile>>sal;
if(emp_dept.compare(dept)==0)
{
outfile<<left;
outfile<<setw(20)<<emp_name;
outfile<<right;
outfile<<setw(20)<<emp_dept;
outfile<<setw(10)<<id;
outfile<<setw(20)<<sal<<endl;
}
}
infile.close();
outfile.close();
return true;
}
bool FileInterface::print_emp(int emp_id)
{
string emp_name,emp_dept;
int id;
double sal;
fstream infile;
infile.open(inputf.c_str(),ifstream::in);
if(infile.fail())
{
cout<<"Error opening inFILE in print_emp"<<endl;
throw "Error in file";
}
while(!infile.eof())
{
infile>>emp_name;
infile>>emp_dept;
infile>>id;
infile>>sal;
if(id==emp_id)
{
cout<<"EMP_NAME : "<<emp_name<<endl;
cout<<"EMP_DEPT : "<<emp_dept<<endl;
cout<<"ID : "<<id<<endl;
cout<<"SAL : "<<sal<<endl;
break;
}
}
infile.close();
return true;
}
bool FileInterface::print_emp(string name)
{
string emp_name,emp_dept;
int id;
double sal;
fstream infile;
infile.open(inputf.c_str(),ifstream::in);
if(infile.fail())
{
cout<<"Error opening inFILE in print_emp1"<<endl;
throw "Error in file";
}
while(!infile.eof())
{
infile>>emp_name;
infile>>emp_dept;
infile>>id;
infile>>sal;
if(emp_name.compare(name)==0)
{
cout<<"EMP_NAME : "<<emp_name<<endl;
cout<<"EMP_DEPT : "<<emp_dept<<endl;
cout<<"ID : "<<id<<endl;
cout<<"SAL : "<<sal<<endl;
}
}
infile.close();
return true;
}
0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector