【问题标题】:Stopping at end of file在文件末尾停止
【发布时间】:2016-03-18 09:35:48
【问题描述】:

让我的循环在结束后停止读取文件时遇到问题。如何让它在最后一行之后停止并转到下一行代码?另外我希望增加的分数随着循环停止并将最终结果写入文件,有人可以帮忙吗?谢谢

do {
    system("cls");
    i = 0;
    printf("\tPortal Examination\n\tEnter Faculty name.:");
    fflush(stdin);
    scanf("%s", f_name);
    printf("\n\tEnter Course.:");
    fflush(stdin);
    scanf("%s", course_text);
    printf("\n\tEnter ID.:");
    fflush(stdin);
    scanf("%s", r_query);
    k = strlen(r_query);
    strcat(f_name,"101stud.txt");
    strcat(course_text,"101exam.txt");
    f_course = fopen(f_name, "rb");

    system("cls");
    printf("\tPortal Examination");
    printf("\n\n..:: Searching for '%s' \n===================================================\n",r_query);
    while (fread(&stud, sizeof(stud), 1, f_course) == 1) {
        for (j = 0; j <= k; j++) {
            s_rollno[j] = stud.stud_rollno[j];
        }
        s_rollno[j]='\0';

        if (stricmp(s_rollno,r_query) == 0) {
            system("pause");
            //*****write exams****
            f_exam = fopen(course_text, "rb");
            while (fread(&numbers, sizeof(numbers), 1, f_exam) != EOF) {
                system("cls");
                printf("\n\tAnswer all Questions:\n\t%s\n\t",numbers.question);
                fflush(stdin);
                scanf("%s", a_query);
                if (stricmp(numbers.answer, a_query) == 0)
                    s_result += 5;
                printf("%s has %d score\n\t", r_query, s_result);
                system("pause");
            }
            break;
            i++;
            if (i % 4 == 0) {
                printf("..::Press any key to continue...");
                getch();
            }
        }
    }
    if (i == 0)
        printf("\n..::No match found!");
    else
        printf("\n..:: %d match(s) found.",i);
    fclose(f_course);
    printf("\n..:: Search Again?\n\n\t[1] Yes\t\t[0] No\n\t");
    scanf("%d",&ch);
} while (ch == 1);
break;

【问题讨论】:

    标签: c loops eof file-handling


    【解决方案1】:

    您的代码存在多个问题:

    • 不要使用fflush(stdin);。行为未定义。它可能会从您的系统上的stdin 读取待处理的字符,但这不是可移植的方式。事实上,没有便携的方法可以做到这一点。可能也没必要。

    • 您没有测试scanf 的返回值。 scanf 返回从 stdin 正确读取的字段数。如果该字段未正确读取,则输出变量中的值是不确定的,因此您应该重试或中止。

    • scanf("%s", f_name); 有风险:意外的长输入会导致缓冲区溢出,您的程序可能会崩溃或有潜在的有害行为。黑客可以利用这种漏洞来渗透系统。如果 f_name 是 40 个字符的数组,则使用 scanf("%39s", f_name);

    • 您发布的代码未显示 f_namestud... 以及更多变量或结构的定义。我们无法验证您的使用是否正确。例如,如果f_name 不够大,strcat(f_name,"101stud.txt"); 执行的连接可能会导致未定义的行为。

    • 代码中间的break; 语句只中断了内部while 循环,而不是外部do / while 循环。永远不会到达后面的i++; 语句。

    • 如果输入流中存在非数字字符,最终的scanf("%d",&amp;ch); 可能会失败。在这种情况下,ch 具有不确定的内容。因此对ch == 1的测试是不可靠的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-15
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      相关资源
      最近更新 更多