Hi, i would like to know if there is a function in c that allows me to search for a specific character in a file, and how to use it.
Thanks in advance

When you open a file, you receive a file position pointer (part of the FILE *, but not the whole thing).

The file pointer has the address of the first byte of the file. If you increment that address, you can access any byte in the file, in sequential mode.

There are a number of different ways to do that - pick the version of fgetc(char) that you want to use, or use your own char pointer, or ...

Walt is right, that usually, you want to load the file into a buffer, and then scan through it, but you can do it directly as well. Even more options exist, since you can do it using high level stream file handling (easier), or low level non-stream file handling (more complex and definitely not recommended).

The only time that I wouldn't use a buffer, would be if the file was so large that I couldn't fit it all in the char buffer you create. Naturally, a really large char buffer, will need to be allocated dynamically with malloc/calloc, because it will exceed the size of the static memory that C has allocated for such things. (the stack).

For starters, why don't you statically create a char buffer[BUFSIZ] and try using strch() to find the char you want. It will return a pointer to the first instance of the char, or NULL if no such char (which is case sensitive), is found. So you need to check the address that strch() returns.

if( strch() ) { 
  //the char was found //the return was not NULL
  //the char was not found //NULL was returned

Now, tell me what goes into the call to strch(). ;)

P.S. You will need to include string.h to use strch().

Edited 5 Years Ago by Adak: n/a

This article has been dead for over six months. Start a new discussion instead.