You are on page 1of 3

// Program #1 // Display file to screen #include <stdio.h> #include <iostream.h> #include <string.h> void main(void) { FILE* fl; fl = fopen("test.

txt","r"); if(fl==NULL) return; char ch; while( (ch = fgetc(fl)) != EOF ) printf("%c",ch); } // Program #2 // Count white spaces and characters #include <stdio.h> #include <iostream.h> #include <string.h> void main(void) { FILE* fl; long no_sp=0; long no_ch=0; fl = fopen("test.txt","r"); if(fl==NULL) return; char ch; while( (ch = fgetc(fl)) != EOF ) { switch(ch){ case ' ': no_sp++; no_ch++; default: no_ch++; } } cout << "Number of white spaces: " << no_sp << endl; cout << "Number of Characters: " << no_ch << endl; } #include <stdio.h> #include <iostream> #include <string> using namespace std; #define WORD 1 #define SPC 2 string token;

int GetToken(FILE* fi){ char ch; switch(ch=fgetc(fi)) { case ' ': token = ch; return SPC; case EOF: return EOF; default: token = ch; return WORD; } } // Program #2 // Count words void main(void) { FILE* fl; long no_wr=0; long no_sp=0; long no_ch=0; string str; fl = fopen("test.txt","r"); if(fl==NULL) return; while(1) { switch(GetToken(fl)) { case EOF: exit(1); case SPC: no_sp++; break; case WORD: str = ""; do{ str = str + token;} while(GetToken(fl)==WORD); cout << str << endl; } } cout << "Number of white spaces: " << no_sp << endl; cout << "Number of Characters: " << no_ch << endl; cout << "Number of Words: " << no_wr << endl; } // Program #2 // find keywords in file #include <stdio.h> #include <iostream> #include <string> using namespace std; #define WORD 1 #define SPC 2 #define MAX_KEY 3

string keywords[MAX_KEY] = {"This","test","and"}; bool Find(string st){ for(int i=0;i<MAX_KEY;i++) if(st==keywords[i]) return true; return false; } extern string token; int GetToken(FILE* fi){ char ch; switch(ch=fgetc(fi)) { case ' ': token = ch; return SPC; case EOF: return EOF; default: token = ch; return WORD; } } void main(void) { FILE* fl; long no_wr=0; long no_sp=0; long no_ch=0; string str; fl = fopen("test.txt","r"); if(fl==NULL) return; while(1) { switch(GetToken(fl)) { case EOF: exit(1); case SPC: no_sp++; break; case WORD: str = ""; do{ str = str + token;} while(GetToken(fl)==WORD); } } cout << "Number of white spaces: " << no_sp << endl; cout << "Number of Characters: " << no_ch << endl; cout << "Number of Words: " << no_wr << endl; }

You might also like