Segmentation fault in fgets() - C language

谁都会走 提交于 2019-12-21 05:56:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!