简体   繁体   English

C中的fgets不返回字符串的一部分

[英]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. 我是C的新手,我正在尝试做一个在文件中搜索字符串的小应用程序。 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). 我的问题是我需要打开一个大文件(超过1GB),里面只有一行,fgets将整个文件返回给我(我正在用10KB文件进行测试)。

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. 我尝试过GREP,但它没有帮助,因为它返回的位置: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. 您只为输入缓冲区分配了20个字节,但告诉fgets读取20个字节。

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. 记住,如果你想要20个字符加上标记字符串结尾的尾部'\\ 0',你必须分配21个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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