C语言:fgets和fgetc函数读取文件

                      C语言:fgets和fgetc函数读取文件


1、fgetc 是 file get char 的缩写,意思是从指定的文件中读取一个字符。
      fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error.

2、fgets函数 char *fgets(char *str, int n, FILE *stream) 从指定的流 stream 读取一行,并把它存储在 str 所指向的字符串内。

      fgets()  reads in at most one less than size characters from stream and stores them into the buffer pointed to by s.  Reading stops after an EOF or a newline.  If a newline is read, it is stored into the buffer.  A terminating null byte ('\0') is stored after the last character in the buffer.

 

3、代码测试

      3.1 c文件fget_demo.c

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>


int fgets_function_demo(const *file_name)
{
	
	char line[1024], *ptr = NULL;
	FILE *fp = NULL;
    int n=0;
	printf("\n%s\n", __FUNCTION__);
	fp = fopen(file_name, "r");
	if (fp == NULL) {
		printf("Couldn't open %s\n",file_name);
		return 0;
	}

	while(fgets(line, 1024, fp)) {
		n++;
		printf("line %3d:%s\n",n,line);
	}

	fclose(fp);
	return 0;
}
 
 
int fgetc_function_demo(const *file_name)
{
    FILE *fp;
    char ch;
    printf("\n%s\n", __FUNCTION__);
    //如果文件不存在,给出提示并退出
   if( (fp=fopen(file_name,"rt")) == NULL ){
        printf("Fail to open file!");
		fclose(fp);
        return -1;
    }
    //每次读取一个字节,直到读取完毕
    while( (ch=fgetc(fp)) != EOF ){
        printf("%c ",ch);
    }
    printf("\n");  //输出换行符
    fclose(fp);
    return 0;

}
 
 
int main()
{
	fgets_function_demo("net_dev";
	fgetc_function_demo("net_dev");
    return 1;
}

 

    3、读取的net_dev文件内容。

static int create_bt_test_file_for_brcm(void)
{
	FILE* fp;
	if (fp != 0) {
		system("chmod 777 /userdata/bt_pcba_test");
		system("mount --bind /userdata/bt_pcba_test /usr/bin/bt_pcba_test");
		return 0;
	}
	return -1;
}

 

   4、编译执行结果

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值