title: Switching writing from file to stdout using "sink()" in R
body: <p>I implemented the following procedure that aims to write some files and print a message in the end of each file when the writing is done:</p>
  
  <pre><code># Print one file per piaf
  output_dir_piafs &lt;- "OUTPUT_dataset_piafs"
  unlink(output_dir_piafs, recursive = TRUE, force = TRUE)
  dir.create(output_dir_piafs)
  for (i in 1:length(lst_sorted)) {
      sink()      # Generates warnings...
      filename &lt;- paste(output_dir_piafs, "/piaf_", i, ".txt", sep="")
      sink(file = filename, append = TRUE)
      sink(type = "message")
      cat("  ", colnames(file1), "\n")
  
      for (j in 1:length(lst_sorted[[i]])) {
          cat(j, " ")
          lapply( lst_sorted[[i]][[j]], 
                  function(x) { 
                      cat(as.character(x), " ")
                  }
          )
          cat("\n")
      }
  
      ## back to the console
      sink()
      cat(paste(filename, "done !\n"))
      #flush(stdout())        # Tested, no particular effect
  }
  </code></pre>
  
  <p>My problem is that, if I do not add a <code>sink()</code> at the very beginning of the loop, the final writing on the standard output (<code>cat(paste(filename, "done !\n"))</code>) has no effect. On the other hand, adding this early <code>sink()</code> generates warnings that I would like to avoid:</p>
  
  <pre><code>There were 50 or more warnings (use warnings() to see the first 50)
  &gt; warnings()
  Warning messages:
  1: In sink() : no sink to remove
  2: In sink() : no sink to remove
  3: In sink() : no sink to remove
  </code></pre>
  
  <p>Does anyone has an idea on how sink() behaves, and/or how to get rid of those warnings?</p>
  
  <p><em><strong>Note:</strong> I also tried <code>try(sink(), silent=TRUE)</code>, but the <code>silent</code> option prevents only from errors...</em></p>