views:

239

answers:

2

I want my program to display the unix windmill while processing. There's a for loop and in every iteration theres a printf function:

printf("Fetching articles (%c)\r",q);

q is one of the characters in the windmill (-\|/) depending on the iteration number.

The problem is - it seems like in 100 iterations there are only two changes in displayed line, and every iteration takes about one second to complete.

What could be the aouse for this?

Here's the whole loop with only two possible chars for the windmill:

for (int i=0;i<numb_articles;i++) {
  memset(file_path,0x0,BUFF_SIZE);

  url=article_urls[i];

  if (rules->print!=NO_PRINT) {
    url=modify_url(url,rules->printout,rules->print);
    if (url=="NULL")
      continue;
  }

  get_page(url,file_content);

  if (strcmp(rules->save.data(),"NULL")!=0)
    if (!check_save(rules->save,file_content,url))
      continue;

  at_least_one_saved=true;
  numb_articles_accepted++;

  encoding_list[i]=get_encoding(file_content);

  title=get_title(file_content,err_msg);

  if (title=="")
    continue;

  title_list[i]=strdup(title.data());
  filename=get_filename(title);

  int count=numb_fn_found(filename_list,i,filename.data());
  char *tmp = new char[10];
  if (count>0) {
    sprintf(tmp,"(%d)",count);
    filename.insert((size_t)filename.length(),tmp);
  }

  filename_list[i]=strdup(filename.data());

  char q;
  if (i%2==0)
    q='|';
  else q='-';

  printf("Fetching articles (%c)\r",q);

  ofstream output_file;
  sprintf(file_path,TMP_FILE,filename.data());
  strncat(file_path,".html",5);
  output_file.open(file_path);

  output_file << file_content;

  output_file.close();
}
+9  A: 

Flush the output after writing each line:

printf("Fetching articles (%c)\r",q);
fflush(stdout);

Without doing this, normally stdout is buffered and only dumps its output when a newline is seen, or its internal buffer fills up.

Greg Hewgill
Thanks, that workedI only had to write it like this:printf("\r");printf("Fetching articles (%c)",q);fflush(stdout);
@Bartek, ah that is what kept confusing me with the \r after the text :)
Johannes Schaub - litb
+2  A: 

The output (console) is buffered. That is, it only writes the output to the screen when the buffer is full or a newline is written. If you want to output characters one at a time, you will need to call fflush(stdout) explicitly to flush the output buffer.

Enjoy,

Robert C. Cartaino

Robert Cartaino
You may want to emend the part about the carriage return since that's precisely the character being printed.
Rob Kennedy
Fixed. I also left out that, technically, a full buffer doesn't flush until you try to write to it... and a few other misc reasons.
Robert Cartaino