Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMPSCI 210 Semester 1- 2015 Tutorial 8 – C programming language.

Similar presentations


Presentation on theme: "COMPSCI 210 Semester 1- 2015 Tutorial 8 – C programming language."— Presentation transcript:

1 COMPSCI 210 Semester 1- 2015 Tutorial 8 – C programming language

2 Exercise 8.1 Write a programme to create a file called “inst.txt” and write the following instruction into the file : Add R1, R2, R3 You need the following header only: #include Name the programme Ex8-1

3 Solution - Exercise 8.1 #include int main() { FILE *fp; fp= fopen("inst.txt","w+"); fprintf(fp,"Add R1, R2, R3\n"); fclose(fp); return 0; }

4 Exercise 8.2 Write another programme to open the file created in Exercise 8.1, and read the contents using “fgetc” command and print the content on the screen. You need the following header only: #include Name this program Ex8-2

5 Solution - Exercise 8.2 #include int main(){ FILE *fp; char c; fp=fopen("inst.txt","r"); c=fgetc(fp); while(c!=EOF){ printf("%c",c); c=fgetc(fp); } fclose(fp); return 0; }

6 Exercise 8.3 Expand your codes in Exercise 8.2 to detect the instruction written in “inst.txt” and print a message declaring the instruction. Your programme should be able to detect whether the instruction is ADD, AND or LD Note: Your programme should be able to convert the contents of the file to lowercase before doing any detection. You need to add the following headers: #include For example it must detect that the instruction written in the file is ADD and print a message like : “This is ADD instruction”

7 Solution - Exercise 8.3 #include int main() { FILE *fp; char c; char reader[100]; char delimiter[2]=" "; char *token; int i; fp=fopen("inst.txt","r"); c=fgetc(fp); i=0; while(c!=EOF){ printf("%c",c); reader[i]=tolower(c); i++; c=fgetc(fp); } fclose(fp); printf("%s", reader);

8 Solution - Exercise 8.3 cont. token=strtok(reader,delimiter); if(strcmp(token,"add")==0)printf("This is ADD instruction \n"); else if(strcmp(token,"and")==0)printf("This is AND instruction\n"); else if(strcmp(token,"ld")==0)printf("This is LD instruction\n"); return 0;}


Download ppt "COMPSCI 210 Semester 1- 2015 Tutorial 8 – C programming language."

Similar presentations


Ads by Google