【发布时间】:2016-12-01 14:09:02
【问题描述】:
我创建了一个函数,该函数将源文件的名称、目标文件的名称以及将复制到目标文件的源文件行的开始行和结束行作为参数,如下例所示.我要做的就是输入要复制到其他文本文件的行,如下例所示:
我向您展示的代码只是“读取”一个文本文件的内容并“写入”另一个文本文件。我想“写”用户给出的特定行,而不是整个文本文件
用户输入:
Source_file.txt //目标文件将从中读取的文件
destination_file.txt //程序写入的新文件
2 3 // 它将打印到目标文件的行数:2-3
Source_file.txt:
1
2
3
4
5
6
destination_file.txt
2
3
代码:
#include <stdio.h>
#include <stdlib.h>
void cp(char source_file[], char destination_file[], int lines_copy) {
char ch;
FILE *source, *destination;
source = fopen(source_file, "r");
if (source == NULL) {
printf("File name not found, make sure the source file exists and is ending at .txt\n");
exit(EXIT_FAILURE);
}
destination = fopen(destination_file, "w");
if (destination == NULL) {
fclose(source);
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while ((ch = fgetc(source)) != EOF)
fputc(ch, destination);
printf("Copied lines %d from %s to %s \n",
lines_copy, source_file, destination_file, ".txt");
fclose(source);
fclose(destination);
}
int main() {
char s[20];
char d[20];
int lines;
printf("-Enter the name of the source file ending in .txt\n"
"-Enter the name of the destination file ending in .txt\n"
"-Enter the number of lines you want to copy\n\n");
printf(">subcopy.o ");
gets(s);
printf("destination file-> ");
gets(d);
printf("Lines: ");
scanf("%d", &lines);
cp(s, d, lines);
return 0;
}
【问题讨论】:
-
您能描述一下您遇到的问题吗?
-
我正在尝试评估 Linux cp 命令。该程序接受 3 个输入:1)我们将读取的文件 2)我们将写入的文件(源文件中的内容)3)我们想要从源文件复制到目标文件的行
-
您所显示的代码有什么问题?你有构建错误吗?您是否遇到运行时错误或崩溃?出乎意料的结果? 您的问题是什么?请read about how to ask good questions。
-
好的。该程序运行良好,它从一个文件中读取并创建整个内容。我要做的就是接受用户的行,例如 3 5。这意味着它将把源文件中的第 3 行到第 5 行写入目标文件。
-
` char ch; ... while( ( ch = fgetc(source) ) != EOF )` 不起作用。
fgetc()返回int,而不是char,因为EOF不能表示为char而要从文本文件中读取行,请参阅 thegetline()function.