You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 $?".
The text was updated successfully, but these errors were encountered:
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:
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:
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:
The improvements are:
The text was updated successfully, but these errors were encountered: