0

I have to enter a number k and a filename as command line arguments and print the first k lines of the file. Then, for every newline character entered, the next line must be printed. My program should terminate when the end of file is reached or the input read is EOF. Here's what I did:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char*argv[]){
  int k = atoi(argv[1]);
  FILE*fp = fopen(argv[2],"r");
  char str[500];
  int i=0;
  while(fgets(str,500,fp)!=NULL&&i<k){
    printf("%s",str);
    i++;
  }
  char* array;
  size_t size=50;
 array=(char*)malloc(size*sizeof(char));
  while(feof(fp)!=0 && array[0]!='\n'){
    getline(&array,&size, stdin);
    fgets(str,500,fp);
    printf("%s",str);
  }
  fclose(fp);
  return 0;
}

My issue is the following- my code works till the first k lines are printed. Then the compiler says 'illegal instruction(core dumped)', and I can't figure out why. Please help.

  • 1
    Quite a few errors. Not sure which one exactly triggers your specific issue but they all should be fixed. 1. [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). 2. `array[0]` is accessing an uninitialized value for at least the first iteration. 3. No error checking of many of the calls, `getline`, and `fgets` in particular. – kaylum Mar 12 '22 at 07:20
  • 1
    And now would be a good time to learn to debug code effectively. Run your program in a debugger. At a minimum it will tell you the exact line of code that triggers the core dump. – kaylum Mar 12 '22 at 07:21
  • 1
    You never check how many arguments you got from command line. This `fopen(argv[2]` is illegal if you did not get 2 arguments. – Gerhardh Mar 12 '22 at 10:32
  • 1
    You have a buffer for one line when you print the first `k` lines. Why do you use another one for following lines (where you even don't check result of `malloc`)? Why do you care if the read line only holds a `'\n'`? The next line is the next line, whatever it contains. – Gerhardh Mar 12 '22 at 10:35
  • 1
    Also for the condition of the second loop. If you know how to check if there was another line for the first `k` files (`fgets()!=NULL)`), why do you think you need to do something totally different for the following lines (`feof()`)? If you do the same things, do them the same way. – Gerhardh Mar 12 '22 at 10:37

0 Answers0