Thread: Looking for a string inside a file

  1. #1
    C Beginner
    Join Date
    Dec 2011
    Location
    Portugal
    Posts
    187

    Looking for a string inside a file

    Hey guys,
    I've wrote the following piece of code :
    Code:
    void procurastring2 (Ficheiro aux, char *string)
    {
    int flag=0;
    char *buf;
    int x;
    int i;
    int linha = 0;
    printf("%s",aux->ficheiro);
    x = open(aux->ficheiro,O_RDONLY);
    read(x,buf,BUF_TAM_MAX);
    linha=1;
    if(buf[i]=='\n')
    {
    linha++;
    }
    else {
    for(i=0; (buf[i]!= '\0') || (!flag) ;i++)
    {
    if(pref(string,buf+i)) {printf("%s foi encontrada na linha %d do ficheiro %s",string,linha,aux->ficheiro); flag=1;}
    else {printf("A string não foi encontrada no ficheiro %s",aux->ficheiro); flag=1;}
    }
    close(x);
    return 1;
    }
    }
    I'm looking for the string 'portugal' inside my aux->ficheiro which is 'ola'.
    Thing is, I wrote in my 'ola' file 'ola portugal'.
    When doing this, seems like something writes on top and 'ola' has nothing in the end of the execution

    Any help ?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    I think we're all getting bored of reading your unindented code.
    SourceForge.net: Indentation - cpwiki
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    How about reading into a pointer pointing to who knows where?

    Code:
    char *buf;
    ...
    read(x,buf,BUF_TAM_MAX);
    How about not checking to see if the open succeeded here?
    Code:
    x = open(aux->ficheiro,O_RDONLY);
    read(x,buf,BUF_TAM_MAX);
    And what do you suppose the value of i is here?

    Code:
    if(buf[i]=='\n')

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. replacing a string inside a file
    By zahid990170 in forum C Programming
    Replies: 5
    Last Post: 04-11-2012, 11:00 AM
  2. Trying to obtain int from inside a string.
    By TonyG in forum C Programming
    Replies: 9
    Last Post: 05-18-2011, 07:35 AM
  3. string inside of a structure?
    By dyelax in forum C++ Programming
    Replies: 8
    Last Post: 06-17-2010, 07:09 PM
  4. Replies: 12
    Last Post: 10-14-2003, 10:17 AM
  5. Replies: 4
    Last Post: 01-22-2002, 11:13 PM