|
| 1 | +## Copyright (C) 2022 John Donoghue <john.donoghue@ieee.org> |
| 2 | +## |
| 3 | +## This program is free software: you can redistribute it and/or modify it |
| 4 | +## under the terms of the GNU General Public License as published by |
| 5 | +## the Free Software Foundation, either version 3 of the License, or |
| 6 | +## (at your option) any later version. |
| 7 | +## |
| 8 | +## This program is distributed in the hope that it will be useful, but |
| 9 | +## WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 | +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 11 | +## GNU General Public License for more details. |
| 12 | +## |
| 13 | +## You should have received a copy of the GNU General Public License |
| 14 | +## along with this program. If not, see |
| 15 | +## <https://www.gnu.org/licenses/>. |
| 16 | + |
| 17 | +## -*- texinfo -*- |
| 18 | +## @deftypefn {} {@var{t} =} write_dbtable_csv (@var{filename}) |
| 19 | +## Private function |
| 20 | +## @end deftypefn |
| 21 | + |
| 22 | +function write_dbtable_csv (t, filename) |
| 23 | + fd = fopen(filename, "wt"); |
| 24 | + if fd == -1 |
| 25 | + error ("Error opening file '%s'", filename); |
| 26 | + endif |
| 27 | + unwind_protect |
| 28 | + cols = subsref (t, substruct(".", "Properties")).VariableNames; |
| 29 | + l = strjoin(cols, ","); |
| 30 | + fprintf(fd, "%s\n", l); |
| 31 | + |
| 32 | + for idx = 1:length(t) |
| 33 | + row = subsref (t, substruct("{}", {idx,':'})); |
| 34 | + values = ""; |
| 35 | + for col=1:numel(cols) |
| 36 | + if col > 1 |
| 37 | + values = [values ","]; |
| 38 | + endif |
| 39 | + if iscell(row) |
| 40 | + v = row{col}{:}; |
| 41 | + else |
| 42 | + v = row(col,:); |
| 43 | + endif |
| 44 | + if islogical(v) |
| 45 | + if v |
| 46 | + v = 1; |
| 47 | + else |
| 48 | + v = 0; |
| 49 | + endif |
| 50 | + endif |
| 51 | + if isnumeric(v) |
| 52 | + v = num2str(v); |
| 53 | + elseif isempty(v) |
| 54 | + v = ""; |
| 55 | + endif |
| 56 | + # quote it if spaces |
| 57 | + if !isempty(strchr(v, " ")) |
| 58 | + v = ['"' v '"']; |
| 59 | + endif |
| 60 | + values = [values v]; |
| 61 | + endfor |
| 62 | + fprintf(fd, "%s\n", char(values)); |
| 63 | + endfor |
| 64 | + |
| 65 | + unwind_protect_cleanup |
| 66 | + fclose(fd); |
| 67 | + end_unwind_protect |
| 68 | +endfunction |
0 commit comments