无法通过重复使用 fgets 读取文件
not able to read a file by repetitive use of fgets
在这段代码中,我尝试从文件中读取数据(每行 30 个字符),内容为:
hello world! Learning to code!
123456789123456789123456789123
用于读取此文件的代码是:
#include<stdio.h>
#include<stddef.h>
int main(void)
{
FILE *fptr = fopen("n","r");
char buff[30];
char *buff_ptr = buff;
size_t buff_size=30;
size_t character_count=0;
buff_ptr = fgets(buff,buff_size,fptr);
printf("%s\n",buff_ptr);
fgets(buff,buff_size,fptr);
printf("%s\n",buff);
return 0;
}
为什么第二个 fgets
没有打印输出?
您需要扩大正在读取数据的字符数组。
fgets
的第一次调用恰好读取文件第一条记录中新行字符之前的 29 个字符(为终止零字符 '[=15=]'
保留一个字符) \n'。第二次调用读取这个换行符。
来自C标准(7.21.7.2 fgets函数)
2 The fgets function reads at most one less than the number of
characters specified by n from the stream pointed to by stream into
the array pointed to by s. No additional characters are read after a
new-line character (which is retained) or after end-of-file. A null
character is written immediately after the last character read into
the array.
声明数组例如
char buff[100];
并像
一样调用fgets
fgets( buff, sizeof( buff ), fptr );
这是一个演示程序,它显示具有 30 个元素的数组不够大,无法读取整个第一条记录。即第一条记录超过30个字符
#include <stdio.h>
#include <string.h>
int main(void)
{
const char record[] = "hello world! Learning to code!\n";
printf( "strlen( record ) = %zu\n", strlen( record ) );
return 0;
}
程序输出为
strlen( record ) = 31
在这段代码中,我尝试从文件中读取数据(每行 30 个字符),内容为:
hello world! Learning to code!
123456789123456789123456789123
用于读取此文件的代码是:
#include<stdio.h>
#include<stddef.h>
int main(void)
{
FILE *fptr = fopen("n","r");
char buff[30];
char *buff_ptr = buff;
size_t buff_size=30;
size_t character_count=0;
buff_ptr = fgets(buff,buff_size,fptr);
printf("%s\n",buff_ptr);
fgets(buff,buff_size,fptr);
printf("%s\n",buff);
return 0;
}
为什么第二个 fgets
没有打印输出?
您需要扩大正在读取数据的字符数组。
fgets
的第一次调用恰好读取文件第一条记录中新行字符之前的 29 个字符(为终止零字符 '[=15=]'
保留一个字符) \n'。第二次调用读取这个换行符。
来自C标准(7.21.7.2 fgets函数)
2 The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.
声明数组例如
char buff[100];
并像
一样调用fgets
fgets( buff, sizeof( buff ), fptr );
这是一个演示程序,它显示具有 30 个元素的数组不够大,无法读取整个第一条记录。即第一条记录超过30个字符
#include <stdio.h>
#include <string.h>
int main(void)
{
const char record[] = "hello world! Learning to code!\n";
printf( "strlen( record ) = %zu\n", strlen( record ) );
return 0;
}
程序输出为
strlen( record ) = 31