在不同的迭代中使用fscanf / fgets读取文件时随机崩溃

时间:2012-12-08 14:17:08

标签: c file file-io

我正在尝试阅读具有以下格式的while questions.txt:

Question\n
Difficulty:Cost:Prize\n
Correct Answer\n
Answer 1\n
.
.
.
Answer i\n
\n

以下是一个从questions.txt读取并将其存储到临时节点以添加到链接列表的函数。

pQuestionType loadQuestions(pQuestionType pFirst)
{
    pQuestionType pTemp = malloc(sizeof(pQuestionType));
    FILE* pFile;
    string sFilename, sTemp;
    char cDump;
    int nTemp, n=0;
    gotoxy(0,0);
    system("cls");
    printf("Enter file name: ");
    gets(sFilename);
    pFile = fopen(sFilename, "rt");
    while(!feof(pFile))
    {
        printf("Iteration \n");
        fgets(sTemp, 255, pFile);
        strcpy(pTemp->sQuestion, sTemp);
        pTemp->sQuestion[strlen(sTemp)-1] = '\0';
        printf("Add question success\n");

        fscanf(pFile, "%d%c", &nTemp, &cDump);
        pTemp->nDifficulty = nTemp;
        printf("Add difficulty success\n");

        fscanf(pFile, "%d%c", &nTemp, &cDump);
        pTemp->nCost = nTemp;
        printf("Add cost success\n");

        fscanf(pFile, "%d%c", &nTemp, &cDump);
        pTemp->nWinnings = nTemp;
        printf("Add winnings success\n");

        fgets(sTemp, 255, pFile);
        strcpy(pTemp->sCorrect, sTemp);
        pTemp->sCorrect[strlen(sTemp)-1] = '\0';
        strcpy(pTemp->sAnswers[0], sTemp);
        pTemp->sAnswers[0][strlen(sTemp)-1] = '\0';
        printf("Add answer success\n");

        for(n=1; n<10; n++)
        {
            fgets(sTemp, 255, pFile);
            if(*sTemp == '\n')break;
            strcpy(pTemp->sAnswers[n], sTemp);
            pTemp->sAnswers[n][strlen(sTemp)-1] = '\0'; 
        }
        printf("Add choices success\n");

        printf("\n");   
        pFirst = addQuestion(pFirst, pTemp);        
        if(*sTemp == EOF) break;
    }
    fclose(pFile);

    return pFirst;
}

当程序试图读取我的第三个问题的难度时,我在第三次迭代时崩溃了。导致这种情况的原因以及我该如何修复我的代码?

1 个答案:

答案 0 :(得分:1)

pQuestionType pTemp = malloc(sizeof(pQuestionType));

如果pQuestionType指针类型(并且它似乎是因为pFirstpTemp都没有*字符。声明),然后它的大小将是一个指针的大小(目前可能是4或8)。

所以这个malloc几乎肯定不会给你足够的记忆。您需要改为使用sizeof(*pTemp)