2011-10-18 131 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」)be 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. 您正在以讀模式打開目標文件,它應該以寫模式打開。
相關問題