【发布时间】:2016-12-01 10:05:49
【问题描述】:
我有下面的程序,它将一个的整个文本文件复制到另一个您输入源文件和目标文件的名称的地方。我需要修改我的程序来评估 Linux cp 命令。
我的subcopy 命令会将源文件的名称、目标文件的名称以及开始行和结束行 将复制到目标文件的源文件行,如下例所示:
subcopy.o Sourcefile.txt 目标文件.txt 100 200
从 Sourcefile.txt 复制第 100 - 200 行到destinationfile.txt
已编辑:我已经完成了所有艰苦的工作。剩下的就是选择我想从一个文件复制到另一个文件的行数。请注意该示例的工作原理。
#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复制文件命令”
-
好吧也许我错了,我把标题改成了复制命令
-
感谢编辑@Am_I_Helpful
-
你为什么打电话给
access()?充其量是没用的,最坏的情况是这样的做法导致a time-of-check/time-of-use (TOCTOU) bug. -
也许你需要这样做并修改你想要复制的行:programmingsimplified.com/c-program-copy-file