fgets 函数

本文详细介绍了fgets函数的使用方法,包括其调用形式、功能以及如何将其应用于文件读取操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

fgets函数用来从文件中读入字符串。

fgets函数的调用形式如下:fgets(str,n,fp);

此处,fp是文件指针;str是存放在字符串的起始地址;

n是一个int类型变量。

函数的功能是从fp所指文件中读入n-1个字符放入str为起始地址的空间内;

如果在未读满n-1个字符之时,已读到一个换行符或一个EOF(文件结束标志),则结束本次读操作,读入的字符串中最后包含读到的换行符。

因此,确切地说,调用fgets函数时,最多只能读入n-1个字符。读入结束后,系统将自动在最后加'\0',并以str作为函数值返回。

 

       #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;

  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值