Segmentation fault in getc()
I am developing a linked list in C. And I am getting the data from a txt file. But when I try to run the program, it gives me a segmentation fault of getc() Here's the code,
#include<stdio.h>
#include<stdlib.h>
struct node{
char surname[100];
int number[1o0];
char n开发者_运维问答ame[100];
struct node *next;
};
typedef struct node Node;
int main()
{
FILE *ifp;
Node first ,*current;
//current =&first;
int i=0,j=0;
int ch;
char num[100],name[100];
ifp = fopen("tele.txt","r");
while (ch != EOF)
{
while(i<4)
{
ch = getc(ifp);
num[i++] = ch;
}
num[i] = '\0';
i=0;
while(ch !='\n')
{
ch = getc(ifp);
if(ch != '\t')
name[j++]=ch;
}
name[j] = '\0';
//ch = '\0';
printf("Number %s\nName %s\n ",num,name);
j=0;
}
fclose(ifp);
}
and the error I am getting while I try to run the program is,
Program received signal SIGSEGV, Segmentation fault. 0x0000003c0ee68dfa in getc () from /lib64/libc.so.6
Kindly guide me in this. thanks in advance.
The most likely reason is that it can't open the file.
Check that ifp
is not NULL immediately after you've called fopen("tele.txt","r")
. If it is NULL, errno
will give you more detail of what went wrong (lots of possible reasons, some of which are: the file doesn't exist, you don't have permissions to access it, or you're in the wrong directory.)
There are also several issues around ch
itself, probably unrelated to the crash:
ch
is not initialized, so thewhile (ch != EOF)
may or may not be entered [thanks to @Dirk for pointing this out];while(ch !='\n')
is a bit dodgy in that if you encouterEOF
, you end up in an infinite loop.
精彩评论