C 命名一个文件的日期
C name a file the date
首先:我知道,以前也出现过一些类似的问题,但对我不起作用。
我需要在 C 中创建一个名为“year/month/day[ 的 .txt 文件=29=]_小时 :分钟
我的代码是:
#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);
}
对不起我奇怪的格式:/
我还是初学者
编辑:整个代码为:https://pastebin.com/78fSRJgx
我曾经在 Android 上遇到过类似的问题,我花了几个小时试图找出问题所在。原来是我的问题。
问题是您不能使用“/”符号作为文件名,因为在文件系统中它被认为是目录的分隔符。因此,文件系统可能会卡住,或者可能永远找不到名称中包含“/”的文件。
对此的综合回答是this
调用 snprintf 的第二个参数应该是 max。缓冲区大小,你没有给出那个参数。正在替换
snprintf( fileSpec, "%04d_%02d_%02d_%02d:%02d.txt",year,month,day,hours,minutes);
和
snprintf( fileSpec, 255, "%04d_%02d_%02d_%02d:%02d.txt",year,month,day,hours,minutes);
(其中 255 是 snprintf 将写入的字符串的最大长度)似乎应该可以解决您的问题。
首先:我知道,以前也出现过一些类似的问题,但对我不起作用。
我需要在 C 中创建一个名为“year/month/day[ 的 .txt 文件=29=]_小时 :分钟
我的代码是:
#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);
}
对不起我奇怪的格式:/
我还是初学者
编辑:整个代码为:https://pastebin.com/78fSRJgx
我曾经在 Android 上遇到过类似的问题,我花了几个小时试图找出问题所在。原来是我的问题。
问题是您不能使用“/”符号作为文件名,因为在文件系统中它被认为是目录的分隔符。因此,文件系统可能会卡住,或者可能永远找不到名称中包含“/”的文件。
对此的综合回答是this
调用 snprintf 的第二个参数应该是 max。缓冲区大小,你没有给出那个参数。正在替换
snprintf( fileSpec, "%04d_%02d_%02d_%02d:%02d.txt",year,month,day,hours,minutes);
和
snprintf( fileSpec, 255, "%04d_%02d_%02d_%02d:%02d.txt",year,month,day,hours,minutes);
(其中 255 是 snprintf 将写入的字符串的最大长度)似乎应该可以解决您的问题。