fgets函数

来源:互联网 发布:pkpm软件pmsap什么锁 编辑:程序博客网 时间:2024/05/16 01:14


1函数 (ISO C)

函数原型:char *fgets(char *buf, int bufsize, FILE *stream);
参数:
*buf: 字符型指针,指向用来存储所得数据的地址。
bufsize: 整型数据,指明存储数据的大小。
*stream: 文件结构体指针,将要读取的文件流。
功能:
注意:《UNIX 环境高级编程》中指出,每次调用fgets函数会造成标准输出设备自动刷清!案例详见《UNIX环境高级编程(第二版)》中程序清单1-5和课后习题5.7,习题5.7的答案中给出了相关的论述。
stream文件流指针体指向文件内容地址的偏移原则
如果使用fgets()读取某个文件,第一次读取的bufsize为5,而文件的第一行有10个字符(算上'\n'),那么读取文件的指针会偏移至当前读取完的这个字符之后的位置。也就是第二次再用fgets()读取文件的时候,则会继续读取其后的字符。而,如果使用fgets() 读取文件的时候bufsize大于该行的字符总数加2(多出来的两个,一个保存文件本身的'\n'换行,一个保存字符串本身的结束标识'\0'),文件并不会继续读下去,仅仅只是这一行读取完,随后指向文件的指针会自动偏移至下一行。
例:
如果一个文件的当前位置的文本如下
Love, I Have
Since you can do it.
如果用fgets(str1,6,file1);去读取
则执行后str1 = "Love," ,读取了6-1=5个字符
这个时候再执行fgets(str1,20,file1)则执行后str1 = " I Have\n"
而如果
fgets(str1,23,file1);
则执行str1="Love ,I Have",读取了一行(包括行尾的'\n',并自动加上字符串结束符'\0'),当前文件位置移至下一行,虽然23大于当前行上字符总和,可是不会继续到下一行。而下一次调用fgets()继续读取的时候是从下一行开始读。


Return Value(返回值)

On success, the function returns str.(执行成功则返回第一个参数)
If the end-of-file is encountered while attempting to read a character, theeof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents ofstr remain unchanged).(如果遇到eof,eof indicator被设置)(如果还没有读内容就遇到eof则返回NULL,str还是原来的值)
If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed bystr may have changed).
(如果遇到读取错误,error indicator被设置,返回空指针,str的值可能被设置——读到一半出错了!)

2序例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <string.h>
#include <stdio.h>
int main(void)
{
    FILE*stream;
    charstring[] ="This is a test";
    charmsg[20];
    /* open a file for update */
    stream =fopen("DUMMY.FIL","w+");
    /* write a string into the file */
    fwrite(string,strlen(string), 1, stream);
    /* seek to the start of the file */
    fseek(stream, 0, SEEK_SET);
    /* read a string from the file */
    fgets(msg,strlen(string)+1, stream);
    /* display the string */
    printf("%s", msg);
    fclose(stream);
    return0;
}
fgets函数用来从文件中读入字符串。fgets函数的调用形式如下:fgets(str,n,fp);此处,fp是文件指针;str是存放在字符串的起始地址;n是一个int类型变量。函数的功能是从fp所指文件中读入n-1个字符放入str为起始地址的空间内;如果在未读满n-1个字符之时,已读到一个换行符或一个EOF(文件结束标志),则结束本次读操作,读入的字符串中最后包含读到的换行符。因此,确切地说,调用fgets函数时,最多只能读入n-1个字符。读入结束后,系统将自动在最后加'\0',并以str作为函数值返回。
函数原型是:char *fgets(char *s, int n, FILE *stream);

摘自百度百科 http://baike.baidu.com/view/656654.htm

和 http://www.cplusplus.com/reference/cstdio/fgets/


0 0
原创粉丝点击