【c&c++】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、编译执行结果

 

 

 



posted @   opensmarty  阅读(337)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
历史上的今天:
2020-02-10 【mysql】GPS应用
点击右上角即可分享
微信分享提示