2023年5月4日 星期四

小凱week12

 第一節課

week12-1

codeblock開新檔案,打上程式碼,執行後桌面會出現一個file.txt檔會寫(Hello World在檔案裡)。
#include <stdio.h>
int main()
{
    FILE*fout =fopen("file.txt","w");
    printf("Hello World\n");
    fprintf(fout,"Hello World在檔案裡\n");
}

week12-2

會把剛剛的file.txt讀進來。
#include <stdio.h>
int main()
{
    char line[20];
    FILE*fin =fopen("file.txt","r");
    fscanf(fin,"%s",line);
    printf("讀到了:%s\n",line);
    fscanf(fin,"%s",line);
    printf("讀到了:%s\n",line);
}

week12-3

會透過字串另存成一個file3.txt檔,後透過程式把字串叫進來。

第二節課

week12-4_keyboard_mouse

寫程式碼讓茶壺透過滑鼠點擊來改變位置。
#include <GL/glut.h>
float teapotX=0,teapotY=0;
void display()
{
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
    glTranslatef(teapotX,teapotY,0);
    glutSolidTeapot(0.3);
    glPopMatrix();
    glutSwapBuffers();
}
void mouse(int button,int state,int x,int y)
{
    teapotX=(x-150)/150.0;
    teapotY=(150-y)/150.0;
    display();
}
int main(int argc,char** argv)
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE|GLUT_DEPTH);
    glutCreateWindow("week12");

    glutDisplayFunc(display);
    glutMouseFunc(mouse);

    glutMainLoop();
}
結合上一個檔案,加入鍵盤控制。(執行後會在freeglut>bin內建一個file4.txt檔案)
#include <stdio.h>
#include <GL/glut.h>
float teapotX=0,teapotY=0;
FILE*fout=NULL;
FILE*fin=NULL;
void display()
{
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
    glTranslatef(teapotX,teapotY,0);
    glutSolidTeapot(0.3);
    glPopMatrix();
    glutSwapBuffers();
}
void mouse(int button,int state,int x,int y)
{
    teapotX=(x-150)/150.0;
    teapotY=(150-y)/150.0;
    if(state==GLUT_DOWN){
        if(fout==NULL) fout=fopen("file4.txt","w");
        fprintf(fout,"%f %f\n",teapotX,teapotY);
    }
    display();
}
void keyboard(unsigned char key,int x,int y)
{
    if(fin==NULL){
        fclose(fout);
        fin=fopen("file4.txt","r");
    }
    fscanf(fin,"%f%f",&teapotX,&teapotY);
    display();
}
int main(int argc,char** argv)
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE|GLUT_DEPTH);
    glutCreateWindow("week12");

    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutMouseFunc(mouse);

    glutMainLoop();
}

第三節課

發現上個檔的file4.txt檔的位置很奇怪,是因為歷史餘毒,要做修改,檔案按滑鼠右鍵選最下面的properties,把路徑修改成.,再用notepad++開起來,發現路徑更改。

沒有留言:

張貼留言