- 1 year ago
Adding Date string to beginning of filename in C, WINAPI
To add a date string to the beginning of a filename in C using the WinAPI, you can follow these steps:
Get the current date and time:
- Use the
GetSystemTime
orGetLocalTime
function to retrieve the current date and time information. These functions populate aSYSTEMTIME
structure with the current system date and time.
- Use the
Format the date and time into a string:
- Use the
sprintf
orsnprintf
function to format the date and time into a string. You can specify the desired format using format specifiers, such as%04d
for the year,%02d
for the month and day, and so on.
- Use the
Concatenate the date string with the original filename:
- Combine the date string with the original filename using string concatenation or string manipulation functions, such as
strcat
orsprintf
.
- Combine the date string with the original filename using string concatenation or string manipulation functions, such as
Rename the file:
- Use the
MoveFile
orMoveFileEx
function to rename the file by providing the original filename with the added date string as the new filename.
- Use the
Here's an example implementation:
c#include <stdio.h>
#include <Windows.h>
int main()
{
SYSTEMTIME currentTime;
GetLocalTime(¤tTime);
char dateString[20];
snprintf(dateString, sizeof(dateString), "%04d%02d%02d", currentTime.wYear, currentTime.wMonth, currentTime.wDay);
const char* originalFilename = "example.txt";
char newFilename[FILENAME_MAX];
snprintf(newFilename, sizeof(newFilename), "%s_%s", dateString, originalFilename);
if (MoveFile(originalFilename, newFilename))
{
printf("File renamed successfully.\n");
}
else
{
DWORD error = GetLastError();
printf("Failed to rename file. Error code: %d\n", error);
}
return 0;
}
In this example, the current date and time are retrieved using GetLocalTime
. The date string is formatted using snprintf
. Then, the original filename is combined with the date string to create the new filename. Finally, the MoveFile
function is used to rename the file. If the renaming is successful, a success message is printed. Otherwise, the error code is printed.
Make sure to include the necessary headers (stdio.h
and Windows.h
) and link against the required libraries when compiling the code.