第1个回答 推荐于2018-11-08
//data.txt文件内容如下
1 个 猪
2 个 猪
3 个 猪
4 个 猪
5 个 猪
6 个 猪
7 个 猪
8 个 猪
//运行结果一
the 8 line :8 个 猪
Press any key to continue
//运行结果二
out of range!
Press any key to continue
//代码如下
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main(void)
{
int lid,cnt=0,flag=0;;
char buf[100]="\0";
FILE *fp;
srand((unsigned)time(NULL));
fp=fopen("data.txt","r");
lid= rand()%10+1;
while (fgets(buf,99,fp)!=NULL)
{
if(cnt==lid)
{
printf("the %d line :%s\n",lid+1,buf);
flag=1;
break;
}
cnt++;
}
if (flag==0)
{
printf("out of range!\n");
}
}本回答被提问者和网友采纳
第3个回答 2015-08-03
#include<stdio.h>
FILE*stream;
void main(void)
{
long l;
float fp;
char s[81];
char c;
stream=fopen("fscanf.out","w+");
if(stream==NULL)
printf("Thefilefscanf.outwasnotopened\n");
else
{
fprintf(stream,"%s%ld%f%c","hello world",
65000,3.14159,'x');
/*Setpointertobeginningoffile:*/
fseek(stream,0L,SEEK_SET);
/*Readdatabackfromfile:*/
fscanf(stream,"%s",s);
fscanf(stream,"%ld",&l);
fscanf(stream,"%f",&fp);
fscanf(stream,"%c",&c);
/*Outputdataread:*/
printf("%s\n",s);
printf("%ld\n",l);
printf("%f\n",fp);
printf("%c\n",c);
fclose(stream);
}
}