Here's an improved version of the code with enhanced error handling, clarity, and use of standard functions:
#include <stdio.h>
#include <time.h>
/**
* Formats a measurement value with the current timestamp into a string.
*
* @param measurement The measured value to include in the string.
* @param buf Buffer to store the formatted string.
* @param size Size of the buffer.
* @return 0 on success, negative error code otherwise:
* -1: Failed to get current time
* -2: Failed to format timestamp
* -3: Buffer too small
*/
int generate_measurement_string(double measurement, char *buf, size_t size) {
// Step 1: Obtain current time
time_t now_time;
if (time(&now_time) == -1) {
return -1; // Error getting current time
}
struct tm *now_tm = localtime(&now_time);
if (now_tm == NULL) {
return -1; // Failed to convert to local time
}
// Step 2: Format timestamp
char time_str[21]; // Sufficient for "YYYY-MM-DD HH:MM:SS\0"
if (!strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", now_tm)) {
return -2; // Failed to format timestamp
}
// Step 3: Calculate required buffer size
int required_size = snprintf(NULL, 0, "Measurement: %.2f, Timestamp: %s",
measurement, time_str);
if (required_size < 0) {
return -2; // Invalid format string
}
// Step 4: Check buffer size
if ((size_t)required_size + 1 > size) { // +1 for null terminator
return -3; // Buffer too small
}
// Step 5: Write formatted string to buffer
snprintf(buf, size, "Measurement: %.2f, Timestamp: %s",
measurement, time_str);
return 0; // Success
}
Key improvements made:
-
Standard Functions: Replaced custom get_date() with standard time() and localtime() for better portability.
-
Error Codes: Added specific error codes for different failure scenarios:
-1 for time-related errors
-2 for formatting issues
-3 for buffer overflow
-
Buffer Safety:
- Uses
strftime with a precisely-sized buffer (21 characters for the timestamp)
- Calculates required buffer size using
snprintf(NULL, 0, ...) to ensure proper buffer sizing
-
Documentation:
- Added a detailed docstring explaining parameters and return values
- Comments explaining each step of the process
-
Clarity:
- Improved variable names for better readability
- Clear separation of logical steps
- Explicit checks for all possible failure points
-
Precision:
- The timestamp buffer size was calculated precisely based on the format string
- The measurement is formatted to 2 decimal places consistently
To use this function safely, the caller should provide a buffer of at least 54 characters (calculated as:
"Measurement: " (12) + 10 (for -99999.99) + ", " (2) +
"Timestamp: " (11) + 19 (timestamp) + 1 (null) = 54)
Example usage:
#include <stdio.h>
int main() {
char buffer[54];
if (generate_measurement_string(25.67, buffer, sizeof(buffer)) == 0) {
printf("%s\n", buffer);
} else {
puts("Formatting failed");
}
return 0;
}
This version maintains the original functionality while adding robust error handling, improved safety, and better documentation for textbook use.