【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 @ 2023-02-10 15:26  opensmarty  阅读(205)  评论(0编辑  收藏  举报