我从一个问题中得到了这段代码,我不明白为什么他们为行[300]选择了准确的300个字符,是不是因为一个.txt文件的行正好有300个字符。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
FILE *cfPtr = fopen("clients.txt", "r");
if(cfPtr == NULL)
{
puts("The file can't be open");
return 0;
}
char name[11], sex[11], dad[11], mom[11], line[300];
int age;
fgets(line, sizeof(line), cfPtr); //skip the first line
while(fgets(line, sizeof(line), cfPtr))
{
if(5 == sscanf(line, "%10s%10s%10d%10s%10s", name, sex, &age, dad, mom))
printf("%s, %s, %d, %s, %s\n", name, sex, age, dad, mom);
}
fclose(cfPtr);
return 0;
}
.txt文件没有这种规则或限制。
至于将300作为 line
数组,并将其用于 fgets(line, sizeof(line), cfPtr);
这只是说 fgets
将从一行中接受最多 300 个字符的输入 (如果字数较少,它可以接受更少的字符)。很有可能,这是一个假设,即没有一行会有超过300个字符,所以这只是一个上限。
fgets(line, sizeof(line), cfPtr)
fgets
读入的字符数最多少于 sizeof(line)
(300字节)从流 cfPtr
并将其存储到 line
.
下面的例子也许能帮助你。
#include <stdio.h>
int main()
{
FILE *fp = fopen("input.txt", "r");
char line[4]; // string length ups to 3 with this declaration.
while(fgets(line, sizeof(line), fp)) {
printf("%s\n",line);
}
printf("enter the string: \n");
fgets(line, sizeof(line), stdin);
printf("string from keyboard %s\n", line);
fclose (fp);
return 0;
}
输入文件和输出。
$cat input.txt
123456789
./test
123 // print 3 characters not 10 (one for enter character) characters of the line
456
789
enter the string:
1234567
line from keyboard 123
你可以看到结果。即使你输入 1234567
你从键盘上得到的字符串是 123
而不是 1234567
.
这是一个原因,使 fgets
比 gets
当你从 stdin
.