Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing line to a file using C

Tags:

c

file-io

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
like image 928
Dunc Avatar asked Mar 08 '12 16:03

Dunc


2 Answers

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:

  1. You must include 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.
  2. You must not use 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.
  3. You must not insert newlines anywhere; the encrypted data might contain newlines, but those must be preserved, and no extraneous one can be added.
  4. When you read this file back in, you must open it as a binary file "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.

like image 116
Jonathan Leffler Avatar answered Sep 30 '22 16:09

Jonathan Leffler


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.

like image 44
mechanical_meat Avatar answered Sep 30 '22 16:09

mechanical_meat