c++ - C 读取文件时出错

标签 c++ c file-io

我正在尝试写入和读取文件。写入工作正常,但当它尝试读取时,程序崩溃了。告诉我错误是什么?

该程序的目标是将学生的记录存储在文件中。 计算百分比,并找出学生百分比最高和最低的学生。

#include <stdio.h>
#include <conio.h>
#include <string.h>
struct result
{
char name[15];
int batchNo;
int rgtNo;
int marks;
float perc;
};
int main()
{
    char answer, i = 1;
FILE *ptr, *abc;
result s, st;
int j;
ptr = fopen("rec.txt","a");
abc = fopen("rec.txt","r");
if(!ptr)
    printf("Error opening file");
else if(!abc)
    printf("Error opening read file");
else {
do
{
    int sum = 0;
    printf("\nEnter name of student %d: ", i);
    scanf("%s", s.name);
    printf("\nEnter Batch #: ");
    scanf("%d", &s.batchNo);
    printf("\nEnter Registeration no: ");
    fflush(stdin);
    scanf("%d", &s.rgtNo);
    printf("\nEnter marks of Five subjects: ");
    scanf("%d",&s.marks);
    /*for(j = 0; j < 5; j++)
    {
        scanf("%d",&s.marks[j]);
        sum += s.marks[j];
    }*/
    s.perc = sum / 5.0;
    printf("Percentage of student %d: %f", i+1,  s.perc);
    fprintf(ptr, "%s %d %d %d %f", s.name, s.batchNo, s.rgtNo, s.marks, s.perc);

    printf("\n\n\n");
    printf("Do you want to add another record? (y/n) ");
    answer = getche();
    i++;
} while(answer == 'y');

printf("outside loop\n");
fclose(ptr);
fflush(stdin);
rewind(abc);
do
{
    fscanf(abc, "%s%d%d%d%f", s.name, s.batchNo, s.rgtNo, s.marks, s.perc);
    printf("in loop");
} while( !feof(abc));
fclose(abc);
}


}

最佳答案

缺陷如此之多,时间如此之少。

C 不是 C++
它们是两种不同的语言。删除 C++ 标签。
但由于您将其标记为 C++,因此您应该使用 fstreamiostream 库以及 std::string 类型。

每个物理文件一个指针
对于同一文件的每种不同模式,您都有一个 FILE *。在许多情况下,这会让操作系统感到困惑,有些操作系统不允许这么做。

相反,请使用一个 FILE * 并将文件以 rw+ 打开,以进行读取写入>追加

参见fseek函数。

scanf 缓冲区溢出
您为该名称保留了 15 个字母。如果用户输入的名称超过 15 个字母,会发生什么情况?缓冲区溢出。您可以覆盖 name 成员后面的其他变量。
您可以通过使用 C 语言的 fscanf 或使用 C++ 语言的 std::cinstd::string 来解决此问题。

刷新输入
flush 函数仅适用于输出缓冲区。不要与输入流一起使用。
在 C 语言中,您必须读取字符,直到缓冲区为空或找到终止符(例如“n”)。 在 C++ 中,这是通过 cin.ignore(1000000, '\n') 完成的。

检查输入函数是否有错误
您不能信任用户。您必须检查scanf返回值是否有错误。如果您要求输入号码并且用户输入号码,则 scanf 将失败。该值未定义。

关于c++ - C 读取文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23791561/

相关文章:

C Playsound函数返回-1073741819退出代码并且不播放mp3文件

具有未定义结果的 C 代码,编译器生成无效代码(使用 -O3)

c++ - 使用 fstream 读取文件

c - 这段代码有什么问题?

c# - 减少文件操作的内存占用

java - 读取 number.txt 文件并查找平均值

c++ - 为什么此代码在 valgrind (helgrind) 下失败?

c++ - ATL 宏仅适用于开发计算机

PHP 扩展函数 array_init 抛出 'return_value is undeclared'

c++ - 带有 SWIG 的 Python C++ 扩展 - 通过导入模块调用函数