#include #include #include #include #include #include #include class TextFile { public: TextFile(std::string filename) { this->filename = filename; open(); } ~TextFile() { if (data.is_open()) { data.close(); } } bool open() { data.open(filename.c_str()); if (!data) { error("tread: couldn't open data file %s", filename.c_str()); } } void close() { data.close(); } void ignore_whitespace() { data >> std::skipws; } long unsigned int lines() { std::ifstream tmpdata(filename.c_str()); if (!tmpdata) { warning("tread: couldn't open file for line counting"); return 0; } long unsigned int count = 0; char buf[1024]; while (!tmpdata.eof()) { tmpdata.getline(buf, 1024); count++; } tmpdata.close(); return count; } template void set_cell_data(Cell &output, long unsigned int row) { column_type v; data >> v; if (!data) { return; } if ( !data.eof() ) { output(0, row) = octave_value(v); } } void skip_column() { Cell c(1,1); set_cell_data(c, 0); } void readline() { char buf[1024]; data.getline(buf, 1024); } bool is_valid() { return data ? true : false; } private: std::string filename; std::ifstream data; }; DEFUN_DLD(tread, args, , "Quick hack for text input, see `textread' for more detail.\n\n\ Usage: tread(filename, format)\n\n\ where format can include '%s' for string,\n\ '%d' for double,\n\ '%*' to ignore column.") { octave_value_list retval; if (args.length() != 2) { print_usage("tread"); return retval; } std::string filename = args(0).string_value(); std::string format = args(1).string_value(); if (error_state) { error("Invalid argument specified"); print_usage("tread"); return retval; } std::istringstream format_s(format); std::vector columns; while (format_s && !format_s.eof()) { std::string p; format_s >> p; columns.push_back(p); } TextFile input(filename.c_str()); if (!input.is_valid()) { return retval; } input.ignore_whitespace(); long unsigned int nr_rows = input.lines(); if (nr_rows == 0) { return retval; } std::vector output(columns.size()); for (int i = 0; i < columns.size(); i++) { output[i] = Cell(1, nr_rows); } std::string s; double d; char buf[1024]; long unsigned int row = 0; try { while (input.is_valid()) { for (int i = 0; i < columns.size(); i++) { OCTAVE_QUIT; if (columns[i] == "%d") { input.set_cell_data(output[i], row); } else if (columns[i] == "%s") { input.set_cell_data(output[i], row); } else { input.skip_column(); break; } } row++; input.readline(); } } catch (std::exception e) { error("tread: cannot read from %s (%s)", filename.c_str(), e.what()); return retval; } dim_vector dim(1, row-1); for (int i = 0; i < columns.size(); i++) { output[i].resize(dim); retval.append( octave_value(output[i]) ); } input.close(); return retval; }