Alex_tz307

Parsing C

Sep 14th, 2020
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. #define MAXLOG10 10
  2. #define BUFSIZE (128 * 1024)
  3.  
  4. FILE *fin, *fout;
  5. int p10[MAXLOG10 + 1] = { 0, 1, 10, 100, 1000, 10000, 100000, 1000000,
  6.   10000000, 100000000, 1000000000 }; // santinela pe prima pozitie
  7. int rpos; char rbuf[BUFSIZE];
  8. int wpos; char wbuf[BUFSIZE];
  9.  
  10. // initializare citire
  11. static inline void initRead() {
  12.   rpos = BUFSIZE - 1;
  13. }
  14.  
  15. // citire caracter
  16. static inline char readChar() {
  17.   if ( !(rpos = (rpos + 1) & (BUFSIZE - 1)) )
  18.     fread( rbuf, 1, BUFSIZE, fin );
  19.   return rbuf[rpos];
  20. }
  21.  
  22. // citire intreg cu semn
  23. int readInt() { // citeste un intreg
  24.   int ch, res = 0, semn = 1;
  25.  
  26.   while ( isspace( ch = readChar() ) );
  27.   if ( ch == '-' ) {
  28.     semn = -1;
  29.     ch = readChar();
  30.   }
  31.   do
  32.     res = 10 * res + ch - '0';
  33.   while ( isdigit( ch = readChar() ) );
  34.  
  35.   return semn * res;
  36. }
  37.  
  38. // initializare scriere
  39. static inline void initWrite() {
  40.   wpos = 0;
  41. }
  42.  
  43. // scriere caracter
  44. static inline void writeChar( char ch ) {
  45.   wbuf[wpos] = ch;
  46.   if ( !(wpos = (wpos + 1) & (BUFSIZE - 1)) )
  47.     fwrite( wbuf, 1, BUFSIZE, fout );
  48. }
  49.  
  50. // scriere intreg cu semn
  51. void writeInt( int x ) {
  52.   int i, cf;
  53.  
  54.   if ( x < 0 ) {
  55.     writeChar( '-' );
  56.     x = -x;
  57.   }
  58.   i = MAXLOG10;
  59.   while ( p10[i] > x )
  60.     i--;
  61.   if ( i == 0 )
  62.     writeChar( '0' );
  63.   else
  64.     do {
  65.       cf = '0';
  66.       while ( p10[i] <= x ) {
  67.         x -= p10[i];
  68.         cf++;
  69.       }
  70.       writeChar( cf );
  71.     } while ( --i > 0 );
  72.  
  73.   writeChar( ' ' ); // separatorul, poate sa difere ('\n'?)
  74. }
  75.  
  76. // scrie caracterele ramase in buffer
  77. static inline void flushBuf() {
  78.   fwrite( wbuf, 1, wpos, fout );
  79. }
  80.  
  81.  
  82. Utilizare:
  83.  
  84. fin = fopen( "input.in", "r" );
  85.   initRead();
  86.   n = readInt();
  87.   // ... alte citiri
  88.   fclose( fin );
  89.  
  90.   fout = fopen( "input.out", "w" );
  91.   initWrite();
  92.   writeInt( n );
  93.   // ... alte scrieri
  94.   flushBuf();
  95.   fclose( fout );
Advertisement
Add Comment
Please, Sign In to add comment