这就是我的教授用他自己的话语提供给我的。
“编写一个程序,复制用户指定的文本文件的内容,并将其复制到另一个文本文件”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;
}
我似乎无法正确地完成文件编写?你能帮忙吗?
答案 0 :(得分:1)
你有堆栈器提到的复制和粘贴问题。而且无需添加额外的换行符。请尝试以下代码。
#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;
}
答案 1 :(得分:1)
如果这是您执行的代码,那么它就会出现问题。
FILE
指针文件打开源文件和目标文件。