can anyone tell me why this programme isnt working? its meant to count how many words that you enter appear in the second sentence. run it and see wot i mean. Thanks,
PROGRAMME:
#include <stdio.h>
int main() {
FILE *file1;
FILE *file2;
FILE *file3;
char sentence1[50];
char sentence2[50];
char sentence3[50];
int i, j, k, c;
int word = 0;
file1 = fopen("sentence1.txt", "w+"); /* we create a file for reading and writing */
file2 = fopen("sentence2.txt", "w+"); /* we create a file for reading and writing */
file3 = fopen("sentence3.txt", "w+"); /* we create a file for reading and writing */
printf("****************************************** ***********\n");
printf("*A PROGRAM TO STORE TEXT IN 3 FILES THEN RECALL THE *\n");
printf("*SECOND AND COUNT THE NUMBER OF TIMES A WROD APPEARS*\n");
printf("****************************************** ***********\n\n");
if(file1==NULL) {
printf("Error: can't create file.\n");
return 1;
}
else {
printf("Enter you first sentence (less than 50 characters):\n");
gets(sentence1);
printf("File created successfully.\n");
for(i=0 ; sentence1[i] ; i++) {
fputc(sentence1[i], file1);
}
rewind(file1); /* reset the file pointer's position */
printf("Contents of the file: ");
while(!feof(file1)) {
printf("%c", fgetc(file1));
}
printf("\n");
fclose(file1);
}
if(file2==NULL) {
printf("Error: can't create file.\n");
return 1;
}
else {
printf("Enter your second sentence (less than 50 characters):\n");
gets(sentence2);
printf("File created successfully.\n");
for(j=0 ; sentence2[j] ; j++) {
fputc(sentence2[j], file2);
}
rewind(file2); /* reset the file pointer's position */
printf("Contents of the file: ");
while(!feof(file2)) {
printf("%c", fgetc(file2));
}
printf("\n");
fclose(file2);
}
if(file3==NULL) {
printf("Error: can't create file.\n");
return 1;
}
else {
printf("Enter your third sentence (less than 50 characters):\n");
gets(sentence3);
printf("File created successfully.\n");
for(k=0 ; sentence3[k] ; k++) {
fputc(sentence3[k], file3);
}
rewind(file3); /* reset the file pointer's position */
printf("Contents of the file: ");
while(!feof(file3)) {
printf("%c", fgetc(file3));
}
printf("\n");
fclose(file3);
}
file2 = fopen("sentence2.txt", "r"); /* open a text file for reading */
if(file2==NULL) {
printf("Error: can't open file.\n");
/* fclose(file); DON'T PASS A NULL POINTER TO fclose !! */
return 1;
}
else {
printf("File opened successfully. Contents:\n\n");
printf("The text you entered from line 2 is:\n");
while(1) { /* keep looping... */
c = fgetc(file2);
if(c!=EOF) {
printf("%c", c); /* print the file one character at a time */
}
else {
break; /* ...break when EOF is reached */
}
}
printf("\n\nOk, please enter a word to look for in this sentence.\n");
scanf("%d", &word);
if (c == word)
word++;
}
printf("This text appears word %d times.\n", word);
fclose(file2);
return 0;
}