c - 删除行时文本文件中的特殊字符

标签 c

我是 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);
}

在我的文本文件中,Test1Test2 位于不同的行,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/

相关文章:

c++ - musl 的 GCC 包装器与 musl 的交叉编译器有何不同?

c++ - 模式匹配算法

c - c 中的数独代码检查器

c - 尝试打印一个简单的字符串: [Warning] conflicting types for 'rawrprint' [enabled by default]

python - 将 C 数据结构和 C API 导出到 Python

c - 什么是连续内存块?

c - 指针被释放但 valgrind 说它不是

c - 如何检查结构是否已初始化

c - Os Dev 的 PCI IDE 教程中的函数 insl 是做什么的?

c - 使用 Node.js ffi 模块分配无符号字符的缓冲区