我在使用日期时遇到一个小问题,而我需要在包含用户当前日期的.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);
有关如何使这项工作的任何想法? 谢谢。
答案 0 :(得分:0)
试试这个:
#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;
}