Hi all. In my searchstring() function, why does the last while() loop execute 11 times? It doesn't matter if I set TEXTLENGTH to 100,000 or 9 million, it always executes 11 times. The text file is less than 10K characters, so shouldn't the fgets return value be NULL because it has passed the end of file indicator? I want to search for the first occurrence of a string in the text file.
Thanks in advance.
Code:// searchfilesforsting.c: search for strings in text file and replace them with another string // 3 functions: openfile(), searchstring(), replacestring() #include <stdio.h> #include <string.h> #include <stdlib.h> #define FILENAMELENGTH 40 #define STRINGLENGTH 1024 #define TEXTLENGTH 10000 char string[STRINGLENGTH], filename[FILENAMELENGTH], *text; FILE *file; void openfile(void); void searchstring(void); // search for string in file void replacestring(void); int main(void) { openfile(); searchstring(); return 0; } void openfile(void) { do { printf("Enter file to open: "); fgets(filename, FILENAMELENGTH, stdin); filename[strlen(filename) - 1] = '\0'; // known filenames. no overflow problems } while((file = fopen(filename, "r"))== NULL); } void searchstring(void) { if((text = calloc(TEXTLENGTH, sizeof(char))) == NULL) // allocate memory for reading text { puts("Memory allocation error"); exit(EXIT_FAILURE); } do { printf("Enter string to search for: "); } while(fgets(string, STRINGLENGTH, stdin) == NULL); string[strlen(string) - 1] = '\0'; // known strings. no overflow problems while((fgets(text, TEXTLENGTH, file)) != NULL) { if(strstr(text, string) != NULL) { puts("A match has been found"); } else { puts("A match has NOT been found"); } } free(text); fclose(file); }



2Likes
LinkBack URL
About LinkBacks



