2011-10-18 2 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. 대상 파일을 읽기 모드로 열려고하면 쓰기 모드로 열어야합니다.
관련 문제