一、读文件
从文件里读取数据进行处理:
1.文件读取内容,筛选字符串
处理、、C 库函数 char *fgets(char *str, int n, FILE *stream) 从指定的流 stream 读取一行,并把它存储在 str 所指向的字符串内。当读取 (n-1) 个字符时,或者读取到换行符时,或者到达文件末尾时,它会停止,具体视情况而定。配合strstr等字符相关函数可对获取的字符进行处理
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define TEST_FILE "test_files"
int get_file()
{
FILE *fp = NULL;
char tmp_buf[128] ={0};
fp = fopen(TEST_FILE,"r");
if(fp == NULL)
{
printf("open file error \n");
return -1;
}
while(fgets(tmp_buf,sizeof(tmp_buf),fp) != NULL)
{
if(strstr(tmp_buf,"ad") != NULL)
{
printf("tmp_buf is %s\n",tmp_buf);
}
}
return 0;
}
int main()
{
get_file();
return 0;
}
二、写文件
按照需求格式创建配置文件:
C 库函数 int fprintf(FILE *stream, const char *format, ...) 发送格式化输出到流 stream 中。
#include </home/yang/codetest/test.h>
#define TEST_FILE "test_files"
int set_file()
{
FILE *fp = NULL;
fp = fopen(TEST_FILE,"w");
if(fp == NULL)
{
return -1;
}
fprintf(fp,"test file\n ");//cover
return 0;
}
int main()
{
set_file();
return -1;
}
三、sscanf和fscanf
sscanf:格式化输入函数
C 库函数 int sscanf(const char *str, const char *format, ...) 从字符串读取格式化输入。
配合正则表达式使用
fscanf://不安全函数
C 库函数 int fscanf(FILE *stream, const char *format, ...) 从流 stream 读取格式化输入。
- stream -- 这是指向 FILE 对象的指针,该 FILE 对象标识了流。
- format -- 这是 C 字符串,包含了以下各项中的一个或多个:空格字符、非空格字符 和 format 说明符