void exitApp() {
// Countdown before exit
for (int i = 60; i > 0; --i) {
printf("Exiting in %d seconds...\r", i);
fflush(stdout);
Sleep(1000);
}
printf("\n");
}
int main() {
system("title Recursive folder synchronization with server (v2025-06-18-Libor)");
code
char exePath[MAX_PATH];
char exeDir[MAX_PATH];
char scriptPath[MAX_PATH];
char logPath[MAX_PATH];
char winSCPPath[MAX_PATH];
char winExePath[MAX_PATH];
char commandLine[1024];
// Record the start time
clock_t start_time = clock();
code
printf("Recursive folder synchronization with server (v2025-06-18-Libor)");
printf("\n\n");
// Get path to this EXE
GetModuleFileNameA(NULL, exePath, MAX_PATH);
strcpy(exeDir, exePath);
char *lastSlash = strrchr(exeDir, '\\');
if (lastSlash) *lastSlash = '\0';
char mutexName[64];
if (g_hMutex == NULL) {
fprintf(stderr, "Error: Failed to create mutex %s.\n\n", mutexName);
exitApp();
return 1;
}
if (GetLastError() == ERROR_ALREADY_EXISTS) {
fprintf(stderr, "Error: Another instance of ftpconn.exe is already running...\n\n");
CloseHandle(g_hMutex);
exitApp();
return 1;
}
code
// Build paths
sprintf(scriptPath, "%s\\ftpconn.exe.config", exeDir);
sprintf(winSCPPath, "%s\\WinSCP.com", exeDir);
sprintf(winExePath, "%s\\WinSCP.exe", exeDir);
if (!file_exists(winExePath)) {
fprintf(stderr, "Error: WinSCP.exe portable file not found at %s\n\n", exeDir);
exitApp();
return 1;
}
if (!file_exists(winSCPPath)) {
fprintf(stderr, "Error: WinSCP.com portable file not found at %s\n\n", exeDir);
exitApp();
return 1;
}
if (!file_exists(scriptPath)) {
fprintf(stderr, "Error: ftpconn.exe.config file not found at %s\n\n", exeDir);
exitApp();
return 1;
}
SYSTEMTIME st;
GetLocalTime(&st);
sprintf(logPath, "%s\\FtpConn.%04d-%02d-%02d.log", exeDir, st.wYear, st.wMonth, st.wDay);
printf("Log file: ");
printf(logPath);
printf("\n\n");
// Open log file
FILE *logFile = fopen(logPath, "a");
if (!logFile) {
fprintf(stderr, "Error: Failed to open log file: %s\n", logPath);
exitApp();
return 1;
}
WriteTimestampToFile(logFile, "START");
WriteTimestamp("START");
printf("\n");
// Set up pipes
SECURITY_ATTRIBUTES sa = { sizeof(sa), NULL, TRUE };
HANDLE readPipe, writePipe;
CreatePipe(&readPipe, &writePipe, &sa, 0);
SetHandleInformation(readPipe, HANDLE_FLAG_INHERIT, 0); // prevent child from inheriting read
// Set up process startup info
STARTUPINFOA si = { sizeof(si) };
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdOutput = writePipe;
si.hStdError = writePipe;
si.hStdInput = NULL;
PROCESS_INFORMATION pi;
// Build command line for WinSCP
sprintf(commandLine, "\"%s\" /script=\"%s\"", winSCPPath, scriptPath);
// Launch WinSCP
if (!CreateProcessA(NULL, commandLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
fprintf(stderr, "Error: Failed to start portable WinSCP. Files needed: WinSCP.com, WinSCP.exe\n\n");
fclose(logFile);
CloseHandle(writePipe);
CloseHandle(readPipe);
exitApp();
return 1;
}
CloseHandle(writePipe); // parent doesn't write
// Read from child process output and write to log and console
char buffer[4096];
DWORD bytesRead;
while (ReadFile(readPipe, buffer, sizeof(buffer) - 1, &bytesRead, NULL) && bytesRead > 0) {
buffer[bytesRead] = '\0';
fputs(buffer, stdout); // show in console
fputs(buffer, logFile); // write to log
fflush(stdout);
fflush(logFile);
}
// Cleanup
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
CloseHandle(readPipe);
printf("\n");
WriteTimestampToFile(logFile, "FINISH");
WriteTimestamp("FINISH");
// Record the end time
clock_t end_time = clock();
// Calculate the execution time in seconds
double cpu_time_used = ((double) (end_time - start_time)) / CLOCKS_PER_SEC;
#include <windows.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#define MAX_PATH_LENGTH 260
#define MAX_COMMAND_LINE_LENGTH 1024
#define MAX_BUFFER_SIZE 4096
#define MUTEX_NAME_FORMAT "Local\\FtpConnMutex_%08X"
#define LOG_FILE_NAME_FORMAT "%s\\FtpConn.%04d-%02d-%02d.log"
HANDLE g_hMutex = NULL;
/**
* Checks if a file exists at the given path.
*
* @param path The path to the file.
* @return 1 if the file exists, 0 otherwise.
*/
int is_file_exists(const char *path) {
DWORD attrs = GetFileAttributesA(path);
return (attrs != INVALID_FILE_ATTRIBUTES) && !(attrs & FILE_ATTRIBUTE_DIRECTORY);
}
/**
* Writes a timestamp to a file.
*
* @param logFile The file to write to.
* @param label The label to include in the timestamp.
*/
void write_timestamp_to_file(FILE *logFile, const char *label) {
SYSTEMTIME st;
GetLocalTime(&st);
fprintf(logFile, "\n=== [%04d-%02d-%02d %02d:%02d:%02d] %s ===\n",
st.wYear, st.wMonth, st.wDay,
st.wHour, st.wMinute, st.wSecond, label);
fflush(logFile);
}
/**
* Writes a timestamp to the console.
*
* @param label The label to include in the timestamp.
*/
void write_timestamp(const char *label) {
SYSTEMTIME st;
GetLocalTime(&st);
printf("\n=== [%04d-%02d-%02d %02d:%02d:%02d] %s ===\n",
st.wYear, st.wMonth, st.wDay,
st.wHour, st.wMinute, st.wSecond, label);
}
/**
* Computes the CRC32 hash of a string.
*
* @param s The string to hash.
* @return The CRC32 hash of the string.
*/
unsigned int crc32(const unsigned char *s) {
unsigned int crc = 0xFFFFFFFF;
while (*s) {
unsigned char b = *s++;
for (int i = 0; i < 8; ++i) {
unsigned int mask = -((crc ^ b) & 1);
crc = (crc >> 1) ^ (0xEDB88320 & mask);
b >>= 1;
}
}
return ~crc;
}
/**
* Creates a mutex name from a folder path.
*
* @param folderPath The folder path.
* @param mutexNameOut The output buffer for the mutex name.
*/
void make_mutex_name_from_path(const char *folderPath, char *mutexNameOut) {
unsigned int hash = crc32((const unsigned char *)folderPath);
sprintf(mutexNameOut, MUTEX_NAME_FORMAT, hash);
}
/**
* Displays a countdown before exiting the application.
*/
void exit_app() {
// Countdown before exit
for (int i = 60; i > 0; --i) {
printf("Exiting in %d seconds...\r", i);
fflush(stdout);
Sleep(1000);
}
printf("\n");
}
/**
* Sets the console title.
*/
void set_console_title() {
system("title Recursive folder synchronization with server (v2025-06-18-Libor)");
}
/**
* Gets the executable path and directory.
*
* @param exePath The output buffer for the executable path.
* @param exeDir The output buffer for the executable directory.
*/
void get_executable_path(char *exePath, char *exeDir) {
GetModuleFileNameA(NULL, exePath, MAX_PATH_LENGTH);
strcpy(exeDir, exePath);
char *lastSlash = strrchr(exeDir, '\\');
if (lastSlash) *lastSlash = '\0';
}
/**
* Creates a mutex to ensure only one instance is running.
*
* @param mutexName The name of the mutex.
* @return 1 if the mutex was created successfully, 0 otherwise.
*/
int create_mutex(const char *mutexName) {
HANDLE hMutex = CreateMutexA(NULL, FALSE, mutexName);
if (hMutex == NULL) {
fprintf(stderr, "Error: Failed to create mutex %s.\n\n", mutexName);
return 0;
}
if (GetLastError() == ERROR_ALREADY_EXISTS) {
fprintf(stderr, "Error: Another instance of ftpconn.exe is already running...\n\n");
CloseHandle(hMutex);
return 0;
}
g_hMutex = hMutex;
return 1;
}
/**
* Checks for the existence of required files.
*
* @param exeDir The executable directory.
* @return 1 if all required files exist, 0 otherwise.
*/
int check_required_files(const char *exeDir) {
char scriptPath[MAX_PATH_LENGTH];
char winSCPPath[MAX_PATH_LENGTH];
char winExePath[MAX_PATH_LENGTH];
sprintf(scriptPath, "%s\\ftpconn.exe.config", exeDir);
sprintf(winSCPPath, "%s\\WinSCP.com", exeDir);
sprintf(winExePath, "%s\\WinSCP.exe", exeDir);
if (!is_file_exists(winExePath)) {
fprintf(stderr, "Error: WinSCP.exe portable file not found at %s\n\n", exeDir);
return 0;
}
if (!is_file_exists(winSCPPath)) {
fprintf(stderr, "Error: WinSCP.com portable file not found at %s\n\n", exeDir);
return 0;
}
if (!is_file_exists(scriptPath)) {
fprintf(stderr, "Error: ftpconn.exe.config file not found at %s\n\n", exeDir);
return 0;
}
return 1;
}
/**
* Sets up logging by creating a log file.
*
* @param exeDir The executable directory.
* @param logFile The output parameter for the log file handle.
* @param logPath The output buffer for the log file path.
*/
void setup_logging(const char *exeDir, FILE **logFile, char *logPath) {
SYSTEMTIME st;
GetLocalTime(&st);
sprintf(logPath, LOG_FILE_NAME_FORMAT, exeDir, st.wYear, st.wMonth, st.wDay);
printf("Log file: %s\n\n", logPath);
*logFile = fopen(logPath, "a");
if (!*logFile) {
fprintf(stderr, "Error: Failed to open log file: %s\n", logPath);
exit_app();
exit(1);
}
}
/**
* Launches WinSCP with the given script and handles its output.
*
* @param exeDir The executable directory.
* @param scriptPath The path to the script.
* @param logFile The log file handle.
*/
void launch_winscp(const char *exeDir, const char *scriptPath, FILE *logFile) {
char winSCPPath[MAX_PATH_LENGTH];
char commandLine[MAX_COMMAND_LINE_LENGTH];
sprintf(winSCPPath, "%s\\WinSCP.com", exeDir);
sprintf(commandLine, "\"%s\" /script=\"%s\"", winSCPPath, scriptPath);
SECURITY_ATTRIBUTES sa = { sizeof(sa), NULL, TRUE };
HANDLE readPipe, writePipe;
CreatePipe(&readPipe, &writePipe, &sa, 0);
SetHandleInformation(readPipe, HANDLE_FLAG_INHERIT, 0); // prevent child from inheriting read
STARTUPINFOA si = { sizeof(si) };
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdOutput = writePipe;
si.hStdError = writePipe;
si.hStdInput = NULL;
PROCESS_INFORMATION pi;
if (!CreateProcessA(NULL, commandLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
fprintf(stderr, "Error: Failed to start portable WinSCP. Files needed: WinSCP.com, WinSCP.exe\n\n");
fclose(logFile);
CloseHandle(writePipe);
CloseHandle(readPipe);
exit_app();
exit(1);
}
CloseHandle(writePipe); // parent doesn't write
char buffer[MAX_BUFFER_SIZE];
DWORD bytesRead;
while (ReadFile(readPipe, buffer, sizeof(buffer) - 1, &bytesRead, NULL) && bytesRead > 0) {
buffer[bytesRead] = '\0';
fputs(buffer, stdout); // show in console
fputs(buffer, logFile); // write to log
fflush(stdout);
fflush(logFile);
}
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
CloseHandle(readPipe);
}
/**
* Cleans up and exits the application.
*
* @param logFile The log file handle.
* @param start_time The start time of the application.
*/
void cleanup_and_exit(FILE *logFile, clock_t start_time) {
clock_t end_time = clock();
double cpu_time_used = ((double) (end_time - start_time)) / CLOCKS_PER_SEC;
fprintf(logFile, "\nTotal execution time: %f seconds\n\n", cpu_time_used);
printf("\nTotal execution time: %f seconds\n\n", cpu_time_used);
fclose(logFile);
exit_app();
}
/**
* The main function.
*
* @return The exit code.
*/
int main() {
set_console_title();
char exePath[MAX_PATH_LENGTH];
char exeDir[MAX_PATH_LENGTH];
char scriptPath[MAX_PATH_LENGTH];
char logPath[MAX_PATH_LENGTH];
char mutexName[64];
get_executable_path(exePath, exeDir);
make_mutex_name_from_path(exeDir, mutexName);
if (!create_mutex(mutexName)) {
exit_app();
return 1;
}
if (!check_required_files(exeDir)) {
exit_app();
return 1;
}
FILE *logFile;
setup_logging(exeDir, &logFile, logPath);
write_timestamp_to_file(logFile, "START");
write_timestamp("START");
printf("\n");
clock_t start_time = clock();
sprintf(scriptPath, "%s\\ftpconn.exe.config", exeDir);
launch_winscp(exeDir, scriptPath, logFile);
printf("\n");
write_timestamp_to_file(logFile, "FINISH");
write_timestamp("FINISH");
cleanup_and_exit(logFile, start_time);
return 0;
}
The refactored code is more modular, easier to read, and easier to maintain. Each function has a clear purpose, and the code is well-documented and formatted consistently.