c语言中fgets操作方法,求一简单程序示范

如题所述

fgets为stdin.h头文件中声明的,从文件中读取字符串的函数。

原型:

char *fgets(char *buf, int bufsize, FILE *stream);

参数:

    buf: 指向用来存储字符串的内存位置。

    bufsize: 读取数据的大小。

    stream: 将要读取的文件流。

fgets最多从文件中读取bufsize-1个字符,若读取的行不足bufsize-1个字符,则读取完这行后就结束;若读取的行超过bufsize-1个字符,则只读取bufsize-1个字符,下次调用fgets时,将从此行未读取完的位置继续读取。


示例:

#include <stdio.h>

int main()
{
    char s[60];
    FILE *fin = fopen("a.txt", "r");
    
    fgets(s, 60, fin);
    puts(s);
    fclose(fin);
    
    return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-10-03
#include <string.h>
  #include <stdio.h>
  int main(void)
  {
  FILE *stream;
  char string[] = "This is a test";
  char msg[20];
  /* 打开一个文件 */
  stream = fopen("DUMMY.FIL", "w+");
  /*向文件中写入测试字符串“this is a test” */
  fwrite(string, strlen(string), 1, stream);
  /* 操作指针指向文件头 */
  fseek(stream, 0, SEEK_SET);
  /* 从文件中读取一定长度的字符串 */
  fgets(msg, strlen(string)+1, stream);
  /* 打印字符串 */
  printf("%s", msg);
  fclose(stream);
  return 0;
  }本回答被提问者采纳
第2个回答  2011-10-03
从流中读一行或指定个字符,   原型是char *fgets(char *s, int n, FILE *stream);   从流中读取n-1个字符,除非读完一行,参数s是来接收字符串,如果成功则返回s的指针,否则返回NULL。   形参注释:*s结果数据的首地址;n-1:一次读入数据块的长度,其默认值为1k,即1024;stream文件指针
fgets函数用来从文件中读入字符串。fgets函数的调用形式如下:fgets(str,n,fp);此处,fp是文件指针;str是存放在字符串的起始地址;n是一个int类型变量。函数的功能是从fp所指文件中读入n-1个字符放入str为起始地址的空间内;如果在未读满n-1个字符之时,已读到一个换行符或一个EOF(文件结束标志),则结束本次读操作,读入的字符串中最后包含读到的换行符。因此,确切地说,调用fgets函数时,最多只能读入n-1个字符。读入结束后,系统将自动在最后加'\0',并以str作为函数值返回。
第3个回答  2011-10-03
用 法: char *fgets(char *string, int n, FILE *stream);
程序例:

#include <string.h>
#include <stdio.h>

int main(void)
{
FILE *stream;
char string[] = "This is a test";
char msg[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);
return 0;
}

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网