Click here to Skip to main content
15,890,973 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm using a buffer to temporarily store a certain bytes of data(characters) from a file. I just want to find out whether a particular word is present in the file. Let's say, I'm searching for a word 'Apple' and I'm storing a string from the file into the buffer which has the first half "App" at the end of the buffer and "le" in the next buffer. I just want to make sure that these words are not missed out What can I do to reread a particular length at the end of the buffer. How can I modify the following code?

What I have tried:

while(feof(fptr)==0){
		char * result;
		char line[100];
		result = fgets( line, sizeof( line ), fptr );
	if ( result == NULL ){
        break;
   	}
   	line[strcspn( line, "\n" ) ] = '\0';
   	token = strtok(line," \t,:;\'\"\?!-_|\\><~@#$%^&*()+{}[].=1234567890");
   	while( token != NULL ) {
      	printf( " %s\n", token );
        if(strcasecmp(token,word)==0){
        	count++; //counts the number of occurrence of the word 
		}
        token = strtok(NULL," \t,:;\'\"\?!-_|\\><~@#$%^&*()+{}[].=1234567890");
   }
	}
Posted
Updated 8-Jul-20 23:13pm

Use C library function - fseek() - Tutorialspoint[^]

But how many times have we told you now that you are doing this the wrong way?
 
Share this answer
 
Comments
Sharon Shelton 9-Jul-20 4:56am    
I'm not asking for a code that gives me output. I'm asking for something that is efficient. fseek() consumes a lot of time of the program. And just because I'm asking doubts in the same single program doesn't mean that I'm asking the same doubt -_- No offense
OriginalGriff 9-Jul-20 5:24am    
And you've been told before: your approach is slow: read the whole file once and process it into memory based word counts. Then search those words.

Yes, seeking can be slow - that's why you don't use it unless you have to!
One way would be to overlap the existing buffer with the next buffer.

If you know that the phrase that you are looking for is of length N, when reaching the end of the buffer you copy the last N-1 characters from the end of the buffer to the beginning. You then fill the rest of the buffer from the file, and resume searching at the beginning of the buffer.
 
Share this answer
 
You could get the size of the file (from fseek/ftell) and allocate a buffer large enough for the entire file. Then read the it into memory and search that way. Alternately, if it is a proper text file, read it line by line, making sure that the input buffer is large enough for the longest line. The key to success is to try a few things to see which works best.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900