Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <fstream>
- #include <sstream>
- using std::ifstream;
- using std::ofstream;
- typedef int32_t number_type; // тип в котором будут хранится числа в бинарном файле
- // (также определяет диапазон значений)
- int fromTXTtoBIN(ifstream & in, ofstream & out);
- int fromBINtoTXT(ifstream & in, ofstream & out);
- int main(int argc, char *argv[])
- {
- ifstream txtfile("some.txt");
- ofstream binfile("some.bin");
- std::cout<<fromTXTtoBIN(txtfile, binfile)<<std::endl;
- txtfile.close();
- binfile.close();
- ofstream txtfile2("sometxtfrombin.txt");
- ifstream binfile2("some.bin");
- std::cout<<fromBINtoTXT(binfile2, txtfile2)<<std::endl;
- txtfile2.close();
- binfile2.close();
- return 0;
- }
- int fromTXTtoBIN(ifstream & in, ofstream & out)
- {
- std::stringstream ss;
- std::string s;
- float num;
- size_t numbers_convert = 0;
- bool newline=false;
- if (in.is_open() && out.is_open())
- {
- while(std::getline(in, s) && ( !s.empty() || !in.eof()) )
- {
- if(newline)
- out<<std::endl;
- ss.str(s);
- while(ss>>num){
- out.write(reinterpret_cast<const char*>(&num), sizeof(num));
- ++numbers_convert;
- }
- newline = true;
- ss.str("");
- ss.clear();
- s.clear();
- }
- return numbers_convert;
- }
- return -1; // ошибка открытия файлов
- }
- int fromBINtoTXT(ifstream & in, ofstream & out)
- {
- std::stringstream ss;
- std::string s;
- float num=0;
- size_t numbers_convert = 0;
- bool newline=false, space = false;
- if (in.is_open() && out.is_open())
- {
- while(std::getline(in, s) && ( !s.empty() || !in.eof()) )
- {
- if(newline)
- out<<std::endl;
- ss.str(s);
- space = false;
- while(ss.read(reinterpret_cast<char*>(&num), sizeof(num))){
- if (space) out<<' ';
- out<<num;
- ++numbers_convert;
- space = true;
- }
- newline = true;
- ss.str("");
- ss.clear();
- s.clear();
- }
- return numbers_convert;
- }
- return -1; // ошибка открытия файлов
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement