读书人

fgets读取如何换行呢

发布时间: 2013-07-09 09:50:48 作者: rapoo

fgets读取怎么换行呢?
本帖最后由 Smilencetion 于 2012-02-27 17:28:14 编辑 程序接受两个命令行参数,第一个是一个字符,第二个是文件名
要求程序只打印文件中包含给定字符的那些行


#include <stdio.h>
#include <stdlib.h>
#define MAX 256
int has_ch(char ,const char *);
int main(int argc,char *argv[])
{
FILE *fp;char arr[MAX],ch;
if(argc!=3)
{
printf("no enough arguments:");
exit(EXIT_FAILURE);
}
ch=argv[1][0];
if((fp=fopen(argv[2],"r"))==NULL)
{
printf("can't open %s",argv[2]);
exit(1);
}
while(fgets(arr,MAX,fp)!=NULL)
{
if(has_ch(ch,arr))
fputs(arr,stdout);
}
fclose(fp);
return 0;
}
int has_ch(char ch,const char *arr)
{
while(*arr)
if(ch==*arr++)
return 1;
return 0;
}



我编译好后再命令行输入 test.exe a txt.txt
其中txt.txt内容为
adsf
dfdfde
asff
adfdfdf

我想问的是
   while(fgets(arr,MAX,fp)!=NULL)
{
if(has_ch(ch,arr))
fputs(arr,stdout);
}

是怎么一行一行读取字符串的
当执行第2次 while(fgets(arr,MAX,fp)!=NULL),fgets是怎么变为从txt.txt第2行开始读取的?还是其他情况
[解决办法]
char * fgets ( char * str, int num, FILE * stream );
Get string from stream

Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or a the End-of-File is reached, whichever comes first.
A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str.
A null character is automatically appended in str after the characters read to signal the end of the C string.


------解决方案--------------------


引用:
引用:

char * fgets ( char * str, int num, FILE * stream );
Get string from stream

Reads characters from stream and stores them as a C string into str until (num-1) characters ha……

是的!

读书人网 >C语言

热点推荐