问题
I am getting a segmentation fault exactly at this line:
while (fgets(line, MAX_LEN + 1, stream) != NULL) {
....
}
where MAX_LEN is 500, line is reading the current line, and stream is open through fopen(filename, "r");
I am reading lines from a file with a specific format and I get a segmentation fault (Core dumps) exactly at this line according to the debugger.
I made my code so that it ignores lines that do not match the scanf format.
Here is what I am implementing. Something close to it at least:
int main(int argc, int **argv) {
....
....
if (argc == 1) {
printf("enter file name: ");
scanf("%s", filename);
if (!(stream = fopen(filename, "r"))) {
perror("Error message goes here.");
exit(EXIT_FAILURE);
}
} else if (argc == 2) {
stream = fopen(argv[1], "r");
if (sream == NULL) {
fprintf(stderr, "error message", argv[1], errno));
return EX_OSERR;
}
}
while (fgets(line, MAX_LEN + 1, stream) != NULL) {
if (sscanf(line, "%49[^@ ]@%49s -> %49[^@ ]@%49s", sender_username, sender_hostname, receiver_username, receiver_hostname) != 4) {
continue;
} else {
do work;
}
来源:https://stackoverflow.com/questions/19390936/segmentation-fault-in-fgets-c-language