【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 ('') 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%sn", __FUNCTION__);
    fp = fopen(file_name, "r");
    if (fp == NULL) {
        printf("Couldn't open %sn",file_name);
        return 0;
    }
 
    while(fgets(line, 1024, fp)) {
        n++;
        printf("line %3d:%sn",n,line);
    }
 
    fclose(fp);
    return 0;
}
 
 
int fgetc_function_demo(const *file_name)
{
    FILE *fp;
    char ch;
    printf("n%sn", __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、编译执行结果

 【c&c++】C语言:fgets和fgetc函数读取文件

 

 



原文链接: https://www.cnblogs.com/opensmarty/p/17109109.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    【c&c++】C语言:fgets和fgetc函数读取文件

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/317061

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 下午2:31
下一篇 2023年2月16日 下午2:32

相关推荐