Fgets and fgetc Read File instances

Source: Internet
Author: User

Fgetc reads information from the file (EOF value:-1)

 
# Include <stdio. h>

IntMain (Void)
{
File * stream;
IntCh;

Stream = fopen ("/Home/chenyadong/desktop/temp1","R +");

Do{
Ch = fgetc (Stream );
If(CH = EOF)
Break;
Putc (CH, stdout );
}While(1);

Fclose (Stream );
Return 0;
}

 

Fgets reads information from the file

# Include <stdio. h>

Int Main ( Void )
{
File * stream;
Char Ch [ 256 ];

Stream = fopen ( " /Home/chenyadong/desktop/temp1 " , " R + " );

Do {
Fgets (CH, 256 , Stream );
If (Feof (Stream ))
Break ;
Fputs (CH, stdout );
} While ( 1 );

Fclose (Stream );
Return 0 ;
}

 

If no judgment is added, do {} while (! Feof (Stream ));

For example:

 
Do{
Ch = fgetc (Stream );
Putc (CH, stdout );
}While(! Feof (Stream ));
 
Do{
Fgets (CH,256, Stream );
Fputs (CH, stdout );
}While(! Feof (Stream ));


Use fgetc to obtain:

Hello World
We are you
��

Use fgets to obtain:

Hello World

I love you

I love you

In the first two examples, the result is:

Hello World

I love you

Why are these different results? Is fgetc or fgets changing the position pointer of the file? Or other reasons?

 

But in the following example, do {} while (! Feof (Stream); (what is the difference between the first two examples ?)

# Include <stdio. h>
# Include < String . H>

Int Main ( Void )
{
File * stream;
Char * String = " Hello world \ ni love you " ;
Char Ch [ 256 ];

Stream = fopen ( " /Home/chenyadong/desktop/temp " , " W + " );
Fwrite ( String , Strlen ( String ), 1 , Stream );
Fseek (stream, 0 , Seek_set );

Do {
Fgets (CH, 256 , Stream );
Fputs (CH, stdout );
} While (! Feof (Stream ));

Fclose (Stream );
Return 0 ;
}

Get:

Hello World

I love you

 

Huan HUan, a solution ~

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.