0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

コンパイラ 字句解析 文字読み取り

Last updated at Posted at 2020-12-31

「コンパイラ 作りながら学ぶ」
中田育男 著
の、p51コードを、参考にしました、メモ書きです。

#include <stdio.h>
#define MAXLINE 120
// コンパイラ 字句解析 文字読み取り

static FILE *fpi;
static FILE *fpo;
static char line[MAXLINE];
static int lineIndex = -1;

char nextChar()
{
    char ch;
    if (lineIndex == -1){
        if (fgets(line, MAXLINE, fpi) != NULL){
            fputs(line, fpo);
            lineIndex = 0;
        } else {
            printf("end of file\n");
            exit(1);
        }
    }
    if ((ch = line[lineIndex++]) == '\n'){
        lineIndex = -1;
        return ' ';
    }
    return ch;
}


int main(){

    char ch;

    //ファイルを読み込みモード、書き込みモードで開く

    fpi = fopen("test.pl0","r");
    fpo = fopen("test2.pl0","w");

    //次の文字を 3回出力

    ch = nextChar();
    printf("%c\n", ch);
    ch = nextChar();
    printf("%c\n", ch);
    ch = nextChar();
    printf("%c\n", ch);
        

    //ファイルオープンに失敗した場合

    if(fpi==NULL || fpo==NULL){

        //失敗と表示し終了

        printf("ファイルオープン失敗\n");

        return -1;

    }

    //ファイルを閉じる

    fclose(fpi);
    fclose(fpo);

    return 0;

}

参考サイト: http://www.isl.ne.jp/pcsp/beginC/C_Language_16.html

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?