c - 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;
}
解决方案
有多个问题:
- 如果无法打开文件,则不要退出程序
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;
}
推荐阅读
- css - Css 网格 - html 表单 - 我无法在垂直流中引导我的元素
- sql - 更新 SQL 查询本身死锁
- java - 如何为 TableView 创建条件 CellValueFactory?
- vim - 如何映射键“;” 在尼奥维姆
- php - 返回或回显视图有什么区别?返回视图说话的时间比回声视图长
- android - 检查权限的自定义方法
- angular - 传单 Property-Routing-does-not-exist-on-type-typeof-import
- kubernetes-helm - 从 helm 命令行设置嵌套数据结构?
- javascript - 在 JavaScript 或 C# 中删除或 \r
- ruby-on-rails - form_with 没有命中控制器的动作