2015-11-09 36 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