1

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?

1
  • fopen() fails and so returns 0? Commented Sep 26, 2011 at 18:08

2 Answers 2

3

Check the return value of fopen (well, check the return value of any call), it probably failed to open the file.

Sign up to request clarification or add additional context in comments.

1 Comment

yeah, i had .txt appended in my makefile. Now i have another problem. on command make it gives error. 0make: *** [a.out] Error 1 why?
1

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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.