所以基本上我已经用 C 语言完成了这个项目 - 我必须设计一个客户/订单系统,其中客户可以发出多个订单,但每个订单仅限于一种产品类型。我创建了一个结构体“orders”,其中包含客户 ID、产品名称、价格和订单时间。下面是计算时间的代码:
// computing order time
time_t timeorder;
char * displayT;
timeorder = time(NULL);
// convert time to string so that it can be displayed
displayT= ctime(&timeorder);
printf("Your order time is: %s\n", displayT); //check if time displays correctly
newOrders11[count13].timeorder = displayT;
紧接着,结构“orders”被写入文件。用户下订单后,输入他/她的 ID 号后应该可以查看他/她的最新订单。但是,当从文件中读取订单时,将显示用户下的第一个订单(而不是最新的订单)。这是从文件读取的代码:
while (count13<=MAXORDERSTOBEMADE && (fread(&newOrders11[count13], sizeof(struct orders), 1, filePointer))==1)
{
if(ID == newOrders11[count13].ID) {
printf("These are the details for order %i\n", count13);
if(count13>=0)
printf("Customer ID: %d\n", newOrders11[count13].ID);
printf("Product Name: %s\n", newOrders11[count13].productname);
printf("Price: %f\n", newOrders11[count13].total);
} else {
continue;
}
count13++;
}
有人知道我该怎么做吗?抱歉,我还是个C初学者。这是我用 C 编写的第一个程序。
最佳答案
在 while
循环中,您仅针对客户 ID 进行测试,因此该客户的第一条记录将匹配。
鉴于文件中的记录按时间戳排序,因此从文件末尾开始读取可能比从头开始读取更好:
fseek(filePointer, -sizeof (struct orders), SEEK_END);
while (count13 <= MAXORDERSTOBEMADE && (fread(...) == 1))
{
if (ID == ...)
{
...
}
else
{
fseek(filePointer, -2 * sizeof(struct orders), SEEK_CUR);
}
}
注意事项:二进制流可能不支持SEEK_END
,并且任意偏移量对于文本流可能没有意义:
7.21.9.2 The fseek function
2 Thefseek
function sets the file position indicator for the stream pointed to bystream
. If a read or write error occurs, the error indicator for the stream is set andfseek
fails.
3 For a binary stream, the new position, measured in characters from the beginning of the file, is obtained by adding offset to the position specified bywhence
. The specified position is the beginning of the file if whence isSEEK_SET
, the current value of the file position indicator ifSEEK_CUR
, or end-of-file ifSEEK_END
. A binary stream need not meaningfully supportfseek
calls with awhence
value ofSEEK_END
.
4 For a text stream, eitheroffset
shall be zero, oroffset
shall be a value returned by an earlier successful call to theftell
function on a stream associated with the same file andwhence
shall beSEEK_SET
.
关于c - 使用 time.h 将时间写入 C 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14214114/