3

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();
}
Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467

2 Answers2

9

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
  • 951,095
  • 183
  • 1,149
  • 1,285
2

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Robert Cartaino
  • 27,494
  • 6
  • 45
  • 67
  • You may want to emend the part about the carriage return since that's precisely the character being printed. – Rob Kennedy Jun 28 '09 at 20:18
  • 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 Jun 28 '09 at 20:32