2011-10-18 15 views
0

これは私の教授が自分の言葉で私に提供したものです。テキストファイルの内容をコピーして別のファイルにコピー

"ユーザーが指定したテキストファイルの内容をコピーし、別のテキストファイル" 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; 
} 

私は、ファイルの書き込みが正しく行わ取得するように見えることはできませんか?あなたは助けてもらえますか?

+1

file = fopen(file2name、 "r")はwrite = fopen(file2name、 "w")にしないでください。 – DeCaf

+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ポインタファイルを使用して、送信元ファイルと送信先ファイルの両方を開きます。
  2. 読み込みモードで読み込み先ファイルを開くときは、書き込みモードで開く必要があります。
関連する問題