Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Search

Status
Not open for further replies.

jeff32889

Programmer
Feb 9, 2005
5
US
How do you search a file for a word?
 
Your questions are way too vague to be answered with any degree of success.


--
 
assuming you are searching a text file for a specific character string

Code:
#include <stdio.h>
#include <stdlib.h>

int main () {
  FILE * pFile;
  long lSize;
  char * buffer;

  char szSearchString[] = "sample"

  pFile = fopen ( "myfile.txt" , "rb" );
  if (pFile==NULL) exit (1);

  // obtain file size.
  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

  // allocate memory to contain the whole file.
  buffer = (char*) malloc (lSize);
  if (buffer == NULL) exit (2);

  // copy the file into the buffer.
  fread (buffer,1,lSize,pFile);

  /*** the whole file is loaded in the buffer. ***/
  if (strstr (str,szSearchString) != NULL)
  {
    //do some processing
  }
  // terminate
  fclose (pFile);
  free (buffer);
  return 0;
}

if you want to search big files, you might need to read it in in blocks and check each block. If you do, you will need to work out a way of dealing with a word that crosses the boundary between two blocks

I havent actually tried compiling this code. I got it from


"If it could have gone wrong earlier and it didn't, it ultimately would have been beneficial for it to have." : Murphy's Ultimate Corollary
 
> that question isn't vague at all
Where's YOUR effort towards a solution then?
This isn't some place where you can just dump a question and expect people to feed you an answer.


--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top