# Thread: got a seg fault

1. ## got a seg fault

i have a seg fault please help. It happens when i go to open a file. if the file has data i get a seg fault. if the file is empty its all ok and i get the proper message.
Code:
void open_batch()
{
char f[100];
char c;
int a = 0, b = 0;
int eof = 0;
int d, e, g, h, i, j, k;
printf("Please enter the file you wish to run: ");
scanf("%s", f);
if(file == NULL)
{
printf("File is empty!\n\n");
exit(1);
}
while(eof == 0)
{
c = fgetc(file);
if((c == 70) || (c == 102) || (c == 85) || (c == 117))
{
for(d = 0; d <= 3; d++)
{
u_type[d] = c;
c = fgetc(file);
printf("%c", u_type[d]);
}
...
...

2. You don't actually call fopen() anywhere...

3. Code:
printf("Please enter the file you wish to run: ");
scanf("%s", f);
if(file == NULL)
{
You can't just expect to input a string and be able to call it a file.

you need to open it...
Code:
FILE *fp;
char c;
fp=fopen("file.txt","r");
c = getc(fp);
Oh and make sure you check the return value of fopen() and also dont use scanf to input strings, use fgets()

4. If you want to take the file name as ainput from user....this will do

Code:
#include <stdio.h>
#include <conio.h>

void main(){

FILE *fp;
char name[30];
clrscr();
scanf("%s",&name);
if ((fp=fopen(name,"rt"))==NULL){
printf("No such file");
}
else
printf("File exists");
.......................
You will input the file name by full path ie. c:\text.txt

Do notice that while writing directly in a program we use double slash(\\) but while typing the input we use one slas(\)

Code:
   while(!feof(fp))
{
ch=fgetc(fp);
. . . . }
Dont forget to close the file everytime you work with file in program

Code:
fclose(fp);

5. > void main(){
> while(!feof(fp))
Why both of these are bad are in the FAQ - read them