今天在看ObjectiveC,看到了一个fgets的例子,才发现对于fgets的理解不够透彻。 fgets 的使用方法:char *fgets(char *string, int n, FILE *stream) 从文件stream中读取n-1个字符/一行(若一行不满n-1个),string接收字符串 如果n <= 0,返回NULL 如果n == 1,返回" ",也就是一个空串 如果成功,返回值等于string, 也就是获得字符串的首地址 如果出错,或者读到FILE的结尾,返回NULL. 下面看例子:
#include <stdio.h>
#include <string.h>
int main( )
{
FILE* wordFile = fopen("words.txt","r");
char word[100];
while(fgets(word, 100, wordFile))
{
word[strlen(word)-1] = '\0';
printf("%s is %d characters long\n", word, strlen(word));
}
fclose(wordFile);
return (0);
} words.txt的内容如下(共4行,第4行,为空): apple trees
many books on the desk
have a cup of water 运行后,输出结果如下: apple trees is 11 characters long many books on the desk is 22 characters long have a cup of water is 19 charcters long 从上面的例子看出,若一行不满100个字符时,fgets可以从文件中读取一行。这点,以前,没有注意到。
|