* * @param cb Callback that updates statusbar * @param win pointer to CsvWindow * @param fromRow first row to save * @param toRow last row to save, if lower than 0: save all the rest (needs fromRow to be set >= 0) */
| 688 | * @param toRow last row to save, if lower than 0: save all the rest (needs fromRow to be set >= 0) |
| 689 | */ |
| 690 | int CsvTable::saveCsv(std::string path, void (*cb)(const char*, void *), void *win, bool flaggedOnly, table_index_t fromRow, table_index_t toRow) { |
| 691 | std::stringstream sstr; |
| 692 | table_index_t rowStart, rowEnd; |
| 693 | const int MAX_MSG_LEN = 500; |
| 694 | char msg[MAX_MSG_LEN + 1]; |
| 695 | std::string tempStr; |
| 696 | int retCode = 0; |
| 697 | std::ofstream output(path, std::ios::binary); |
| 698 | |
| 699 | // rather stupid TODO fix when `headerRow` gets fixed |
| 700 | std::vector<std::string> headerRowCopy; |
| 701 | headerRowCopy.resize( headerRow->size() ); |
| 702 | for( table_index_t i = 0; i < (table_index_t) headerRow->size(); ++i ) { |
| 703 | headerRowCopy.at(i) = headerRow->at(i); |
| 704 | } |
| 705 | |
| 706 | if( output ) { |
| 707 | output.clear(); |
| 708 | if( definition.encoding == CsvDefinition::ENC_UTF16LE ) { |
| 709 | output.put( static_cast<char>(static_cast<unsigned char>(0xFF)) ); |
| 710 | output.put( static_cast<char>(static_cast<unsigned char>(0xFE)) ); |
| 711 | } else if(definition.encoding == CsvDefinition::ENC_UTF16BE) { |
| 712 | output.put( static_cast<char>(static_cast<unsigned char>(0xFE)) ); |
| 713 | output.put( static_cast<char>(static_cast<unsigned char>(0xFF)) ); |
| 714 | } |
| 715 | if( hasCustomHeaderRow ) { |
| 716 | output << encode( vec2string(headerRowCopy, definition), definition.encoding ); |
| 717 | output << encode( definition.linebreak, definition.encoding ); |
| 718 | } |
| 719 | if( fromRow < 0 ) { |
| 720 | rowStart = 0; |
| 721 | rowEnd = storage.rows(); |
| 722 | } else { |
| 723 | rowStart = fromRow; |
| 724 | if( toRow >= 0 ) { |
| 725 | rowEnd = toRow + 1; // '+ 1' because of 'r < rowEnd' in for loop |
| 726 | } else { |
| 727 | rowEnd = storage.rows(); |
| 728 | } |
| 729 | } |
| 730 | for( table_index_t r = rowStart; r < rowEnd; ++r ) { |
| 731 | if( !flaggedOnly || isFlagged(r) ) { |
| 732 | output << encode( vec2string(storage.row(r), definition), definition.encoding ); |
| 733 | output << encode( definition.linebreak, definition.encoding ); |
| 734 | if( (r % 20000) == 0 ) { |
| 735 | snprintf(msg, MAX_MSG_LEN, "Saved %d lines to file.", r); |
| 736 | cb(msg, win); |
| 737 | } |
| 738 | } |
| 739 | } |
| 740 | output.close(); |
| 741 | retCode = saveReturnCode::SAVE_OKAY; |
| 742 | } else { |
| 743 | retCode = saveReturnCode::SAVE_ERROR; |
| 744 | } |
| 745 | |
| 746 | return retCode; |
| 747 | } |