2
* Copyright (C) 2004 Laurent Mazet
4
* This program is free software; you can redistribute it and/or modify
5
* it under the terms of the GNU General Public License as published by
6
* the Free Software Foundation; either version 2 of the License, or
7
* (at your option) any later version.
9
* This program is distributed in the hope that it will be useful,
10
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
* GNU General Public License for more details.
14
* You should have received a copy of the GNU General Public License
15
* along with this program; If not, see <http://www.gnu.org/licenses/>.
24
#include <octave/oct.h>
25
#include <octave/Cell.h>
27
DEFUN_DLD (cell2csv, args, nargout,
29
"@deftypefn {Function File} {} cell2csv (@var{file}, @var{c})\n"
30
"@deftypefnx {Function File} {} cell2csv (@var{file}, @var{c}, @var{sep})\n"
31
"@deftypefnx {Function File} {} cell2csv (@var{file}, @var{c}, @var{sep}, @var{prot})\n"
33
"Create a CSV file from a cell. "
34
"@var{sep} changes the character used to separate two fields. By "
35
"default, two fields are expected to be separated by a coma "
36
"(@code{,}). @var{prot} changes the character used to protect a string. "
37
"By default it's a double quote (@code{\"}).\n"
41
if ((args.length() < 2) || (args.length() > 4)) {
43
return octave_value();
47
std::string file = args(0).string_value();
49
Cell c = args(1).cell_value();
51
std::string sep = (args.length() > 2) ? args(2).string_value() : ",";
52
if (sep.length() != 1) {
53
error("Only on charactere need as separator\n");
54
return octave_value();
57
std::string prot = (args.length() > 3) ? args(3).string_value() : "\"";
58
if (prot.length() != 1) {
59
error("Only on charactere need as protector\n");
60
return octave_value();
64
std::ofstream fd(file.c_str());
66
error("cannot write %s\n", file.c_str());
67
return octave_value();
70
/* Concat a cell into a string */
73
/* For each element */
74
for (int i=0, il=c.rows(); i<il; i++) {
76
for (int j=0, jl=c.columns(); j<jl; j++) {
83
if (c(i, j).is_real_scalar()) {
85
/* Output real value */
87
sprintf(tmp, "%g", c(i, j).double_value());
91
else if (c(i, j).is_string()) {
92
/* Output string value */
93
std::string str = c(i, j).string_value();
94
if (str.find(sep) != str.npos) {
96
while ((pos=str.find(prot, pos)) != str.npos) {
97
str.replace(pos, 1, prot+prot);
100
str = prot + str + prot;
105
else if (!c(i, j).is_empty()) {
106
/* Output NaN value */
107
warning ("not a real or a string\n");
114
/* Add end of line */
121
return octave_value();