Emerson <> wrote:
> my problem is in the comments of the code .
> would u please give me some clue what 's the problem?
> /*******************************/
> #include "stdio.h"
> #include "malloc.h"
There's no "malloc.h" in standard C. Use <stdlib.h> for the declaration of
malloc() and friends. Moreover, you normally would enclose the names of the
standard header files in angle brackets (i.e. '<' and '>').
> #include "assert.h"
> int main(void)
> {
> FILE *p_file;
> static char *filename="test";
> char *s=NULL;
> int c;
> int num=0;
> if ((p_file=fopen(filename,"w+"))==NULL) { /* does "w+" means your
> can read & write the file? */
Yes. And if it already exists it's truncated to zero length.
> printf("cant't open file %s\n",filename);
It probably would make sense to bail out in this case, so add e.g.
return EXIT_FAILURE;
> } else {
> while ((c=getchar())!=EOF) {
> if (fputc(c,p_file)!=EOF)
> ++num; /*# of character written*/
> }
> fflush(p_file);
> }
> if ((s=(char*)calloc(num,sizeof(*s)))==NULL) {
> printf("can't calloc enough memory\n");
> } else {
> assert(p_file!=NULL); /*the file stores actually what i
> input,ant the p_file is NOT NULL */
> if((s=fgets(s,5,p_file))==NULL) /*i just get 5-1 character,and make
> sure the p_file has more than 5 character*/
> printf("error in fgets\n"); /*problem is HERE,this message is
> printed,WHY?*/
Because after writing to the file you're at the end of it, i.e. at the
position directly after the last character you wrote. Before you can
read back all the characters you just wrote you must set the current posi-
tion in the file back to the start of it using either rewind() or fseek().
> else
> printf("fgets get followings: %s \n", s);
> }
> fclose(p_file);
> return 0;
> }
Regards, Jens
--
\ Jens Thoms Toerring ___
\__________________________
http://www.toerring.de