Testo dell'esercizio
realizzare un "precompilatore" che legendo un file c realizzi un nuovo file con le seguenti caratterstiche :
- numerazione di riga
- tutte le istruzioni che prevedono l'include devono essere sostituite con il contenuto dell'include espresso da #include<nome>
- eliminare tutte le righe commentate, presupponendo che i commenti siano messi in righe dedicate
- eliminare le righe vuote
usare la funzione substr, fgets, fputs, explode, strlen
mostra soluzione
016 | $f1 = fopen ( $f_name , "r" ) or die ( "impossibile aprire il file\n" ); |
017 | $f2 = fopen ( "new_" . $f_name , "w" ) or die ( "impossibile creare il file\n" ); |
019 | fputs ( $f2 ,leggi( $f1 )); |
023 | function leggi( $file ){ |
028 | $stringa = fgets ( $file ); |
031 | if ( $stringa == "" || $stringa == "\n" ) |
035 | if (commento( $stringa )) |
039 | if (( $str = f_include( $stringa ))!= "" ) |
043 | $stringa = $riga . "\t" . $stringa ; |
051 | function commento( $stringa ){ |
053 | static $commento_multiriga = false; |
057 | if (cerca( $stringa , "/*" )){ |
058 | $commento_multiriga = true; |
062 | if (cerca( $stringa , "//" )) |
065 | if ( $commento_multiriga && cerca( $stringa , "*/" )){ |
066 | $commento_multiriga = false; |
070 | if ( $commento_multiriga == true) |
078 | function cerca( $stringa , $ele ){ |
079 | if ( count ( explode ( $ele , $stringa ))>1) |
085 | function f_include( $stringa ){ |
089 | $stringa = explode ( "<" , $stringa ); |
090 | if ( count ( $stringa )!=2 || cerca( $stringa [0], "#include" )===false) |
092 | $stringa = explode ( ">" , $stringa [1]); |
093 | $stringa = $stringa [0]; |
100 | $f = fopen ( "/usr/include/" . $stringa , "r" ) or die ( "impossibile aprire il file di header\n" ); |
103 | if (( $str = fgets ( $f ))!= "" ){ |
104 | $stringa .= $riga . "\t" . $str ; |
torna