生成固定格式文本文件(如銀行話單、EDI 報文),要求每字段固定寬度 10 字符,不足部分按規則填充:
| 模式 | 格式字符串 | 示例輸入 "abc" | 說明 |
|---|---|---|---|
| 左對齊,右填空格 | `%-10s` | `"abc "` | 標準左對齊 |
| 右對齊,左填空格 | `%10s` | `" abc"` | 標準右對齊 |
| 左對齊,右填 0 | `%-s%0*d` | `"abc0000000"` | 字符串 + 寬度為 (10-len) 的零填充整數 |
| 右對齊,左填 0 | `%0*d%s` | `"0000000abc"` | 零填充整數 + 字符串 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int INT32;
typedef char INT8;
void write_aligned_field(INT32 align_mode, const INT8 *input) {
INT8 buffer[64] = {0};
const INT32 FIELD_WIDTH = 10;
INT32 len = strlen(input);
switch (align_mode) {
case 1: // 左對齊,右填空格
snprintf(buffer, sizeof(buffer), "%-*s", FIELD_WIDTH, input);
break;
case 2: // 右對齊,左填空格
snprintf(buffer, sizeof(buffer), "%*s", FIELD_WIDTH, input);
break;
case 3: // 左對齊,右填 0
snprintf(buffer, sizeof(buffer), "%-s%0*d", input, FIELD_WIDTH - len, 0);
break;
case 4: // 右對齊,左填 0
snprintf(buffer, sizeof(buffer), "%0*d%s", FIELD_WIDTH - len, 0, input);
break;
default:
fprintf(stderr, "無效模式: %d\n", align_mode);
return;
}
FILE *fp = fopen("output.txt", "w");
if (fp) {
fputs(buffer, fp);
fclose(fp);
printf("寫入成功: [%s]\n", buffer);
} else {
perror("文件打開失敗");
}
}
int main() {
INT32 mode;
INT8 input[64];
printf("輸入模式 (1-4) 和字符串: ");
scanf("%d %63s", &mode, input);
write_aligned_field(mode, input);
return 0;
}
snprintf(buf, size, "%*s", width, str); // 右對齊,寬度由 width 指定 snprintf(buf, size, "%-*s", width, str); // 左對齊
snprintf(buf, size, "%0*d", width, 0); // 輸出 width 個 '0'
// 左對齊右填0:字符串 + 零串 "%-s%0*d" → input + (width-len)個'0' // 右對齊左填0:零串 + 字符串 "%0*d%s" → (width-len)個'0' + input
輸入: 1 hello 輸出: [hello ] (左對齊,右5空格) 輸入: 2 hello 輸出: [ hello] (右對齊,左5空格) 輸入: 3 hello 輸出: [hello00000] (左對齊,右5零) 輸入: 4 hello 輸出: [00000hello] (右對齊,左5零)
利用 `snprintf` 的動態寬度 `*`、零填充 `0`、左對齊 `-` 三大標準格式修飾符組合,即可實現所有固定寬度字段對齊填充需求。本文封裝的 `write_aligned_field` 函數可直接集成到話單生成、報文構建等固定格式文件輸出系統中。