csev / cc4e

C Programming for Everybody
https://www.cc4e.com/
Other
292 stars 92 forks source link

this is not an issue but a little improvement to an example #98

Open avlcat opened 3 months ago

avlcat commented 3 months ago

Hi,

I've tried example cc_02_06.c from the long video (at position 1:34:11 in the video). This is the example:

#include <stdio.h>

int main() {
    char line[1000];
    FILE *hand;
    hand = fopen("romeo.txt", "r");
    while ( fgets(line, 1000, hand) != NULL ) {
    printf("%s", line);
    }
}

When I first compiled and run the program it returned "Segmentation fault (core dumped)". I am not a programmer but rather a sysadmin but I knew to compile the code with debug info and then to run gdb ./a.out and then inside gdb to run the program which said:

(gdb) r
Starting program: /home/ovi/learn/c/lessons/a.out

Program received signal SIGSEGV, Segmentation fault.
Address not mapped to object.
0x00000008003595e3 in fgets () from /lib/libc.so.7

Then I've realized I forgot to create the text file from where the program should read. I knew to use gdb but other beginners might not knew that, type the code and their program will crash (at least on linux or freebsd, where I tested the program).

So, I propose a little bit of an improvement to the program:

#include <stdio.h>

int main() {
    char line[1000];
    FILE *hand;

    hand = fopen("romeo2.txt", "r");
    if (hand == NULL) {
        perror("Error opening file");
        return 1;
    }

    while (fgets(line, sizeof(line), hand) != NULL) {
        printf("%s", line);
    }

    fclose(hand);
    return 0;
}

The improvements are: