0

Beginner here, I've been practicing with strings and files, and I've been trying to generate this text file that has the current date as the file name, but for some reason, fopen doesn't generate the file. Any advice?

Here's my code:

#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);
}
πάντα ῥεῖ
  • 83,259
  • 13
  • 96
  • 175
  • your call to `strftime` is producing an invalid file name: `09/05/20.txt` That has directory separator chars in it. Try to create a file on your desktop that looks like that and see what the OS tells you about it. The other thing it could be doing is trying to find the directory path `09/05/` which probably doesn't exist, which is why you can't create the file `20.txt` there. – Andy Sep 05 '20 at 06:27
  • As a diagnostic, it's useful to test the library function return value, and check the global `errno` for details of why the library function failed. Omitted from tutorial examples, but commonly used in industrial-strength programs. See https://stackoverflow.com/questions/16507816/what-kind-of-errors-set-errno-to-non-zero-why-does-fopen-set-errno-while – MarkU Sep 05 '20 at 06:32

1 Answers1

1

Since you have tagged c++ in this question so I will provide you with C++ solution to it.

#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)));

}

Here I used this answer to get current date, converted it into string and opened a file name with it.

This will generate a file with current date as it's name, and then you can perform your desired operations with it.

Ahmad Anis
  • 1,026
  • 10
  • 19