views:

57

answers:

2

Hi!

I'm totally new in C, and I'm trying to do a little application that searches a string into a file, my problem is that I need to open a big file (more than 1GB) with just one line inside and fgets return me the entire file (I'm doing test with a 10KB file).

actually this is my code:

#include <stdio.h>
#include <string.h>


int main(int argc, char *argv[]) {
 char *search = argv[argc-1];

 int retro = strlen(search);
 int pun  = 0;
 int sortida;
 int limit = 10;

 char ara[20];

 FILE *fp; 
 if ((fp = fopen ("SEARCHFILE", "r")) == NULL){
  sortida = -1;
  exit (1);
 }

 while(!feof(fp)){
  if (fgets(ara, 20, fp) == NULL){
   break;
  }
  //this must be a 20 bytes line, but it gets the entyre 10Kb file
  printf("%s",ara);
 }

    sortida = 1;

 if(fclose(fp) != 0){
  sortida = -2;
  exit (1);
 }

 return 0;
}

What can I do to find an string into a file?

I'v tried with GREP but it don't helps, because it returns the position:ENTIRE_STRING.

I'm open to ideas.

Thanks in advance!

+3  A: 

Try

printf("%s\n",ara);     

Also consider initializing variables before you use them:

char ara[20]={0x0};
jim mcnamara
I have no idea how `printf` would solve his problem, and there's no need to initialize `ara` here, as `fgets` is going to overwrite it
Michael Mrozek
%s\n makes the string print as a new line each time \n == newline character
jim mcnamara
Oh, I see, you were saying to add the `\n` to the end of his existing printf. Got it
Michael Mrozek
ohf!! is for the newline!!! :D thanks mates!
Marc
I'm feel a little stupid :P
Marc
@michael - Best Practice == initialize all strings to nuls. Always.
jim mcnamara
hopely OP understood that the reason why it "looked" as if it has read "the whole file" is that printing even one read byte after another results in the original file as output, not surprising; and that searching string this way is not so easy since the string could be "split" into two separated 20byte block, and the separation avoid recognization of the string
ShinTakezou
@jim Nonsense; it's good practice if you're learning and/or you don't trust yourself not to screw it up, but there's no reason to initialize a variable that's going to be overwritten immediately after the declaration
Michael Mrozek
There's no need to do initialization.
Nyan
Nyan - Michael. Consider reading 'Code complete', 2nd Ed, Chap 10. p 241. If I understand you, you mean "don't init variables" if you think/hope/suspect some operation nearby is going to clean it out for you. Correct? Obviously I disagree.
jim mcnamara
+1  A: 

You only allocated 20 bytes for the input buffer, but told the fgets to read 20 bytes.

Make this change:

  if (fgets(ara, sizeof(ara)-1, fp) == NULL){ 

remember, if you want 20 characters PLUS the trailing '\0' that marks the end of the string you have to allocate 21 bytes.

Grimper