简体   繁体   中英

read line by line of file and store in C

I am having trouble how to use getline in C. I want to read each line and store it into an array. So I am able to read each line, print each line out and print the number of characters in each line.

I am having trouble when I run my program It does not print out the number of lines and the file and it does not stop it just stays put after all lines of a file are printed.

I also do not know how to store the line into an array. Any help/hints would be appreciated!!!

int main(int argc, char *argv[])
{
  int line_count=0;
  int charac_count;
  int count=0;

  char line[81];    
  char *lineptr;
  lineptr=(char*)malloc(sizeof(char)*81);
  int lineptr_size=81;  
  if(!lineptr)
  {
     printf("malloc memory error\n");
     exit(EXIT_FAILURE);
  }     

  if(argc !=3)
  {
    printf("Number of parameters is incorrect.\n");
    exit(EXIT_FAILURE);
  }

  FILE *r; 

  r=fopen(argv[1], "r");
  if(r==NULL)
  {
      printf("File cant be open\n");
      exit(EXIT_FAILURE);
  }


  charac_count=getline(&lineptr, &lineptr_size, r);
  while(charac_counter!=EOF)
  {


        if(charac_count!=-1)
        {
            puts(lineptr);
            printf("%i\n", charac_count);
        }
        line_count++;
        break;


  }


  printf("%i\n", count);
  fclose(r);
  free(lineptr);
  return 0;

}

As @BLUEPIXY mentioned, you have an infinite loop. Try something like this instead:

while((charac_count=getline(&lineptr, &lineptr_size, r))!=EOF)
  {
        if(charac_count!=-1)
        {
            puts(lineptr);
            printf("%i\n", charac_count);
        }
        line_count++;
        break;
  }

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