2015-11-09 41 views
-1

这是一个简单的程序,应该将一个 文件的内容复制到一个文件here中。我创建copyme通过下面的命令中有少量文字:我的复制文件功能没有按预期工作

touch copyme.txt 
open copyme.txt 

然后我输入文字,并保存 touch copyme.txt命令文件。

然后我编译的程序:

// Program to copy one file ot another 

#include <stdio.h> 

int main (void) 
{ 
    char in_name[64], out_name[64]; 
    FILE *in, *out; 
    int c; 

    // get file names from user 

    printf("Enter name of file to be copied: "); 
    scanf("%63s", in_name); 

    printf("Entere name of output file: "); 
    scanf("%63s", out_name); 

    // open input and output files 

    if ((in = fopen(in_name, "r")) == NULL) 
    { 
     printf("Can't open %s for reading.\n", in_name); 
     return 1; 
    } 

    if ((out = fopen(out_name, "w")) == NULL) 
    { 
     printf("Can't open %s for writing.\n", out_name); 
     return 2; 
    } 

    while ((c = getc(in)) != EOF) 
     putc(c, out); 

    // Close open files 

    fclose (in); 
    fclose (out); 

    printf("File has been copied\n"); 

    return 0; 
} 

而在终端运行它。 这里是输出:

Enter name of file to be copied: copyme 
Entere name of output file: here 
Can't open copyme for reading. 

编译器无法识别copyme文件,虽然它是 的文件夹中实际存在(我看到它,我打开它,我读 它)。 我会很感激的帮助。我对这件事很陌生。 谢谢!

+0

看起来好像你没有权利访问此文件 – LBes

+0

查看fopen的'man'页面以获取错误 – KevinDTimm

+7

您创建了一个名为copyme.txt的文件,然后键入copyme作为文件名! – pm100

回答

2

变化

if ((in = fopen(in_name, "r")) == NULL) 
    { 
     printf("Can't open %s for reading.\n", in_name); 
     return 1; 
    } 

#include <errno.h> 
    if ((in = fopen(in_name, "r")) == NULL) 
    { 

     perror("Can't open file for reading.\n"); 
     return 1; 
    } 

你会得到一个人类可读的消息,告诉您为什么它不能读取的文件

+1

我不认为这提供了一个问题的答案。 – Haris

+0

它是非常有用的建议和太长的时间来发表评论 – pm100

+2

这是非常有用的,和一个非常好的评论。但这只是不适合作为答案。我知道这对评论会有点大。可能是一个例子的链接本来就不错。 – Haris