【问题标题】:Trying to create a text file with the current date as the filename, but fopen does not generate the file试图创建一个以当前日期为文件名的文本文件,但 fopen 不生成文件
【发布时间】:2020-09-05 14:33:45
【问题描述】:

这里是初学者,我一直在练习字符串和文件,我一直在尝试生成这个以当前日期为文件名的文本文件,但由于某种原因,fopen 不会生成文件。有什么建议吗?

这是我的代码:

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

main() {

    FILE *fLog;
    time_t actualtime;
    struct tm *day;
    char Date[13];
    
    time(&actualtime);
    
    day = localtime(&actualtime);
    strftime(Date, 10, "%x", day);
    
    strcat(Date, ".txt");
    
    printf("%s", Date);
    fLog = fopen(Date, "w");
    fprintf(fLog, "Hello world");
    fclose(fLog);
}

【问题讨论】:

  • 您对strftime 的调用产生了无效的文件名:09/05/20.txt 其中包含目录分隔符。尝试在您的桌面上创建一个看起来像这样的文件,看看操作系统告诉您什么。它可能做的另一件事是尝试找到可能不存在的目录路径09/05/,这就是为什么你不能在那里创建文件20.txt
  • 作为诊断,测试库函数返回值很有用,并检查全局errno 以了解库函数失败原因的详细信息。从教程示例中省略,但常用于工业级程序。见stackoverflow.com/questions/16507816/…

标签: c


【解决方案1】:

由于您已在此问题中标记了c++,因此我将为您提供 C++ 解决方案。

#include <iostream>
#include <chrono>
#include <ctime>   
#include <string>
#include <fstream>

using namespace std; 

int main()
{
    auto start = std::chrono::system_clock::now();
    std::time_t end_time = std::chrono::system_clock::to_time_t(start);
    cout<<ctime(&end_time);

    ofstream f1;
    f1.open(static_cast<string>(ctime(&end_time)));

}

这里我使用this 回答获取当前日期,将其转换为字符串并用它打开一个文件名。

这将生成一个以当前日期为名称的文件,然后您可以使用它执行所需的操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    相关资源
    最近更新 更多