• 0

[c] Searching a file?


Question

11 answers to this question

Recommended Posts

  • 0

Read it in as a string, and use char *strstr(const char *s1, const char *s2) to locate s2 in s1. Although I guess it depends on what you what to do with the result, this returns s1 + x, where x is the offset of the location of substring s2.

Link to comment
Share on other sites

  • 0
thanks.. but I am not sure how to traverse a file with spaces, tabs and new lines to find the specific word...

strtok allows u to tokenize

but strstr is useful too to find a substring; it's case-sensitive btw.

Link to comment
Share on other sites

  • 0
thanks.. but what if i wanted to find a word to replace with a different word in a file?  would i still use strstr?

That's getting a little tricker, you'd have to make a temp string that starts with the string up until that place and then concatenate the replacement word onto it and then concatenate what's after the word you're replacing. I'd use strstr to find the place in the string where that word is.

Link to comment
Share on other sites

  • 0
also i could use the strstr to find the searched word more than once right??

Sure, you can run strstr on the newly created string when you replace the first occurence of it.

Link to comment
Share on other sites

  • 0

i am having some problem reading a flie.. here is my code so far:

#include <stdio.h>

int main() {
  char c[10];  
  FILE *file;  

  file = fopen("c:\\file.txt", "r"); 


  if(file==NULL) {
    printf("Error: can't open file.\n");

    return 1;
  }
  else {
    printf("File opened successfully. Contents:\n\n");
    
    while(fgets(c, 10, file)!=NULL) { 

      printf("String: %s", c);        

    }

    printf("\n\nNow closing file...\n");
    fclose(file);
    return 0;
  }
}

for some reason it keeps on saying "Error: can't open file." Even though I have a c:\file.txt and some text in it.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.