【发布时间】:2017-09-10 20:07:08
【问题描述】:
嗨。
如您所见,我正在尝试将来自 C 项目的最新数据保存在日志文件中,其中文件名对应于实际时间/日期。
虽然路径在控制台中正确组合并显示,但文件本身以一个奇怪的点开头,更准确地说,是一个空格,后面跟着那个点和另一个空格,显示在图片中。
我使用的是 Windows 7 64bit 和 cygwin64。
相关的代码位是:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
void save_to_file(char* timestamp, char* homepath, int generation)
char* create_timestamp(char* timestamp)
int main(){
char homepath[28] = "D:\\cygwin64\\home\\ignite\\log\\";
int generation = 0;
char* timestamp = malloc (30 * sizeof(char));
create_timestamp(timestamp);
save_to_file(timestamp, homepath, generation);
}
void save_to_file(char* timestamp, char* homepath, int generation){
char string[4];
char logchar[4] = "log";
char dot[] = {"."};
char fileend[5] = {".txt"};
char* path = malloc(60*sizeof(char));
strcpy(path, homepath);
strcat(path, logchar);
snprintf(string, 4, "%d", generation);
strcat(path, string);
strcat(path, dot);
strcat(path, timestamp);
strcat(path, fileend);
FILE* f = fopen(path, "ab+");
if(f == NULL){
printf("Error opening file!\n");
exit(1);
}
else{
//write to file
}
}
char* create_timestamp(char* timestamp){
time_t rawtime;
struct tm *info;
char buffer[30], *string, *work;
string = malloc (5* sizeof(char));
work = malloc (30* sizeof(char));
char point[] = {"."};
time( &rawtime );
info = localtime( &rawtime );
strcpy(buffer, asctime(info));
int n = info->tm_mday;
snprintf(string, 4, "%d", n);
strcpy(work, string);
n = (int) info->tm_mon + 1;
snprintf(string, 3, "%d", n);
strcat(work, point);
strcat(work, string);
///*
n = info->tm_year + 1900;
snprintf(string, 5, "%d", n);
strcat(work, point);
strcat(work, string);
n = info->tm_hour;
snprintf(string, 3, "%d", n);
strcat(work, point);
strcat(work, string);
n = info->tm_min;
snprintf(string, 3, "%d", n);
strcat(work, point);
strcat(work, string);
n = info->tm_sec;
snprintf(string, 3, "%d", n);
strcat(work, point);
strcat(work, string);
strcpy(timestamp, work);
free(string);
return timestamp;
}
【问题讨论】:
-
告诉我们你如何获得
homepath? -
您使用的是 Windows 还是 Linux?如前所述,您所展示的并不是相关代码的所有。包含足够的内容,以便提供的内容可以编译。
-
请参阅How to create a Minimal, Complete and Verifiable Example。您的代码使用了几个您尚未定义的变量(例如,
homepath、generation、timestamp),这些变量都在该代码块中使用。您的代码应该包含一个完整的示例,如果需要,我们可以复制/粘贴和编译。 -
因为您在
fopen()中使用了"ab+"选项,是否可以合理地预期您正在打开的文件是预先存在的,(即并且可能包含后面的空格通过那个点和另一个空格)? -
你的数组太短了。
"D:\\cygwin64\\home\\ignite\\log\\"是 29 个字节。