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.