我是 C 新手,所以我不确定我的错误在哪里。但是,我确实知道问题的很大一部分在于我如何将双打存储在 d_buffer (double) 数组中,或者我打印它的方式。
具体来说,我的输出一直在打印非常大的数字(小数点前大约有 10-12 位数字,小数点后有一行零。此外,这是对旧程序的改编,允许双输入,所以我只添加了两个 if 语句(在“read”for 循环和“printf”for 循环中)和 d_buffer 声明。
我将不胜感激任何输入,因为我在这个错误上花了几个小时。
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
struct DataDescription
{
char fieldname[30];
char fieldtype;
int fieldsize;
};
/* -----------------------------------------------
eof(fd): returns 1 if file `fd' is out of data
----------------------------------------------- */
int eof(int fd)
{
char c;
if ( read(fd, &c, 1) != 1 )
return(1);
else
{ lseek(fd, -1, SEEK_CUR);
return(0);
}
}
void main()
{
FILE *fp; /* Used to access meta data */
int fd; /* Used to access user data */
/* ----------------------------------------------------------------
Variables to hold the description of the data - max 10 fields
---------------------------------------------------------------- */
struct DataDescription DataDes[10]; /* Holds data descriptions
for upto 10 fields */
int n_fields; /* Actual # fields */
/* ------------------------------------------------------
Variables to hold the data - max 10 fields....
------------------------------------------------------ */
char c_buffer[10][100]; /* For character data */
int i_buffer[10]; /* For integer data */
double d_buffer[10];
int i, j;
int found;
printf("Program for searching a mini database:\n");
/* =============================
Read in meta information
============================= */
fp = fopen("db-description", "r");
n_fields = 0;
while ( fscanf(fp, "%s %c %d", DataDes[n_fields].fieldname,
&DataDes[n_fields].fieldtype,
&DataDes[n_fields].fieldsize) > 0 )
n_fields++;
/* ---
Prints meta information
--- */
printf("\nThe database consists of these fields:\n");
for (i = 0; i < n_fields; i++)
printf("Index %d: Fieldname `%s',\ttype = %c,\tsize = %d\n",
i, DataDes[i].fieldname, DataDes[i].fieldtype,
DataDes[i].fieldsize);
printf("\n\n");
/* ---
Open database file
--- */
fd = open("db-data", O_RDONLY);
/* ---
Print content of the database file
--- */
printf("\nThe database content is:\n");
while ( ! eof(fd) )
{ /* ------------------
Read next record
------------------ */
for (j = 0; j < n_fields; j++)
{
if ( DataDes[j].fieldtype == 'I' )
read(fd, &i_buffer[j], DataDes[j].fieldsize);
if ( DataDes[j].fieldtype == 'F' )
read(fd, &d_buffer[j], DataDes[j].fieldsize);
if ( DataDes[j].fieldtype == 'C' )
read(fd, &c_buffer[j], DataDes[j].fieldsize);
}
double d;
/* ------------------
Print it...
------------------ */
for (j = 0; j < n_fields; j++)
{
if ( DataDes[j].fieldtype == 'I' )
printf("%d ", i_buffer[j]);
if ( DataDes[j].fieldtype == 'F' )
d = d_buffer[j];
printf("%lf ", d);
if ( DataDes[j].fieldtype == 'C' )
printf("%s ", c_buffer[j]);
}
printf("\n");
}
printf("\n");
printf("\n");
}
预期输出:以数字“e = 2.18281828”结尾的 3 行数据
要重现该问题,以下两个文件需要与 lookup-data.c 文件位于同一目录中:
- [db-data][1]
- [db-description][2]