2015-01-26 4 views
0

내 수업을위한 프로그램으로 며칠 동안 꾸며졌고 fwrite를 협력 할 수 없습니다. 나는 fread와 fwrite를위한 온라인 리소스를 살펴 보았고, 교수의 예를 살펴 보았고,이 문제를 해결하기 위해 다시 시도했지만, 아무 것도 효과가 없었다. 필자가 무엇을 하든지, fwrite는 텍스트 편집기가 문자 인코딩을 감지 할 수 없도록 만듭니다. 따라서 fwrite가 파일에 메모리 주소 나 쓰레기 값을 쓰고 있다고 가정합니다. 그것을 읽지 마라. 이 프로그램은 한 파일의 내용을 다른 파일에 쓴다고 가정합니다.fwrite가 내 텍스트 파일을 손상시킵니다.

여기 내 코드입니다.

#include <unistd.h> 
#include <stdio.h> 
#include <stdlib.h> 

int main(int argc, char* argv[]) { 
//initialize files 
FILE* infile, *outfile; 
char* buffer; 
int read = 0; 

//handle the case of having the wrong number of inputs. 
if (argc != 4){ 

    printf("Error: incorrect number of inputs\n"); 
    //returning 1 will tell us that this was an error (as opposed to returning zero) 
    return 1; 
} 
else{ 
    //handle the case of not having read acces to file 1 
    if (access(argv[1], R_OK) == 1){ 

     printf("Error: you do not have read access to the first file\n"); 
     return 1; 
    } 
    else { 
     //handle the case of not having write access to file 2 
     if (access(argv[2], W_OK) == 1){ 
      printf("Error: you do not have write access to the second file\n"); 
      return 1; 
     } 
     else{ 
      //handle a bad buffer size (zero or negative number) 
      if ((int)*argv[3] < 0){ 
       printf("Error: bad input for buffer size.\nBuffer size: %d \n", (int)*argv[3]); 
       return 1; 
      } 
     } 
    } 
    //open the files in the correct mode. 
    infile = fopen(argv[1], "r"); 
    outfile = fopen(argv[2], "w"); 


    buffer = malloc((int)*argv[3]); 

    while (!feof(infile)){ 
     read = fread (buffer,1,(int)*argv[3],infile); 
     fwrite(buffer,1,(int)*argv[3],outfile); 
    } 

} 
//close files, and deallocate the buffer. 
fclose(infile); 
fclose(outfile); 
free(buffer); 
//if we made it here, then that means that our program ran correctly, so return zero. 
return 0; 
} 
+2

에 당신은'그냥 캐스트 int', 당신이 [ASCII 표]를 체크 아웃 할 수 있습니다 (HTTP에'char'을 변환하지 않습니다 //www.asciitable를 .com /) 당신이 무엇을 얻는 지 알아 내기 위해 문자 ''9 ''(힌트 : 정수 값 '9'가 아님) –

답변

2

atoi(argv[3]) 

에 잘못된

(int)*argv[3] 

변화를이며,

같은 것을 어딘가에 값을 저장하고,이 정수로 변환 있다고 확인하면 더 나은 것
int size; 
char *endptr; 

size = strtol(argv[3], &endptr, 10); 
if (*endptr != '\0') 
    errorNotAnIntegerAbortHere(); 
buffer = malloc(size); 
. 
. 
. 

아니요 *argv[3]argv[3]의 첫 번째 문자 인 argv[3][0]과 같습니다.

+0

고마워요! 이 모든 것이 수정되었습니다. –

1

fread는 no보다 작습니다. EOF에서 요청 된 바이트 수.

변경

if (read) 
    fwrite(buffer,1,read,outfile); 
+0

'fread()'는 코드에서 일반적인 오류입니다. OP는 3 개의 명령 행 인자를 처리하고'int'로 변환해야합니다.'fwrite' 전에'fread()'를보십시오. –

관련 문제