Why does printf return a value?

前端 未结 6 1835
自闭症患者
自闭症患者 2021-01-11 11:05

I know that printf returns a negative error or number of characters printed on success. Only reason to check this return value is if the execution of program s

6条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-11 11:31

    One of the main reasons why this is used is for troubleshooting. Printf can be used to also write to a file (not only STDOUT). Ensuring that all the charachters have been writen to the file is crucial in some applications. An example of this can be found below:

    #include 
    #include 
    
    int main(void)
    {
      FILE *fp;
    
      printf("This will display on the screen.\n");
    
      if((fp=freopen("OUT", "w" ,stdout))==NULL) {
        printf("Cannot open file.\n");
        exit(1);
      }
    
      if( printf("This will be written to the file OUT.") < 0){
          return -1;
      }
    
      fclose(fp);
    
      return 0;
    }
    

    You might ask why you should use printf to print a file. Consider this. Some software was developed that had no error logging implemented but instead used printf. A knowledgeable C programmer can redirect the output of printf to a file at the top of the code and thus implement error logging to a file instead of STDOUT. At this point he can use the return value of printf to ensure that the these errors were printed correctly.

提交回复
热议问题