c语言文件操作函数fgets,C语言fgets函数按行读取文件

这篇博客介绍了在C语言中如何利用fgets和fgetws函数实现按行读取文件内容。由于C语言没有getline()函数,fgets通过设置缓冲区大小可以达到类似效果。文章提供了示例代码,展示如何打开文件并搜索特定字符串,强调了这两个函数在遇到换行符或文件结束时停止读取的特点。同时,还提及了它们在不同平台和库中的兼容性信息。
摘要由CSDN通过智能技术生成

fgets, fgetws

Get a string from a stream.C语言没有像C++、Python语言的getline()函数,无法读取文件的某一行。然而,C语言有fgets()函数,该函数返回string类型,关键是该函数遇到换行符或EOF,则读取结束。利用这一特点,我们可以设置n为适当的缓冲区大小,即可以实现按行读取。

char *fgets( char *string, int n, FILE *stream );

wchar_t *fgetws( wchar_t *string, int n, FILE *stream );

Function Required Header Compatibility

fgets ANSI, Win 95, Win NT

fgetws or ANSI, Win 95, Win NT

For additional compatibility information, see Compatibility in the Introduction.

Libraries

LIBC.LIB Single thread static library, retail version

LIBCMT.LIB Multithread static library, retail version

MSVCRT.LIB Import library for MSVCRT.DLL, retail version

Return Value

Each of these functions returns string. NULL is returned to indicate an error or an end-of-file condition. Use feof or ferror to determine whether an error occurred.

Parameters

string

Storage location for data

n

Maximum number of characters to read

stream

Pointer to FILE structure

Remarks

The fgets function reads a string from the input stream argument and stores it in string. fgets reads characters from the current stream position to and including the first newline character, to the end of the stream, or until the number of characters read is equal to n – 1, whichever comes first. The result stored in string is appended with a null character. The newline character, if read, is included in the string.

fgets is similar to the gets function; however, gets replaces the newline character with NULL. fgetws is a wide-character version of fgets.

fgetws reads the wide-character argument string as a multibyte-character string or a wide-character string according to whether stream is opened in text mode or binary mode, respectively. For more information about using text and binary modes in Unicode and multibyte stream-I/O, see Text and Binary Mode File I/O and Unicode Stream I/O in Text and Binary Modes.

e.g:

#include "StaticLib.h"

#include "stdio.h"

#include "string.h"

bool fnShow()

{

char cFileName[] = "..\\StaticLib\\StaticLib.h";

char cFind[] = "extern";

char cLine[1024];

int iBuff = 1024;

FILE *fp;

fp = fopen(cFileName,"r");

if(NULL == fp)

{

printf("打开文件失败!\n");

return false;

}

while(!feof(fp))

{

fgets(cLine,iBuff,fp);

if(strstr(cLine,cFind))

{

printf("%s",cLine);

}

}

fclose(fp);

return true;

}

1289851923935076352.htm

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值