这是 C++ 中的代码,它可以工作,但是给定的符号被插入到行的开头,但它应该位于每行的末尾。
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <string>
#define BUF_SIZE 1
int main(int argc, LPTSTR argv[]) {
setlocale(LC_ALL, "Russian");
HANDLE hIn, hOut;
DWORD nIn, nOut;
CHAR Buffer[BUF_SIZE];
char filename[MAX_PATH];
if (argc != 3) {
printf("Usage: lab1 file1 character\n");
printf("-1");
return 1;
}
hIn = CreateFile(argv[1], GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hIn == INVALID_HANDLE_VALUE) {
printf("Unable to open input file. Error: %x\n", GetLastError());
printf("-1");
return 2;
}
char appendChar = *argv[2];
// Check for valid character
if (appendChar == '\0' || appendChar == '\n' || appendChar == '\r') {
printf("Invalid character\n");
CloseHandle(hIn);
printf("-1");
return 3;
}
// Form the name of the output file
strcpy_s(filename, argv[1]);
//len = atoi(argv[2]);
int len = argv[2][0];
char * pos = strstr(filename, ".");
if (pos == NULL) {
strcat_s(filename, ".txt"); // Changed to .txt
}
else {
int letter = pos - filename;
filename[letter + 1] = 't';
filename[letter + 2] = 'x';
filename[letter + 3] = 't';
filename[letter + 4] = '\0'; // Terminate the string
printf("Output file name: %s\n", filename);
}
hOut = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hOut == INVALID_HANDLE_VALUE) {
printf("Unable to create output file. Error: %x\n", GetLastError());
CloseHandle(hIn);
printf("-1");
return 4;
}
int counter = 0;
bool endOfLine = true;
while ((ReadFile(hIn, Buffer, BUF_SIZE, &nIn, NULL) && nIn > 0)) {
if (Buffer[0] == '\n') {
endOfLine = true;
WriteFile(hOut, Buffer, nIn, &nOut, NULL); // Write the newline character
WriteFile(hOut, &appendChar, sizeof(appendChar), &nOut, NULL); // Append the specified character
counter++;
}
else {
WriteFile(hOut, Buffer, nIn, &nOut, NULL);
endOfLine = false;
}
if (nIn != nOut) {
std::cerr << "Write error: " << GetLastError() << std::endl;
CloseHandle(hIn);
CloseHandle(hOut);
printf("-1");
return 5;
}
}
// If the last line does not end with a newline,
// append the specified character at the end of the file
if (!endOfLine) {
WriteFile(hOut, &appendChar, sizeof(appendChar), &nOut, NULL);
counter++;
}
printf("Number of replacements: %d\n", counter);
CloseHandle(hIn);
CloseHandle(hOut);
return 0;
}
它是如何工作的:在主文件夹中有一个文件,其中包含一些扩展名为
.out
的文本,在执行结束时,应该会出现一个扩展名为.txt
的文件,并且将执行任务:插入给定的每行末尾的符号。
输入数据:带代码的文件、带文本的文件、要替换的符号
我已经尝试了一切,字符仍然插入到行首
这些线是向后的:
WriteFile(hOut, Buffer, nIn, &nOut, NULL); // Write the newline character
WriteFile(hOut, &appendChar, sizeof(appendChar), &nOut, NULL); // Append the specified character
当您在输入文件中遇到换行符时,您正在将换行符写入输出文件,然后写入符号。 您需要交换语句,以便先写入符号,然后写入换行符。
另外,不要忘记,在 Windows 上,大多数文本文件使用
\r\n
作为换行符,而不是 \n
本身。 您根本没有检查 \r
。 您不想写出 \r
后跟符号,然后是 \n
。 所以你需要检测\r
并延迟直到符号被写入。