Chet stupid how to write the result to a file.

#include <assert.h> #include <stdio.h> int main () { int a, b; int r = scanf ("%d%d", &a, &b); assert (r == 2); printf ("%d\n", a + b); return 0; } 
  • 2
    You need to open the file using the fopen function and write data there, for example, using fprintf - Vlad from Moscow
  • one
    As I understand it, the result is pulling at least as much as the Nobel Prize, and it must be recorded in the tablet of the history of Mankind! - Vlad from Moscow

3 answers 3

In principle, the code needs to be modified for this and it is not necessary :) It is enough to run the resulting program with the redirection of the standard output to the file:

 ./program > H.txt 

If this does not suit, then there are at least two options:

  1. man fopen , man fwrite , man fprintf
  2. man open , man write

    If this is for solving the Olympiad problem, then

     freopen("h.txt", "w", stdout); 

      Well, and finally, what you most likely need. :)

       #include <stdio.h> #include <assert.h> int main( void ) { FILE *fp; int a, b; int r = scanf ("%d%d", &a, &b); assert( r == 2 ); fp = fopen( "H.txt", "w" ); assert( fp != NULL ); if ( fp ) { fprintf ( fp, "%d\n", a + b ); fclose( fp ); } return 0; } 

      It is better to calculate the result as having the type long long int , and write

        fprintf ( fp, "%lld\n", ( long long int )a + b ); 

      since the addition of two integers of the same type can lead to overflow.

      • one
        If the first assert still something that can be justified (but it is doubtful ...), then the second is definitely nothing :) - PinkTux
      • one
        @PinkTux You err. assert is deactivated by the preprocessor directive NDEBUG in the final version. program A at the debugging stage, it is useful as a means of error reporting. - Vlad from Moscow
      • Here about NDEBUG I also speak. What is good that in the release version no diagnostics will be in case of an error? In my pampas, such a code will simply not be reviewed. And if it repeats often, you can grab a candelabrum :-) - PinkTux
      • @PinkTux In the release version, after it verifies that the file is being created, it can add a more advanced diagnostic system using the if clause. :) In the meantime, we do not know what he is going to do in case of an error opening the file. - Vlad from Moscow
      • I am afraid that a person who does not know about fopen may copy the code as true in everything, and not even guess that assert can disappear :-) - PinkTux