c - 使用 time.h 将时间写入 C 中的文件

标签 c

所以基本上我已经用 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 The fseek function sets the file position indicator for the stream pointed to by stream. If a read or write error occurs, the error indicator for the stream is set and fseek 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 by whence. The specified position is the beginning of the file if whence is SEEK_SET, the current value of the file position indicator if SEEK_CUR, or end-of-file if SEEK_END. A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END.

4 For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.

关于c - 使用 time.h 将时间写入 C 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14214114/

相关文章:

c - 如何按值而不是引用添加字符串

c++ - 指针如何允许硬件访问?

c - 通过C中的共享内存将结构传递给进程

c - 我输出的第一个字符在 C 中被省略

c - 如何在 C 的共享库中使用外部符号

c - C 语言的 aws 版本 4 签名

c - 如何避免mutex_lock阻塞?

c++ - C++ vs C源代码的编译和执行时间

c - char 指针的动态数组

c - 变量参数函数的堆栈激活框架如何工作?