There are two differences between Write
and WriteString
:
Write
adds a newline after all expressions, WriteString
does not.
Write
uses the FormatType
of the output stream (default InputForm
), WriteString
uses OutputForm
.
WriteString
does not require its argument to be a string. Therefore, the simplest fix is to just change the second Write
to WriteString
.
WriteString[str, "A["]; WriteString[str, 0]; WriteString[str, "] = 0;"]
(* A[0] = 0; -- no trailing newline *)
Alternatively, we could write out all the expressions with a single call to WriteString
:
WriteString[str, "A[", 0, "] = 0;"]
(* A[0] = 0; -- no trailing newline *)
If we want a newline after the semicolon, we can add an explicit newline:
WriteString[str, "A[", 0, "] = 0;\n"]
(* A[0] = 0; -- with trailing newline *)
or add an extra write:
WriteString[str, "A[", 0, "] = 0;"]
Write[str]
(* A[0] = 0; -- with trailing newline *)
If we open the file using FormatType -> OutputForm
, then we can use a single Write
to put the statement on a line of its own:
str = OpenWrite["zot", FormatType -> OutputForm];
Write[str, "A[", 0, "] = 0;"]
Close[str];
FilePrint["zot"]
DeleteFile["zot"]
(* A[0] = 0; -- with trailing newline *)
Aside: Symbolic C
If you are going to be doing a lot of C code generation, you might want to look at Symbolic C. It allows high-level expression of intent and takes away all the nasty string quoting and concatenation.
Needs["SymbolicC`"]
CStatement[CAssign[CArray["A", 0], 123]] // ToCCodeString
(* A[0] = 123; *)
CFunction[int, myfunction, {{int, i}}
, CReturn[COperator[Times, {i, 10}]]
] // ToCCodeString
(*
int myfunction(int i)
{
return i * 10;
}
*)
WriteString[str,Tostring[0]]
is one way $\endgroup$Export
, egcode = {"A[" <> ToString[0] <> "]=0;", "A[" <> ToString[1] <> "]=1;"}; Export["file.c", code, "Lines"];
$\endgroup$