简体   繁体   中英

File read in 'c' using fgets

If i have a text file with each line of different length, how does the following code work??

FILE *ptr;
char str[100];
ptr=fopen("hi.txt","r");
while(fgets(str,100,ptr)!=NULL)
{
........
........
}

In this code the 'str' will hold 100 characters which includes some of the characters from 2nd line of text file(if the 1st line of file is 90 chars then 10 chars from second line will also be read).. If i am correct, can you please tell how to read exactly only one line during every ready?

fgets will read up to a single line OR the value passed in as the second parameter.

fgets man page

As long as none of your lines are longer than 99 characters (saving one for the NUL terminator, your code will work as expected.

If you call fgets on a line that is longer than N-1, your next read will continue where it left off and go another 99 bytes or until it finds the end of the line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM