I'm currently doing this:
FILE *fOut;
fOut = fopen("fileOut.txt", "w");
char line[255];
...
strcat(line, "\n");
fputs(line, fOut);
but find that when I open the file in a text editor I get
line 1
line 2
If I remove the strcat(line, "\n"); then I get.
line 1line2
How do I get fOut to be
line 1
line 2
The puts()
function appends a newline to the string it is given to write to stdout
; the fputs()
function does not do that.
Since you've not shown us all the code, we can only hypothesize about what you've done. But:
strcpy(line, "line1");
fputs(line, fOut);
putc('\n', fOut);
strcpy(line, "line2\n");
fputs(line, fOut);
would produce the result you require, in two slightly different ways that could each be used twice to achieve consistency (and your code should be consistent — leave 'elegant variation' for your literature writing, not for your programming).
In a comment, you say:
I'm actually looping through a file encrypting each line and then writing that line to a new file.
Oh boy! Are you base-64 encoding the encrypted data? If not, then:
b
in the fopen()
mode (as in fOut = fopen("fileout.bin", "wb");
) because encrypted data is binary data, not text data. This (the b
) is safe for both Unix and Windows, but is critical on Windows and immaterial on Unix.fputs()
to write the data; there will be zero bytes ('\0'
) amongst the encrypted values and fputs()
will stop at the first of those that it encounters. You probably need to use fwrite()
instead, telling it exactly how many bytes to write each time."rb"
and read it using fread()
.If you are base-64 encoding your encrypted data, then you can go back to treating the output as text; that's the point of base-64 encoding.
When files are opened with w
(or wt
) Windows replaces the \n
with \r\n
.
To avoid this, open the file with wb
(instead of w
).
...
fOut = fopen("fileOut.txt", "wb");
...
Unlike many other OSs, Windows makes a distinction between binary and text mode, and -- confusingly -- the Windows C runtime handles both modes differently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With