我正在C中开发一个链接列表,并从txt文件中获取数据。但是当我试图运行这个程序时,它给了我一个getc()的分段错误--这是代码,
#include<stdio.h>
#include<stdlib.h>
struct node{
char surname[100];
int number[1o0];
char name[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);
}当我试着运行这个程序时,我遇到的错误是,
程序接收信号SIGSEGV,分割故障。从/lib64 64/libc.so.6到getc ()中的0x0000003c0ee68dfa
请在这方面指导我。提前谢谢。
发布于 2010-12-05 22:40:04
最可能的原因是它无法打开文件。
在调用ifp之后立即检查fopen("tele.txt","r")是否为NULL。如果为NULL,errno将向您提供更详细的错误信息(许多可能的原因,其中一些原因是:文件不存在,您没有访问它的权限,或者您位于错误的目录中)。
ch本身也有几个问题,可能与崩溃无关:
ch没有初始化,所以可以也可能不会输入while (ch != EOF),这要归功于@Dirk指出这个out;while(ch !='\n')有点不可靠,因为如果您选择了外部EOF,那么您将进入一个无限循环。https://stackoverflow.com/questions/4361709
复制相似问题