Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
avlcat opened this issue Jun 10, 2024 · 0 comments
Open

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

avlcat opened this issue Jun 10, 2024 · 0 comments

Comments

@avlcat
Copy link

avlcat commented Jun 10, 2024

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:

  • it checks for the existence of the file, if it cannot be opened for some reason will also display the reason
  • it closes the file handler
  • it returns something at the end of the program, return 0 for success and anything else (usually 1) for error (this is also useful for debug purposes, after the program exited I can find out the return value from the shell running "echo $?".
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant