fgetc,getc会导致程序在从文本文件中读取时崩溃

时间:2012-09-12 09:49:30

标签: c file input fgetc getc

什么错了?我很确定我的语法是正确的,因为它没有警告。另外,它不会超过getc(document);我尝试了fgetc(document);相同的结果。我没有到这里来的是什么? (我使用printf("$");查看它崩溃的位置)

char temp[51];
int cntr = 0,listcntr = 0,buffer;
FILE *document;
contact list[MAXCONTACTS];
document = fopen("addressbook.txt","r");
do
{
    for(cntr = 0;cntr < 51; cntr++)
        temp[cntr] = '\0';
    cntr = 0;
    do
    {

        buffer = getc(document);
         printf("$");
        if(buffer != '\t')
            temp[cntr] = buffer;
        ++cntr; 
    }while(buffer != '\t'&& buffer != EOF);
list[listcntr].name = temp;

1 个答案:

答案 0 :(得分:1)

好的我稍微修改了你的代码并添加了几个检查,也许就足够了。

char temp[51];
int listcntr = 0,buffer;
contact list[MAXCONTACTS];
FILE *document = fopen("addressbook.txt","r");

if (NULL == document){
    //exit here
}

for(int i = 0;i < 51; i++){
    temp[i] = '\0';
}

int cntr = 0;
for (int cntr=0; cntr < 51 && !feof(document); cntr++){
    buffer = getc(document);
    if (buffer == '\t'){
        break;
    }
    temp[cntr] = buffer;
}

if(listcntr < MAXCONTACTS){
    // you should probably copy temp here
    list[listcntr].name = temp;
}