C fgets()函数读取文件的用法示例

标准C库提供 fgets() 函数从指定流中读取一行,其中该流可以是文件。 fgets() 函数还用于从给定字符串中读取指定数量或大小的字符。在本教程中,我们将学习fgets()的用法  函数及其参数有不同的例子。

null

fgets()函数语法

fgets()的语法  功能非常简单。只有3个参数可以返回char数组 价值观。

char *fgets(char *str, int n, FILE *stream)

以下是参数的含义和用法信息。

  • char *str 是复制或获取字符串的字符串值 将被存储。
  • int n 读取字符的大小或计数。
  • FILE *stream 是我们要读取的流,通常是一个文件。

函数的返回值

如果函数执行成功完成 有一个返回值是char。如果到达流或文件的结尾并且没有读取任何字符,str的内容将保持不变,并返回空指针。

从文件中读出整行

例如,现在是时候了。我们将创建一个示例代码来读取文件 file.txt .  读取的字符串将放入字符串中。

  • char str[] 是存储读取的字符串的char数组。
  • FILE *f 是我们用来读取字符串的文件指针。
#include int main () {   //File pointer to store opened file information and cursor   FILE *f;   //str char array to stored read values or characters   char str[160];   /* opening file for reading */   f = fopen("file.txt" , "r");   if(f == NULL) {      perror("Error opening file");      return(-1);   }   if( fgets (str, 160, f)!=NULL ) {      /* writing content to stdout */      puts(str);   }   fclose(f);      return(0);}
Read From File Whole Line
从文件读取整行

我们将用文件名存储上面的代码 fgets.c 我们将使用以下命令编译。

$ gcc fgets.c -o fgets

以及  运行创建的 fgets 可执行文件如下。

$ ./fgets
Read From File Whole Line
从文件读取整行

从文件中读取指定字节数或大小的行

在本例中,我们将指定要读取的字符串大小。大小值将 作为fgets()的第二个参数提供  功能。在本例中,我们将从给定的文件中读取300个字符到 str 字符数组。

#include int main () {   //File pointer to store opened file information and cursor   FILE *f;   //str char array to stored read values or characters   char str[300];   /* opening file for reading */   f = fopen("file.txt" , "r");   if(f == NULL) {      perror("Error opening file");      return(-1);   }   if( fgets (str, 300, f)!=NULL ) {      /* writing content to stdout */      puts(str);   }   fclose(f);   return(0);}

相关文章: 什么是EOF(文件结尾)?PHP、C++、C、Python、java的例子

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享