80 likes | 162 Views
COMPSCI 210 Semester 2 - 2014. Tutorial 8 – C programming language. 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< stdio.h >
E N D
COMPSCI 210Semester 2- 2014 Tutorial 8 – C programming language
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<stdio.h> Name the programme Ex8-1.c
Solution - Exercise 8.1 #include<stdio.h> int main() { FILE *fp; fp= fopen("inst.txt","w+"); fprintf(fp,"Add R1, R2, R3\n"); fclose(fp); return 0; }
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<stdio.h> Name this program Ex8-2.c
Solution - Exercise 8.2 #include<stdio.h> 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; }
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<stdio.h> #include<string.h> #include<ctype.h> For example it must detect that the instruction written in the file is ADD and print a message like : “This is ADD instruction”
Solution - Exercise 8.3 #include<stdio.h> #include<string.h> #include<ctype.h> intmain() { FILE *fp; char c; char reader[100]; char delimiter[2]=" "; char *token; inti; 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);
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;}