简体   繁体   English

奇怪的C程序fgets

[英]strange C program fgets

I was going through an open source codebase and I see the following:- 我正在浏览一个开源代码库,我看到以下内容: -

char *buf;
char *line;
#define BUFSIZE 5000

buf = malloc(BUFSIZE)
line = buf;

while(fgets(line, (unsigned)(buf + BUFSIZE -line), in) != NULL) {
    // do stuff
    // ....
}

Why is the second argument to fgets given as buf + BUFSIZE - line ? 为什么fgets的第二个参数是buf + BUFSIZE - line

That gives the number of characters from line to end of buf . 这给出了bufline到另一line的字符数。 Your //do stuff likely increments line //do stuff可能增加line

buf + BUFSIZE is a char * pointing to the first char after the memory allocated for buf buf + BUFSIZE是一个char *指向为buf分配的内存的第一个char

buf + BUFSIZE - line is an integral, the number of chars from line to buf + BUFSIZE - and therefore the number of characters you can safely write to line without overflowing buf buf + BUFSIZE - line是一个整数,从linebuf + BUFSIZE的字符数 - 因此你可以安全地写入line的字符数而不会溢出buf

buf + BUFSIZE - line gives the free space in the buffer. buf + BUFSIZE - line给出缓冲区中的可用空间。

This way line can be a scrolling pointer pointing to the first free byte, where the next read operation can put the data. 这种方式line可以是指向第一个空闲字节的滚动指针,其中下一个读取操作可以放置数据。

Line will probably get incremented during the loop. 在循环期间,线可能会增加。 Thus this expression shrinks the value of BUFSIZE by the size of text already read. 因此,此表达式将BUFSIZE的值缩小了已读取的文本的大小。

It's a guess, sicne you didn't post the loop. 这是猜测,sicne你没有发布循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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