c - fopen 文件名以奇怪的点开头

标签 c file fopen

/image/4TmGr.png

嗨。

正如您所见,我正在尝试将 C 项目的最新数据保存在日志文件中,其中文件名对应于实际时间/日期。

虽然路径在控制台内正确组合并显示,但文件本身以一个奇怪的点开头,更准确地说是一个空格,后跟该点和另一个空格,显示在图片中。

我使用的是 Windows 7 64 位和 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;
}

最佳答案

Your array is too short. "D:\cygwin64\home\ignite\log\" is 29 bytes. – melpomene

关于c - fopen 文件名以奇怪的点开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43413651/

相关文章:

c++ - git merge 没有冲突就代表一切正常吗?

java - 当我们使用 renameTo() 两次失败时,为什么?

java - 将文件转换为字节数组再转换为字符串的更有效方法

ruby - 删除文本文件中的特定行?

c - fopen 未打开文件

c - 如果在同一执行中写入和读取文件,程序将挂起

c - 使用 C 访问 Twitter Streaming API

c++ - 读取音频流到输出设备

c - 在结构体中引用结构体

c - fopen 后检测文件删除