2014-03-26 2 views
0

현재 작업 디렉토리에서 파일을 제거하려고합니다. 파일을 찾을 수 없을 때 "잘못된 파일"을 인쇄하려고하면 세그먼트 오류가 발생합니다. 이 스 니펫은 더 큰 프로그램의 일부입니다.현재 디렉토리에서 파일 제거

코드 :

printf("\nEnter your current password:\t"); 
scanf("%s",temp2); 
comp2 = strcmp(password,temp2); 
file = (char*)malloc(100 * sizeof(char)); 
if(comp2 == 0) 
{ 
    int value; 
    printf("\nEnter the file name:\t"); 
    scanf("%s",file); 
    sprintf(cmd,"rm -i %s",file); 
    value=system(cmd); 
    if(value == -1) 
     printf("\nFile not Found. Exiting Program"); 
} 
else 
    printf("\nThe password is incorrect. Please try again."); 
break; 

어떤 도움을 주 시겠어요? 미리 감사드립니다.

+1

'cmd '는 어디에 할당 되었습니까? 또한,'rm -i'는 대화 형 명령이지만 대화 형 프로세스가 아닙니다. 또한 C는'unlink' 호출을하므로'system'을 사용할 필요가 없습니다 ... – Joe

+2

[remove] (http://pubs.opengroup.org/onlinepubs/009695299/functions/remove.html) 사용 방법은 어떻습니까?) ([주의 사항] (https://www.securecoding.cert.org/confluence/display/seccode/FIO08-C.+Take+care+when+calling+remove%28%29+on+an+open+file))) 또는 [링크 해제] (http://pubs.opengroup.org/onlinepubs/009695299/functions/unlink.html)? – miku

+1

서브 프로세스에서'rm'을 실행하는 것은 C 프로그램에서 파일을 삭제하는 좋은 방법이 아닙니다. 그것은'rm'이 발견되지 않는 비정상적인'$ PATH'또는'rm'이 당신이 삭제하려고하는 파일을 오해하게하는 파일명의 공백과 같은 모든 잠재적 문제에 개방적입니다. 'unlink'와 같은 시스템 호출을 사용하여 * 자신의 * 프로그램이 파일을 삭제하기 위해 * 다른 * 프로그램을 실행하는 대신 파일을 삭제하도록하십시오. – Wyzard

답변

1

당신은 제거 기능을

remove(file_name); 
1

를 사용하여 제거 (경로)를 사용할 수 있습니다 - 그것은 파일이나 디렉토리를 제거합니다.

관련 문제