简体   繁体   中英

fgets in C doesn't return a portion of an string

I'm totally new in C, and I'm trying to do a little application that searches for a string in 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've tried with GREP but it don't helps, because it returns the position:ENTIRE_STRING.

I'm open to ideas.

Try

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

Also consider initializing variables before you use them:

char ara[20]={0x0};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM