I'm trying to find all data for a day (Monday, Tuesday...) and write the data below. My txt document is written as:
Monday .......
..............
..............
Tuesday.......
..............
..............
Monday........
..............
..............
The only thing that is separating days is an empty line.
I successfully find the day in a file, the problem is that I need to print all the data until an empty line occurs.
For instance, if I select Monday(selectedday="Monday"
), my output should be:
Monday .......
..............
..............
Monday .......
..............
..............
The code I've tried:
int main()
{
char string[100], selectedday[] = "monday"; //for Monday
FILE* openbill;
openbill= fopen("bill.txt", "r");
if (openbill== NULL)
{
printf("Failed to open bill\n");
return NULL;
}
while (fscanf(openbill, "%s", string) == 1)
{
if (strstr(openbill, selectedday) != 0)
{
printf("%s", string);
}
}
}
Thank you for your help.
The scanset %2[\n]
tells fscanf
to scan up to two characters and only scan newlines.
The format string "%99s"
tells fscanf
to scan up to 99 non-whitespace characters into string
. This allows room for the terminating zero.
output
is a flag that is set to 1
when the day is found and set to 0
when a pair of newlines is scanned. A 1
enables output and string
will be printed.
#include <stdio.h>
#include <string.h>
void showday ( char *selectedday) {
char string[100] = "";
char newline[3] = "";
int result = 0;
int output = 0;
FILE* openbill = NULL;
openbill = fopen ( "bill.txt", "r");
if ( openbill == NULL) {
perror ( "bill.txt");
return;
}
do {
string[0] = 0;//set empty string
if ( 1 == ( result = fscanf ( openbill, "%2[\n]", newline))) {
if ( output) {//enabled
printf ( "%s", newline);
}
if ( '\n' == newline[1]) {//two newlines
output = 0;//disable
}
}
else {
result = fscanf ( openbill, "%99s", string);
if ( strstr ( string, selectedday)) {
output = 1;//enable
}
}
if ( output && string[0]) {//enabled and string not empty
printf ( "%s ", string);
}
} while ( EOF != result);
fclose ( openbill);
}
int main ( void) {
showday ( "monday");
return 0;
}