C 给文件命名日期

C 给文件命名日期,c,fopen,C,Fopen,首先:我知道,以前也有过类似的问题,但对我来说不起作用 我需要用C创建一个名为“年/月/日\小时:分钟”的.txt文件 我的代码是: #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> int main(){ int hours, minutes, seconds, day, month, year; char fileSpec [255]; //

首先:我知道,以前也有过类似的问题,但对我来说不起作用

我需要用C创建一个名为“年/月/日\小时:分钟”的.txt文件

我的代码是:

#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\n",day,month,year,hours,minutes,seconds);
}
#包括
#包括
#包括
#包括
int main(){
整小时,分,秒,日,月,年;
char fileSpec[255];
//输入文件名的时间
现在是时候了;
时间(现在);
printf(“今天是:%s”,ctime(&now));
struct tm*local=localtime(&now);
小时数=本地->tm_小时;
分钟=本地->tm\u分钟;
秒=本地->tm_秒;
day=本地->tm\mday;
月份=本地->每月一次+1;
年份=本地->tm\U年份+1900;
//时间块结束
//创建文件
文件*fPointer;
snprintf(fileSpec,“%04d_u%02d_%02d_%02d:%02d.txt”,年、月、日、小时、分钟);//来自另一篇文章。我不知道确切的语法
fPointer=fopen(fileSpec,“w”);
fprintf(fPointer,“创建日期和时间:%d/%d/%d%d:%d:%d\n”,日、月、年、时、分、秒);
}
Sry用于我的奇怪格式:/

我还是个初学者


编辑:整个代码是:

我有一次在Android上遇到类似的问题,我花了几个小时试图解决这个问题。结果证明这是我的问题

问题是您不能使用“/”符号作为文件名,因为在文件系统中它被称为目录分隔符。因此,文件系统可能会卡住,或者可能永远找不到名称中包含“/”的文件


对此的一个综合答案是,

调用snprintf的第二个参数应该是max.buffer size,您没有给出该参数。替换

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


(其中255是snprintf将写入的字符串的最大长度)似乎应该可以解决您的问题。

您应该说明实际的问题是什么。但我猜这是由于在文件名中使用了/造成的。这不适用于分隔目录。您需要
fclose(fPointer)
我试过了,但仍然不起作用。你试过什么?我想说的是,你的文件名中不能有“/”符号。也许可以用下划线
或其他可以使用的符号替换。我确实用替换了它,但仍然不起作用。最新版本在粘贴库中。你在使用windows吗?如果是,请按照sugg来自此的估计
snprintf( fileSpec, 255, "%04d_%02d_%02d_%02d:%02d.txt",year,month,day,hours,minutes);