"Les Coover" <lc******@cox.net.spam> wrote:
I have struggled and struggled with this and still can not get it.
The endless loop is supposed to be that way so that
strings can be entered over and over again. When finished
CTRL + C returns to UNIX $ prompt. I know this is crude
but I am just trying to get the basics. All I want to do
is enter data into a text file, the following code compiles
and runs, creating a text file, but will not place the input 01_green
into the text file.
Thanks in advance for any help.
First, lets reformat your code (indents are wonderful devices)
so that it is more readable...
/* jeto.c */
#include <stdio.h>
int main(void)
{
FILE *file; /* FILE pointer */
char color[100];
/* create a file for writing */
file = fopen ("jeto.txt", "w");
printf("Enter, Example: 01_green\n\n");
while(scanf("%99s",color) == 1)
{
fprintf(file, " %50s\n", color);
}
fclose(file); /* now close the file */
return 0;
}
OK... you've opened a file, jeto.txt, and then you write a few
char's to it. But you've done that through the stdio functions,
which buffer output data. There are three modes of buffering
used by stdio, none, line buffering, and block buffering.
With no buffering data is immediately written to the output
device (stderr is an example). With line buffering the data is
written each time a line is completed as indicated by a newline
character being sent (stdout is an example). With block
buffering the data is output when the block is filled (disk
files are an example).
Hence, while you are using the fprintf() function to "write"
data, all it is doing is buffering the data. No actual write to
the disk will take place until the buffer is full or some other
mechanism is used to cause a write. For example, if you repeat
the input cycle often enough you will fill the buffer and cause
data to actually be written to the file. But instead you are
typically killing the program (using ^C) without ever flushing
the data to the file.
The fflush() function is provided to cause data to be output
from the buffer. And the setvbuf() function is provided to set
the type of buffering used.
Given that your fprintf() call always includes a newline, you
could, after opening the file, change its buffering mode to
either no buffering or to line buffering to get the desired
behavior. You could also put a fflush(file); statement
immediately after the fprintf() call.
See the man pages for setvbuf() and fflush() for specifics.
--
Floyd L. Davidson <http://web.newsguy.com/floyd_davidson>
Ukpeagvik (Barrow, Alaska)
fl***@barrow.com