0

I want to make 'cat -b' function.

This result is perfect when meet last step.

I got Segmant Fault error and I don't know how to fix it.

How can I do?

FILE *file_name = NULL;
file_name = fopen(av[2], "r");
char temp[1024], *str;
int cnt_file_number = 1;
while(!feof(file_name)){
    printf("%4.d ", cnt_file_number++);
    str = fgets( temp, sizeof(temp), file_name);
    if(strcmp(str, "\0") == 0 ) break;
    printf("%s", str);
}
fclose(file_name);
melpomene
  • 84,125
  • 8
  • 85
  • 148
hyumil
  • 35
  • 1
  • 4

2 Answers2

0

Aside from the fact that your program does not reflect the description of what "cat -b" would do, we do not know what av[2] is; so, no telling whether that file exists or is readable. It'd be wise to check fopen() to ensure that it opens a valid file. If it is not, then it returns NULL and feof(NULL) will fail.

Also, if you read past the end of file, str == NULL and strcmp(NULL,...) will fail.

bill.lee
  • 2,207
  • 1
  • 20
  • 26
  • av[2] means argv[2] when cat hi.txt, av[2] is hi.txt. so, this means FILE NAME – hyumil Apr 28 '19 at 08:35
  • Okay. Not knowing whether av[2] is valid, my pt still stands. I added another point of failure in my answer, however. – bill.lee Apr 28 '19 at 08:44
0

fgets returns a null pointer if it encounters an error. You are using str right away without checking it. A better way would be something like

while(fgets(temp, sizeof(temp), file_name) {
    // your printing code but using temp instead of str
}

Since fgets returns either temp or null you don't need that extra str pointer and if it is null due to EOF the loop will terminate properly.

Also, checking feof in your loop condition won't do the job because several characters are read at once and EOF might not be the next char but among the next few chars.

Edit: oh sorry. I misread. You are actually checking if str is empty but as others pointed out in the comments there is a better way to do this. Maybe this even solves the problem.

canislepus
  • 14
  • 3