c语言 文件中读取指定内容

2025-04-07 19:07:18
推荐回答(2个)
回答1:

#include
#include
#include

#define BUF_SIZE 1024
#define KEY "AB2345"
#define KEY_LEN 7

int main()
{
int ch = 0;
int first = 1;//开始时的标志,因为是一个字符一个字符的扫描
int flag = 0;//文件开头是不是所要读内容的标志
int count = 0;//遇到'\n'的个数
int pre_pos = 0, cur_pos = 0;//前一次和当前文件指针的位置
char buf[BUF_SIZE] = {0};
FILE *fp = NULL;

fp = fopen("test.txt", "r");
if (fp == NULL)
{
printf("Cann't open the file!\n");
exit(1);
}
else
{
while ((ch = fgetc(fp)) != EOF)
{
if (first)
{
//若要读取的内容在文件开头就有时
//移动指针到文件开头
fseek(fp, -1L, SEEK_CUR);
fgets(buf, KEY_LEN, fp);
if (strcmp(buf, KEY) == 0)
{
first = 0;
flag = 1;
continue;
}
else
{
first = 0;
}
}
if (ch == '\n')
{
count++;//遇到'\n'的个数
pre_pos = cur_pos;//上次遇到'\n'时文件指针的位置
cur_pos = ftell(fp);//当前遇到'\n'时文件指针的位置

//文件开头内容符合要求的就适当移动指针位置
//然后读取输出来
if (count == 1 && flag == 1)
{
fseek(fp, 0L, SEEK_SET);
memset(buf, 0, sizeof(buf));
fgets(buf, cur_pos - 1, fp);
printf("%s\n", buf);
}
//之后内容符合要求的就适当移动指针位置
//然后读取输出来
else
{
memset(buf, 0, sizeof(buf));
fgets(buf, KEY_LEN, fp);
if (strcmp(buf, KEY) == 0)
{
fseek(fp, (-1) * (KEY_LEN - 1), SEEK_CUR);
memset(buf, 0, sizeof(buf));
fgets(buf, cur_pos-1-pre_pos, fp);
printf("%s\n", buf);
}
}
}
}
}
fclose(fp);

return 0;
}

回答2:

没有办法,必须自己解析。C语言可是非常底层的语言,没有那么多好用的特性啦。