我是 C 新手,我正在尝试从文本文件中删除一行,我的代码删除了指定的行,但在末尾留下了一个特殊的 �
字符,我不知道为什么或如何解决它。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void removeBook(int line) {
FILE *file = fopen("bookrecord.csv", "r");
int currentline = 1;
char character;
FILE *tempfile = fopen("temp.csv", "w");
while(character != EOF) {
character = getc(file);
printf("%c", character);
if (character == '\n') {
currentline++;
}
if (currentline != line) {
putc(character, tempfile);
}
}
fclose(file);
fclose(tempfile);
remove("bookrecord.csv");
rename("temp.csv", "bookrecord.csv");
}
void main() {
removeBook(2);
}
在我的文本文件中,Test1
和 Test2
位于不同的行,Test1
位于第 1 行,Test2
> 第 2 行。运行该函数时,它会删除第 2 行 (Test2
),但在其位置保留特殊的 �
字符。为什么?
最佳答案
代码中存在问题:
character
必须定义为int
来处理所有字节值以及getc()< 返回的特殊值
。EOF
/- 您不测试文件是否已成功打开。
字符
在第一次测试中未初始化,行为未定义。- 即使在文件末尾,您也始终输出读取的
字符
,因此您在输出文件末尾存储一个'\377'
字节值,显示在您的系统上为�
,在某些其他系统上为ÿ
。 - 您应该在输出换行符之后增加行号,因为它是当前行的一部分。
main
的原型(prototype)是int main()
,而不是void main()
。
这是更正后的版本:
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int removeBook(int line) {
FILE *file, *tempfile;
int c, currentline;
file = fopen("bookrecord.csv", "r");
if (file == NULL) {
fprintf("cannot open input file bookrecord.csv: %s\n", strerror(errno));
return 1;
}
tempfile = fopen("temp.csv", "w");
if (tempfile == NULL) {
fprintf("cannot open temporary file temp.csv: %s\n", strerror(errno));
fclose(tempfile);
return 1;
}
currentline = 1;
while ((c = getc(file)) != EOF) {
if (currentline != line) {
putc(c, tempfile);
}
if (c == '\n') {
currentline++;
}
}
fclose(file);
fclose(tempfile);
if (remove("bookrecord.csv")) {
fprintf("cannot remove input file bookrecord.csv: %s\n", strerror(errno));
return 1;
}
if (rename("temp.csv", "bookrecord.csv")) {
fprintf("cannot rename temporary file temp.csv: %s\n", strerror(errno));
return 1;
}
return 0;
}
int main() {
return removeBook(2);
}
关于c - 删除行时文本文件中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55666495/