所以我有这个文本文件,其中包含有关人们放在那里的东西的信息,还有这个数字代表它发布的日期 (dd/mm/yy)。
示例:此文本文件包含某些足球比赛的结果,谁赢得了赛季以及庆祝事件的地点
15042018 13:00
Marítimo Moreirense 1-1
15042018 14:00
Benfica Porto 0-1
16042018 13:00
Rio Ave Tondela 1-1
03052018 14:56
Porto wins the season!
03052018 16:00
The celebration will be in Aliados
现在假设今天的日期是 03/05/2018(对应于文件 03052018 中写入的最后日期),现在我想从那里打印其余部分,包括我找到该日期的行,如下所示:
03052018 14:56
Porto wins the season!
03052018 16:00
The celebration will be in Aliados
我的代码,我尝试使用 fseek()
,首先我计算 n 个字节,直到找到与今天日期对应的日期,然后我转到传递 n 个字节的文件并打印休息,但它失败了:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *users_info;
char datesearch[10];
users_info = fopen("TDesporto.txt", "w+");
int i=0;
time_t currentTime;
time(¤tTime);
struct tm *myTime = localtime(¤tTime);
int date = myTime->tm_mday*1000000 + myTime->tm_mon*10000+10000 + myTime- >tm_year+1900; //this is is going to give the number of today's date
while(!(strcmp(date,datesearch))){ //cicle ends when I find the number (datesearch) that is equal to todays date and will count the bytes until that point
fscanf(users_info, "%d", datesearch);
i++;
}
fseek(users_info,i,SEEK_SET);//going to n bytes into the file and print the rest
char line[100];
while(fgets(line, 100, users_info) != NULL)
{
printf("%s\n", line);
}
fclose(users_info);
return 0;
}
编辑:我忘了,这部分我实际上必须向后打印出来,所以它必须像这样出来
03052018 16:00
The celebration will be in Aliados
03052018 14:56
Porto wins the season!
最佳答案
要提取日期字符串,您可以使用 strftime()
喜欢
time_t t=time(NULL);
struct tm *a = localtime(&t);
strftime(d, 9, "%d%m%Y", a);
d
是字符串。
在用于strftime()
的格式字符串中,%d
、%m
和%Y
代表分别代表日、月和年(作为数字)。
然后您可以使用 strcmp()
在输入文件中找到该字符串的第一个实例。
char line[200], str[30];
long pos[100], ctr=0;
for(i=0; fgets(line, sizeof(line), fin); ++i)
{
if(i%3==0)
{
if(sscanf(line, "%29s", str)!=1 )
{
printf("\nSomething went wrong.");
return 1;
}
if(strcmp(str, d)==0)
{
pos[ctr++]=ftell(fin)-strlen(line);
break;
}
}
}
其中 pos
是一个数组,用于存储文件中的位置(使用 ftell()
获得)从那里读取应该稍后完成和 ctr
用于索引这个数组。
找到匹配项后,我们无需检查进一步的匹配项,只需记录应该读取的位置即可。让我们在另一个循环中执行此操作,如
for(i+=1; fgets(line, sizeof(line), fin); ++i)
{
if((i+1)%3==0)
{
pos[ctr++]=ftell(fin);
}
}
记录完所有位置后,我们将使用它们来显示输出
for(i=ctr-1; i>=0; --i)
{
fseek(fin, pos[i], 0);
for(int j=0; j<2; ++j)
{
if(fgets(line, sizeof(line), fin)==NULL)
{
break;
}
printf("%s", line);
}
printf("\n");
}
如前所述,您程序中的 date
是一个 int
,不能用作 strcmp()
的参数。
关于c - 在文本文件中查找特定数字并从该点开始打印文件的其余部分 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50295746/