Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

End of File/constant char

Status
Not open for further replies.

gonzilla

Programmer
Apr 10, 2001
125
US
Hi,

I feel like I should know why this is happening...but I'm not sure why. I work on Sun UNIX machine. I am trying to simply write a file with a character array using
fprintf(). Like this...

FILE *fp;
char array[]="this is the output string";

open the file (tried text and binary)...

fprintf(fp, array);
fclose(fp);

...or I have tried other versions of that fprintf() statement...

fprintf(fp, "%s" , array);
etc...

When I use vi to open the file, it looks fine but I get a prompt saying incomplete last line. The only version of the fprintf() that doesn't produce that prompt is

fprint(fp, "%s\n", array);

Why do I need the newline? Why does that fix it? I'm guessing it flushes the line, but doesn't fclose(fp) do that already? I feel like theremust be another way. I even put a newline at the end of the array string and that didn't work, ie..

char array[]="this is the output string\n";

Any help would be appreciated.

Thanks.

-Tyler
 
vi recognizes "\n" as end-of-line. There's nothing actually wrong
with the text file.
 
The call:
Code:
      fprintf(fp, "%s" , array);
writes the text without adding an end-of-line (EOL) marker, which is '\n' or '\r\n' (for DOS/Windows). A line is a sequence of characters terminated by the EOL marker. Every file is terminated by an end-of-file (EOF) marker which is usually -1. The text in the file, after the above fprintf call, is as follows:
Code:
       this is the output stringEOF
Whereas vi expects it to be:
Code:
       this is the output stringEOLEOF
The first line is not terminated properly, even though most well-written text utilities are able to pick this up. It's good thing that vi warns you of this scenario.
 
Thank you for the clarification! That makes tons of sense.

Thanks.

-Tyler
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top