如何在每行末尾而非开头插入指定符号?C+WinAPI代码修正
修正WinAPI C代码:将指定符号插入每行末尾而非开头
问题根源是代码逻辑顺序错误——当前先写入指定符号,再写入行内容,导致符号出现在行首。只需调整写入顺序,先输出行内容,再输出符号即可。
修正后的完整代码
#include <windows.h> #include <stdio.h> #include <string.h> #define BUFFER_SIZE 1024 int main() { // 替换为实际输入输出文件路径 LPCWSTR inputPath = L"input.out"; LPCWSTR outputPath = L"output.txt"; // 替换为用户指定的插入符号 const char* insertSymbol = "||"; DWORD dwRead, dwWritten; char buffer[BUFFER_SIZE]; BOOL isFirstLine = TRUE; // 打开输入文件 HANDLE hInput = CreateFileW(inputPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hInput == INVALID_HANDLE_VALUE) { printf("打开输入文件失败,错误码: %lu\n", GetLastError()); return 1; } // 创建输出文件(覆盖已有文件) HANDLE hOutput = CreateFileW(outputPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hOutput == INVALID_HANDLE_VALUE) { printf("创建输出文件失败,错误码: %lu\n", GetLastError()); CloseHandle(hInput); return 1; } // 逐段读取文件并分割行处理 while (ReadFile(hInput, buffer, BUFFER_SIZE - 1, &dwRead, NULL) && dwRead > 0) { buffer[dwRead] = '\0'; // 确保字符串终止 char* line = strtok(buffer, "\r\n"); while (line != NULL) { if (!isFirstLine) { // 非首行先写入换行符,保证行分隔正确 WriteFile(hOutput, "\r\n", 2, &dwWritten, NULL); } isFirstLine = FALSE; // 核心修正:先写行内容,再写指定符号 WriteFile(hOutput, line, strlen(line), &dwWritten, NULL); WriteFile(hOutput, insertSymbol, strlen(insertSymbol), &dwWritten, NULL); line = strtok(NULL, "\r\n"); } } // 关闭资源 CloseHandle(hInput); CloseHandle(hOutput); printf("处理完成,输出文件已生成\n"); return 0; }
关键修改说明
- 写入顺序调换:原代码中是先输出符号再输出行内容,现在改为先输出读取到的行内容,再输出指定符号,直接解决符号位置错误的问题。
- 换行符处理:添加了首行判断,确保非首行先写入换行符,避免输出内容出现格式混乱。
- 可配置项:预留了文件路径和插入符号的替换位置,方便用户根据实际需求修改。
内容的提问来源于stack exchange,提问作者Marchenko
相关产品推荐
相关产品推荐

