gpt4 book ai didi

c - 从文件中读取,输出只显示一行

转载 作者:太空宇宙 更新时间:2023-11-04 04:37:58 24 4
gpt4 key购买 nike

我想从文件 newdata.dat 中读取一些数据,其中有 5 个数据。我的程序应该输出全部 5 个数据:

323 贝利,比尔 922.00

163 比恩,吉姆 2023.00

183 丹尼尔斯, jack 3932.00

123 美国能源部,约翰 1022.00

121 史密斯,山姆 512.00

但我的输出只显示 1 行数据。请指教?谢谢。

艾莉

示例代码:

#include <stdio.h>
#include <string.h>

main () {

/* Define Structure */
/* ---------------- */

struct emp
{
int id_num; /* employee number */
float salary; /* employee salary */
char first_name[20]; /* employee first name */
char last_name[30]; /* employee last name */
};


/* Declare variables */
/* ----------------- */
struct emp info[100]; /* a maximum 100 people can be stored */
FILE *in_file_ptr:
int i;


/* Open the input file. If error, display message and exit the program */
/* --------------------------------------------------------------- */
in_file_ptr = fopen("newdata.dat", "rb");
if (!in_file_ptr)
{
printf ("\nCannot open file newdata.dat for reading.\n");
return 1;
}


for ( i = 0; i < 100; i++ )
{
/* Read data from input file and load array struct for processing */
fread (&info[i], sizeof(info[i]), 100, in_file_ptr);

/* concatenate first name anda last name */
strcat (info[i].last_name, info[i].first_name);

printf ("%10i %20s %-10.2f\n", info[i].id_num,
info[i].last_name, info[i].salary);


if(feof(in_file_ptr))break;

} /* end for loop */

fclose (in_file_ptr);

} /* end of main */

最佳答案

您的代码进行了一些重复计算:一方面,它执行了 100 次读取;另一方面,它执行了 100 次读取。另一方面,它指示 fread 读取 100 条记录。由于第一个 fread 消耗了文件中的所有记录,因此循环立即在 feof 上退出。

您应该像这样一次阅读全部内容:

size_t count = fread (&info[i], sizeof(info[i]), 100, in_file_ptr);
for (size_t i = 0 ; i != count ; i++) {
... // no reading or checking feof here
}

或者改变fread来读取单个记录,像这样:

if (fread (&info[i], sizeof(info[i]), 1, in_file_ptr) != 1) break;
// ^

请注意,如果您使用 feof,您应该在阅读后和使用您已阅读的任何数据之前检查它。您还应该检查 fread 的返回值。

关于c - 从文件中读取,输出只显示一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29201703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com