2011-03-30 3 views
1

다음은 각 스레드가 ping 명령의 출력을 텍스트 파일에 기록하기 위해 호출 할 코드입니다. 파일이 제대로 작성되었지만 파일이 없습니다. 지금 내가 어떤 스레드를 생성하지 않았고, 단지 주에서이 같은 함수를 호출 :c의 텍스트 파일에 ping 명령의 출력을 쓰는 데 문제가 있습니까?

customPing("www.google.com", 10, 2, 1); 


void customPing(char *url, int test_interval,int samplesPerTest, int testDuration) 
{ 
    printf("-->%s %d(sec) %d %d(hrs)\n", url, test_interval, samplesPerTest, testDuration); 

    int durationInProgress = 0, 
     durationInSeconds = testDuration * 10, 
     n = samplesPerTest; 

    char pingCmd[80]; 
    char filename[10]; 

    FILE *fptr; 

    sprintf(filename, "pingResult%d.txt", fileCounter++); 
    fptr = fopen(filename, "a"); 

    sprintf(pingCmd, "ping -n %d %s >> %s ", n, url,filename); 

    printf("ping command: %s\n", pingCmd); 

    while (durationInProgress <= durationInSeconds) 
    { 
     system(pingCmd); 

     durationInProgress += test_interval; 

     printf("Going to sleep...\n"); 
     fclose(fptr); 
     Sleep(test_interval); 
     fptr = fopen(filename, "a"); 
    } 

    printf("***Done***\n"); 
} 

출력 : 내가 잘못하고있는 무슨에


1. Enter url: www.google.ca 

2. Enter Testing-Interval(10 sec, 20 sec, etc): 10 

3. Test Samples per test (10, 100 etc): 2 

4. Start test (yes/no): yes 

4. Test Duration (1 hr, 24 hrs, etc) 1 
     ***Test Starting*** 
-->www.google.com 10(sec) 2 1(hrs) 
ping command: ping -n 2 www.google.com >> pingResult0.txt 
The process cannot access the file because it is being used by another process. 
Going to sleep... 
The process cannot access the file because it is being used by another process. 
Going to sleep... 
***Done*** 
Press any key to continue . . . 

어떤 아이디어? ? Visual Studio 2008, Win Vista를 사용 중입니다. (도움이되는 경우) 감사합니다.

+0

, 왜 그냥 직접 다시 부모 핑에서 파이프'popen'에게 결과를 사용하지 읽기 모드로 파일을 열고 다음 명령을 실행? –

답변

1

파일에 쓰려면 printf 또는 sprintf이 아닌 fprintf을 사용해야합니다!


코드에서 FILE* 작업을 사용하지 마십시오. 출력은 자동으로 올바른 파일로 리다이렉트되며, 동시에 프로그램 내부에서 파일을 사용하려고하면 나쁜 일이 일어납니다.

단순히 system("cmd >> file")이고 "cmd"의 출력은 파일에서 끝납니다.

+0

하지만 다음과 같은 명령어 설정이 있습니다 : ping -n 2 >> filename.txt, 그리고 >>는 텍스트 파일에 쓰는 것을 처리합니다. 내가 틀렸다면 나를 바로 잡아라. – infinitloop

+0

sprintf가 문자열에 씁니다. 내 파일 이름을 어떻게 구성합니까? – infinitloop

+0

아! 나는 당신의 코드를 충분히 연구하지 않았다. 답변 됨 – pmg

0

은 왜 내가 핑 (ping)가 파일에의 기입 해에 실패 의심 ping 명령

을 실행하기 전에이 프로그램에서 파일을 여는하지만 당신은 표준 에러 출력을 볼니까.

대신 다음 파일로 핑 (ping)의 출력을 지시 파일을 읽을

관련 문제