首页 > 解决方案 > C中的文件,不能将元素从一个文件复制到另一个文件

问题描述

如果该行是奇数,我正在尝试将元素从一个文件复制到另一个文件;例如我在第一个文件中:

6
5 6 8
3
6 9 32

输出应该是

5 6 8
6 9 32

但我什么也没得到。

这是我的代码:

int main() {
    FILE *data_input = fopen("data.in", "r");
    FILE *data_out = fopen("data.out", "w");
    char str;
    int nr = 0;

    if (data_input == NULL || data_out == NULL)
        printf("error");

    while ((str = fgetc(data_input)) != EOF) {
        str = fgetc(data_input);

        if (str == "\n")
            nr++;

        if (nr % 2 != 0)
            fputc(str, data_out);
    }

    fclose(data_input);
    fclose(data_out);

    return 0;
}

标签: cfile

解决方案


有多个问题:

  • 如果无法打开文件,则不要退出程序
  • fgets()你在循环中有一个冗余
  • fgetc()返回一个int,不要使用char变量来存储它并测试EOF
  • 命名一个字节str非常混乱
  • 您应该在测试行尾之前测试并输出字节:尾随换行符是行的一部分。
  • 行号通常从 1 开始。第一行的数字 1 是奇数。从您的预期输出中,您需要具有偶数行号的行。

这是修改后的版本:

#include <stdio.h>

int main() {
    FILE *data_input = fopen("data.in", "r");
    FILE *data_out = fopen("data.out", "w");
    int c;
    int lineno = 1;  // the first line is line 1

    if (data_input == NULL || data_out == NULL) {
        printf("error opening files\n");
        return 1;
    }

    while ((c = fgetc(data_input)) != EOF) {
        if (lineno % 2 == 0)  // output lines with an even line number
            fputc(c, data_out);
        if (c == "\n")        // update the line number after the newline
            lineno++;
    }

    fclose(data_input);
    fclose(data_out);

    return 0;
}

推荐阅读