Click to See Complete Forum and Search --> : EOF question


ubaka
01-27-2003, 08:01 AM
hey i was going through the Ncurses-HOWTO and stumbled on this example. can someone please explain this code> explain the role of the variable prev and how it works.


#include <ncurses.h>

int main(int argc, char *argv[])
{
int ch, prev;
FILE *fp;
int goto_prev = FALSE, y, x;

if(argc != 2)
{ printf("Usage: %s <a c file name>\n", argv[0]);
exit(1);
}
fp = fopen(argv[1], "r");
if(fp == NULL)
{ perror("Cannot open input file");
exit(1);
}

initscr(); /* Start curses mode */

prev = EOF;
while((ch = fgetc(fp)) != EOF)
{ if(prev == '/' && ch == '*') /* If it is / and * then olny
* switch bold on */
{ attron(A_BOLD);
goto_prev = TRUE; /* Go to previous char / and
* print it in BOLD */
}
if(goto_prev == TRUE)
{ getyx(stdscr, y, x);
move(y, x - 1);
printw("%c%c", '/', ch); /* The actual printing is done
* here */
ch = 'a'; /* 'a' is just a dummy
* character to prevent */
// "/*/" comments.
goto_prev = FALSE; /* Set it to FALSE or every
* thing from here will be / */
} else
printw("%c", ch);
refresh();
if(prev == '*' && ch == '/')
attroff(A_BOLD); /* Switch it off once we got *
and then / */
prev = ch;
}
getch();
endwin(); /* End curses mode */
return 0;
}

truls
01-27-2003, 08:37 AM
From a quick glance here's my take on this:

prev and ch are of type char, which means they hold a single character.
The routine goes through a text file printing the text. When it encounters the string "/*", which starts a comment, it turns on bold mode. When it encounters the string "*/", which ends a comment, it turns off bold mode.

When prev='/' and ch='*' you have the string "/*", i.e. the start of a comment.
When prev='*' and ch='/' you have the string"*/", i.e. the end of a comment.

So prev is basically just a variable holding the previously read character from the file. ch holds the currently read character.

ubaka
02-05-2003, 04:47 AM
thanx ;)