这是我的教授用他自己的话说给我的。
“编写一个程序,复制用户指定的文本文件的内容,并将其复制到另一个文本文件“copy.txt”。文件中的任何行不应超过 256 个字符。”
这是我迄今为止根据他的信息设计的代码:
#include <stdio.h>
#include <io.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
int main ( void )
{
char filename[256]=""; //Storing File Path/Name of Image to Display
static const char file2name[] = "C:\\Users\\Rael Jason\\Desktop\\Rael's iPod\\Codeblocks\\copy.txt";
FILE *file;
FILE *write;
printf("Please enter the full path of the text file you want to copy text: ");
scanf("%s",&filename);
file = fopen ( filename, "r" );
file = fopen (file2name, "r" );
if ( file != NULL )
{
char line [ 256 ]; /* or other suitable maximum line size */
char linec [256]; // copy of line
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
fputs ( line, stdout ); /* write the line */
strcpy(linec, line);
fprintf (write , linec);
fprintf (write , "\n");
}
fclose (write);
fclose ( file );
}
else
{
perror ( filename ); /* why didn't the file open? */
}
return 0;
}
我似乎无法正确完成文件写入?你能帮忙吗?
最佳答案
您遇到了 stacker 提到的复制和粘贴问题。并且不需要添加额外的换行符。尝试以下代码。
#include <stdio.h>
#include <io.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
int main ( void )
{
char filename[256]=""; //Storing File Path/Name of Image to Display
static const char file2name[] = "C:\\Users\\Rael Jason\\Desktop\\Rael's iPod\\Codeblocks\\copy.txt"; Copy File
FILE *file;
FILE *write;
char line [ 256 ]; /* or other suitable maximum line size */
char linec [256]; // copy of line
printf("Please enter the full path of the text file you want to copy text: ");
scanf("%s",&filename); // Enter source file
file = fopen ( filename, "r" );
write = fopen (file2name, "w" );
if ( file != NULL )
{
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
fputs ( line, stdout ); /* write the line */
strcpy(linec, line);
fprintf (write , linec);
// fprintf (write , "\n"); // No need to give \n
}
fclose (write);
fclose ( file );
}
else
{
perror ( filename ); /* why didn't the file open? */
}
return 0;
}
关于复制文本文件的内容并将其复制到另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7804097/