Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

fopen - C name a file the date

First off all: I know, some similar problems have been there before, but it does not work for me.

I need to create a .txt file in C which is called "year/month/day_hour :minute

My code is:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(){
int hours, minutes, seconds, day, month, year;
char fileSpec [255];
//TIME for file name
    time_t now;
    time(&now);
    printf("Today is : %s", ctime(&now));
    struct tm *local = localtime(&now);
 
    hours = local->tm_hour;          
    minutes = local->tm_min;         
    seconds = local->tm_sec;         
 
    day = local->tm_mday;            
    month = local->tm_mon + 1;       
    year = local->tm_year + 1900;   
      
    //Time block end

    //create file
    FILE * fPointer;
    snprintf( fileSpec, "%04d_%02d_%02d_%02d:%02d.txt",year,month,day,hours,minutes); //From another post. I do not exactly know the syntax
    fPointer = fopen(fileSpec,"w");
    fprintf(fPointer ,"Date and Time of creation: %d/%d/%d %d:%d:%d
",day,month,year,hours,minutes,seconds);
}

Sry for my strange formatting :/

I am still quite a beginner.

Edit: The whole code is: https://pastebin.com/78fSRJgx

question from:https://stackoverflow.com/questions/65842499/c-name-a-file-the-date

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The second argument in a call to snprintf should be max. buffer size, you didn't give that argument. Replacing

snprintf( fileSpec, "%04d_%02d_%02d_%02d:%02d.txt",year,month,day,hours,minutes);

with

snprintf( fileSpec, 255, "%04d_%02d_%02d_%02d:%02d.txt",year,month,day,hours,minutes);

(where 255 is the maximum length of the string snprintf will write) seems like it should solve your problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...