69,371
社区成员
发帖
与我相关
我的任务
分享
/*---读取文中一行,遇到文件结束返回NULL---*/
char *read_line(FILE *fp)
{
int i=0,len=80;
char ch,*s;
s=(char *)calloc(len,sizeof(char));
while((ch=fgetc(fp))!=EOF)
{
if(ch=='\n')
break;
s[i++]=ch;
if(i==len)
{
len+=20;
s=(char *)realloc(s,len*sizeof(char));
}
}
s[i]='\0';
return(s);
}
/*---此函数并不读取一行末尾的'\n',如果要读取'\n'的话把s[i++]=ch放到if(ch=='\n')之前---*/
while(fscanf(fp,"%s",buffer)==1)
{
fprintf(stdout,"%s",buffer);
printf("\n");
}
#include <stdio.h>
int main(void)
{
char arr[20][100] = {'\0'};
int ret = 0, index = 0;
FILE *stream;
if( (stream = fopen( "test1.txt", "r" )) == NULL )
printf( "The file 'test1.txt' was not opened\n" );
else
printf( "The file 'test1.txt' was opened\n" );
do
{
ret = fscanf(stream,"%[^\n]\n",arr[index++]);
}while(ret != 0 && ret != EOF);
//output
while(index >= 0)
{
printf("%s\n",arr[index--]);
}
return 0;
}
fgets(buff,sizeof(buff),fp);
fgetline