Re: not writing to file
- From: jt@xxxxxxxxxxx (Jens Thoms Toerring)
- Date: 31 Oct 2006 01:29:25 GMT
John Smith <jsmith@xxxxxxxxxxx> wrote:
I try to write some data to a file. After some data had supposedly
been written to the file, I opened the file before the program
closed it and found it empty. What's wrong with my code? Thanks.
FILE *lptr
char *name;
int nNo;
.............
.............
lptr=fopen("myfile","w")
..............
..............
/* deep in a function */
sprintf(buffer, "%s\r\n",name);
printf("No is %d. Name is %s\n",nNo,buffer);
Why first copy everything to 'buffer' when printf() can print out
what 'name' is pointing directly?
/* they printed OK on screen, my way of checking things */
fwrite (name , 1 , sizeof(name) , lptr);
If 'name' is the variable you defined above then this call is probably
not what you wanted to do - it will write out as many chars as a char
pointer is long on your system, not the string. Replace 'sizeof(name)'
by 'strlen(name)' to write out the string (or use fprintf()).
fwrite (&nNo , 1 , sizeof(nNo) , lptr);
/* checked file without waiting for it to close and
/* found nothing in the file. It's empty. Why? */
As Adrian pointed out most standard C output functions store output
in their internal buffers before writing them to disk (at least as
long as there's enough place left in the buffers) in order to speed
up execution. To make sure things have got written to the disk either
call fflush() on the FILE pointer or 'unbuffer' it using setbuf() or
setvbuf() (or close the file).
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@xxxxxxxxxxx
\__________________________ http://toerring.de
.
- References:
- not writing to file
- From: John Smith
- not writing to file
- Prev by Date: Re: C Interview Questions
- Next by Date: Re: C Interview Questions
- Previous by thread: Re: not writing to file
- Next by thread: Re: not writing to file
- Index(es):
Relevant Pages
|
|