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

问题描述 投票:0回答:1

我是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,在第1行有Test1,在第2行有Test2。当函数运行时它删除第2行(Test2)但在其位置留下特殊的字符。为什么?

c
1个回答
0
投票

代码中存在问题:

  • 必须将character定义为int来处理所有字节值和EOF返回的特殊值getc()
  • 你不测试文件是否成功打开。
  • character在第一次测试中未初始化,行为未定义。
  • 您始终输出character读取,即使在文件末尾,因此您将'\377'字节值存储在输出文件的末尾,在系统上显示为,在某些其他系统上显示为ÿ
  • 您应该在输出换行符后增加行号,因为它是当前行的一部分。
  • main的原型是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);
}
© www.soinside.com 2019 - 2024. All rights reserved.