[英]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. 现在,如果我不给出最后一个
printf
命令,它不会给我一个分段错误,但如果我给它printf
它会给我一个seg错误。 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. 我将.txt附加到我的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. 在这种情况下,
fopen
返回NULL
,当你将NULL
传递给feof
它会崩溃程序。 You have to check return values and error codes, especially when functions may return NULL
. 您必须检查返回值和错误代码,尤其是当函数可能返回
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.