fgets 订阅
fgets函数功能为从指定的流中读取数据,每次读取一行。其原型为:char *fgets(char *str, int n, FILE *stream);从指定的流 stream 读取一行,并把它存储在 str 所指向的字符串内。当读取 (n-1) 个字符时,或者读取到换行符时,或者到达文件末尾时,它会停止,具体视情况而定。 [1] 展开全文
fgets函数功能为从指定的流中读取数据,每次读取一行。其原型为:char *fgets(char *str, int n, FILE *stream);从指定的流 stream 读取一行,并把它存储在 str 所指向的字符串内。当读取 (n-1) 个字符时,或者读取到换行符时,或者到达文件末尾时,它会停止,具体视情况而定。 [1]
信息
外文名
fgets
函数使用
键盘输入fgets(buf,n,stdin)
头文件
stdio.h
中文名
fgets
功    能
读取数据
长    度
n-1个字符的字符串
fgetsfgets函数语法
char *fgets(char *str, int n, FILE *stream);从指定的流 stream 读取一行,并把它存储在str所指向的字符串内。当读取(n-1)个字符时,或者读取到换行符时,或者到达文件末尾时,它会停止,具体视情况而定。 [2]  如果文件中的该行,不足n-1个字符,则读完该行就结束。如若该行(包括最后一个换行符)的字符数超过n-1,则fgets只返回一个不完整的行,但是,缓冲区总是以NULL字符结尾,对fgets的下一次调用会继续读该行。函数成功将返回stream,失败或读到文件结尾返回NULL。因此不能直接通过fgets的返回值来判断函数是否是出错而终止的,应该借助feof函数或者ferror函数来判断。如果成功,该函数返回相同的 str 参数。如果到达文件末尾或者没有读取到任何字符,str 的内容保持不变,并返回一个空指针。如果发生错误,返回一个空指针。
收起全文
精华内容
下载资源
问答
  • fgets

    千次阅读 2018-03-23 00:41:53
    fgetschar *fgets(char *str, int num, FILE *stream);1. 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 eithe...

    fgets

    char *fgets(char *str, int num, FILE *stream);
    1. 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 the end-of-file is reached, whichever happens first.
            A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.
            A terminating null character is automatically appended after the characters copied to str.

            Notice that fgets is quite different from gets: not only fgets accepts a stream argument, but also allows to specify the maximum size of str and includes in the string any ending newline character.
    1.1 Parameters
    str
            Pointer to an array of chars where the string read is copied.
    num
            Maximum number of characters to be copied into str (including the terminating null-character).
    stream
            Pointer to a FILE object that identifies an input stream.
            stdin can be used as argument to read from the standard input.
    1.2 Return Value
            On success, the function returns str.
            If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged).
            If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed).
    2. Example
    2.1 example

    /*
     ============================================================================
     Name        : fgets_example_1.c
     Author      : foreverstrong
     Version     :
     Copyright   : Your copyright notice
     Description : Hello World in C, Ansi-style
     ============================================================================
     */
    
    /* fgets example */
    #include <stdio.h>
    
    int main()
    {
    	FILE *pFile;
    	char mystring[100];
    
    	pFile = fopen("myfile.txt", "r");
    	if (pFile == NULL)
    	{
    		perror("Error opening file");
    	}
    	else
    	{
    		if (fgets(mystring, 100, pFile) != NULL)
    		{
    			puts(mystring);
    		}
    		fclose(pFile);
    	}
    	return 0;
    }
    
            This example reads the first line of myfile.txt or the first 99 characters, whichever comes first, and prints them on the screen.

    2.2 myfile.txt



    Output:

    $forever strong$
    
    3. fgets
            Defined in header <stdio.h>
    char *fgets( char          *str, int count, FILE          *stream ); (until C99)
    char *fgets( char *restrict str, int count, FILE *restrict stream ); (since C99)
    char *fgets( char          *str, int count, FILE          *stream ); (C99 前)
    char *fgets( char *restrict str, int count, FILE *restrict stream ); (C99 起
            Reads at most count - 1 characters from the given file stream and stores them in the character array pointed to by str. Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character. If no errors occur, writes a null character at the position immediately after the last character written to str.
            The behavior is undefined if count is less than 1.
    3.1 Parameters
           str - pointer to an element of a char array
            count - maximum number of characters to write (typically the length of str)
            stream - file stream to read the data from
    3.2 Return value
            str on success, null pointer on failure.
            If the failure has been caused by end-of-file condition, additionally sets the eof indicator (see feof()) on stream. The contents of the array pointed to by str are not altered in this case.
            If the failure has been caused by some other error, sets the error indicator (see ferror()) on stream. The contents of the array pointed to by str are indeterminate (it may not even be null-terminated).
    3.3 Notes
            POSIX additionally requires that fgets sets errno if it encounters an failure other than the end-of-file condition.
            Although the standard specification is ambiguous in the case where count==1, common implementations read no characters, store zero in str[0], and report success (return str)
    4. Example
    4.1 example

    /*
     ============================================================================
     Name        : fgets_example_2.c
     Author      : foreverstrong
     Version     :
     Copyright   : Your copyright notice
     Description : Hello World in C, Ansi-style
     ============================================================================
     */
    
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
    	FILE* tmpf = tmpfile();
    	fputs("Alan Turing\n", tmpf);
    	fputs("John von Neumann\n", tmpf);
    	fputs("Alonzo Church\n", tmpf);
    
    	rewind(tmpf);
    
    	char buf[8];
    	while (fgets(buf, sizeof buf, tmpf) != NULL)
    	{
    		printf("\"%s\"\n", buf);
    	}
    
    	if (feof(tmpf))
    	{
    		puts("End of file reached");
    	}
    }
    
    Output:
    "Alan Tu"
    "ring
    "
    "John vo"
    "n Neuma"
    "nn
    "
    "Alonzo "
    "Church
    "
    End of file reached
    

    References
    http://en.cppreference.com/w/c/io/fgets
    http://zh.cppreference.com/w/c/io/fgets
    http://www.cplusplus.com/reference/cstdio/fgets/


    展开全文
  • fgets.c

    2021-02-17 00:31:44
    fgets.c
  • fgets 函数

    2021-01-18 15:41:53
    fgets 函数 原型:char *fgets(char s,int size,FILEstream);

    fgets 函数

    原型:char *fgets(char *s,int size,FILE *stream);

    功能:
    从stream指定的文件内读入字符,保存到s所指定的内存空间

    参数:
    s 字符串
    size 指定最大读取字符串的长度(size-1)
    stream 文件指针

    例子
    #include <stdio.h>
    int main()
    {
    char str[100] = {0};
    fgets(str, sizeof(str), stdin);
    printf(“str = %s\n”, str);
    }

    **

    sprintf 函数

    **

    原型:
    int sprintf(char *str,const char *fomat,…)

    功能:
    sprintf的作用是将一个格式化的字符串输出到一个目的字符串中

    参数:
    str :字符串首地址
    format:格式化字符串

    展开全文
  • fgets函数

    2020-08-12 00:02:38
    #include <stdio.h> #include <string.h> int main(int argc, const char *argv[]) { char buf[32] = { 0 }... p = fgets(buf, 5, stdin); if(NULL == p) { perror("fgets"); return -1; } prin
    				/*************************************************
    				 *功能:从文件流中读取字符串到s指向的空间
    				 *参数: 
    				 *			@s      存放读取到的数据的缓存区首地址
    				 *			@size   读取size-1,补'\0'
    				 *			@stream 文件流指针
    				 *返回值:
    				 ************************************************/			
    				 char *fgets(char *s, int size, FILE *stream);
    
    
    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, const char *argv[])
    {
    	char buf[32] = { 0 };
    	char *p = NULL;
    
        memset(buf, 0, sizeof(buf));
    	p = fgets(buf, 5, stdin);
    	if(NULL == p)
        {
    		perror("fgets");
    		return -1;
    	}
    
    	printf("buf:%s\n", buf);
    	printf("p:%s\n", p);
    
    	return 0;
    }
    
    
    

    测试结果

    在这里插入图片描述

    展开全文
  • 当前位置:我的异常网» 热门搜索»linux fgets 阻塞linux fgets 阻塞www.myexceptions.net网友分享于:2013-09-23搜索量:159次场景:linux下fgets(.stdin)不阻塞?解决方案linux下fgets(..,..,stdin)不阻塞??我...

    当前位置:我的异常网» 热门搜索 » linux fgets 阻塞

    linux fgets 阻塞

    www.myexceptions.net  网友分享于:2013-09-23   搜索量:159次

    场景:linux下fgets(.stdin)不阻塞?解决方案

    linux下fgets(..,..,stdin)不阻塞??

    我编写了一个修改文档的程序,但是不知道为什么用fgets(buf,1024,stdin)的时候就不阻塞,我是分为两个函数写的,两个函数分别工作的时候就正常,两个函数合起来工作的时候就会这样,求救!!

    函数如下:

    find函数寻找对应项,modify函数修改对应项。

    #include  

    extern   int   modify(FILE   *fp);

    int   main()

    {

    FILE   *fp;

    if(fp=fopen( "./t.txt ", "r+ ")==NULL)

    {

    printf( "there   is   no   such   file ");

    return   -1;

    }

    find(fp);

    modify(fp);

    fclose(fp);

    return   0;

    }

    int   find(FILE   *fp)

    {

    char   *t;

    char   *idata;

    char   *namebuf,*buf2,*addr,*tempbuf;

    char   *searchname;

    char   *tsearchname,*tnamebuf;

    long   count;

    long   offsize;

    offsize=0;

    fseek(fp,0,SEEK_SET);

    searchname=(unsigned   char   *)malloc(1024);

    idata=(unsigned   char   *)malloc(1024);

    tsearchname=(unsigned   char   *)malloc(1024);

    tsearchname=searchname;

    while((*searchname=(unsigned   char)fgetc(stdin))!= ': ')

    {

    searchname++;

    }

    namebuf=(unsigned   char   *)malloc(1024);

    tempbuf=(unsigned   char   *)malloc(1024);

    tnamebuf=(unsigned   char   *)malloc(1024);

    namebuf=tnamebuf;

    while((t=fgets(tempbuf,1024,fp))!=NULL)

    {

    fseek(fp,offsize,SEEK_SET);

    while((*tnamebuf=(unsigned   char)fgetc(fp))!= ': ')

    {

    tnamebuf++;

    printf( "the   number   is:%s\n ",namebuf);

    }

    printf( "namebuf:%s\nsearchname:%s\n ",namebuf,tsearchname);

    int   a=0;

    if((a=strcmp(namebuf,tsearchname))==0)

    break;

    printf( "strcmp   is:%d\n ",a);

    tnamebuf=namebuf;

    fgets(tempbuf,1024,fp);

    offsize=ftell(fp);

    printf( "%s\n ",tempbuf);

    }

    if(t==NULL)

    {

    printf( "can 't   find   the   number\n ");

    return   1;

    }

    else

    {

    printf( "the   number   %s   is   found\n ",namebuf);

    printf( "end   here\n ");

    }

    printf( "enter   your   data   **:**\n ");

    printf( "yeye\n ");

    return   0;

    }

    int   modify(FILE   *fp)

    {

    char   *pointbuftemp;

    char   *buf,*buf2,*buftemp;

    int   rest;

    long   current,next,nextnext,departure;

    buf=(unsigned   char   *)malloc(1024);

    buftemp=(unsigned   char   *)malloc(1024);

    buf2=buf;

    current=ftell(fp);

    rest=1024;

    fgets(buf,rest,fp);

    next=ftell(fp);

    departure=0;

    while(fgets(buf,rest,fp)!=NULL)

    {

    nextnext=ftell(fp);

    departure=nextnext-next;

    next=ftell(fp);

    rest-=departure;

    buf+=departure;

    }

    fseek(fp,current,SEEK_SET);

    fgets(buftemp,1024,stdin);

    fputs(buftemp,fp);

    fputs(buf2,fp);

    printf( "fflush?\n ");

    return   0;

    }

    请问这是什么原因,应该怎么办呢?谢谢!!

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

    设这样的

    *searchname=(unsigned char)fgetc(stdin)!= ': '

    读完以后,缓冲区里的\n号没读取出来.在modify内再用fgets(buftmp,1024,stdin)读时就会把这个 '\n '读走.

    这样改一下就可以了:

    while((*searchname=(unsigned char)fgetc(stdin))!= ': ')

    {

    searchname++;

    }

    fgetc(stdin); //添加一句.

    不过说实话,楼主的程序有很多地方都是冗余的.

    你的malloc分配的空间,好象都没free吧.

    文章评论

    展开全文
  • fgets用法

    千次阅读 2018-04-03 15:03:41
    fgets()从文件或者流中获取字符串。stdin是标准输入流示例1:char strBuf[1024];fgets(strBuf, sizeof(strBuf), stdin); //处理strBuf示例2:FILE* fp = fopen("some_file.txt", "r")...
  • 但是 gets() 有一个非常大的缺陷,即它不检查预留存储区是否能够容纳实际输入的数据,换句话说,如果输入的字符数目大于数组的长度,gets 无法检测到这个问题,就会发生内存越界,所以编程时建议使用 fgets()。...
  • fgets实现

    千次阅读 2018-09-17 13:18:06
    char *fgets(char *s, int n, FILE *stream) { register int c; register char *cs; cs = s; while(--n &gt; 0 &amp;&amp; (c = getc(stream)) != EOF) { if((*cs++ = c) == '\n') {...
  • fgets函数功能

    2020-01-15 10:31:30
    fgets函数功能
  • 为了避免缓冲区溢出,从终端读取输入时应当用fgets()代替gets()函数。但是这也将带来一个问题,因为fgets()的调用格式是:fgets (buf, MAX, fp)fgets (buf, MAX, stdin)buf是一个char数组的名称,MAX是字符串的最大...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 5,730
精华内容 2,292
关键字:

fgets