c - 在 .txt 文件中查找今天的日期并打印行?

标签 c date

我在处理日期时遇到了一个小问题,而我需要打印包含用户当前日期的 .txt 文件中的所有行。

这是我的代码:

//My function
int search(FILE *fp, char * str)
{
    FILE *fp1;
    fp1 = fopen("fp1","w");
    char s[10],c;
    int len = strlen(str);
    int i = 0;
    int d;
    int seek = fseek(fp, 0, 0);
    c = fgetc(fp);
    while (c != EOF)
    {
        if (c == ' ' || c == '\n')
        {
            s[i] = '\0';
            i = 0;
            if (strcmp(s, str) == 0)
            {
                while (c = fgetc(fp) != '\n')
                {
                    fseek(fp, -2L, 1);
                    d = ftell(fp);
                }
                while ((c = fgetc(fp)) != '\n')
                {
                    fputc(c, fp1);
                }
            }
        }
        else
        {
            s[i] = c;
            i++;
        }
        c = fgetc(fp);
    }
    return 1;
}

//int main function callback
            printf("\n\nTasks due today("__DATE__"): \n");
            FILE *tasks = fopen("tasks.txt", "r+");
            search(tasks, __DATE__);
            fclose(tasks);

知道如何让它发挥作用吗? 谢谢。

最佳答案

试试这个:

#include <stdio.h>
#include <string.h>

int search(FILE *fp, const char *str){
    FILE *fp1;
    fp1 = fopen("fp1","w");
    if(!fp || !fp1 || !str || !*str)
        return 0;

    char line[128];
    while(fgets(line, sizeof line, fp)){
        if(strstr(line, str)){
            fputs(line, fp1);
        }
    }
    fclose(fp1);
    return 1;
}

int main(void){
    printf("\n\nTasks due today(\"%s\"): \n", __DATE__);
    FILE *tasks = fopen("tasks.txt", "r");
    search(tasks, __DATE__);//Note that __DATE__ is at the time of compilation.
    fclose(tasks);
    return 0;
}

关于c - 在 .txt 文件中查找今天的日期并打印行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37141932/

相关文章:

sql - 如何在 SQL Server 中获取今天的第一个小时?

javascript - 新日期 ("")添加 GMT 时间

ios - 如何获取周一、周二等工作日的本地化字符串表示形式?

c - 返回字符串中包含子字符串的第一个索引的递归函数

c - 链表语法

c - 空函数但函数参数出现段错误

php - 修复旧的 MySQL 日期字段错误

c - 将 c short 分配给 Ada short_integer

c - 由于大小分配导致的数组错误

MySQL 按时间段对订单中的不同客户进行计数