简体   繁体   中英

Segmentation fault

Here is my code.

#include<stdio.h>

int main(int argc,char** argv)
{
    FILE* fp;
    fp=fopen(argv[1],"r");

    struct element{
        int value;
        char activity;
    };

    typedef struct element element;
    element a;
    printf("%d",feof(fp));
}

Now if I don't give the last printf command it does not give me a segmentation fault, but if I give it printf it gives me a seg fault. Why?

I got the answer to my prev problem, now i have another problem

i had .txt appended to my input file in my makefile. Now i have another problem. on command make it gives error.

0make: *** [a.out] Error 1 

why?

检查fopen的返回值(好吧,检查任何调用的返回值),它可能无法打开文件。

Because you do not specify the file in a command line arguments, or because the file you have specified there could not be opened for some reason. In that case, fopen returns NULL , and when you pass that NULL to feof it crashes the program. You have to check return values and error codes, especially when functions may return NULL .

The correct code may look something like this:

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[])
{
    FILE *fp;

    if (argc < 2)
    {
        fprintf (stderr, "Please specify the file name.\n");
        return EXIT_FAILURE;
    }

    fp = fopen(argv[1], "r");

    if (fp == NULL)
    {
        perror ("Cannot open input file");
        return EXIT_FAILURE;
    }

    printf ("%d\n", feof (fp));
    return EXIT_SUCCESS;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM