2011-03-30 58 views
1

下面是我的代碼,將由每個線程調用以將ping命令的輸出寫入文本文件。該文件已正確創建,但沒有任何內容。現在我沒有創建任何線程,只是這樣調用該函數從主:將ping命令的輸出寫入c中的文本文件的問題?

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"); 
} 

OUTPUT:


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'管道結果從平直接回父? – 2011-03-30 23:42:03

回答

1

要寫入文件,您必須使用fprintf而不是printfsprintf


不要在代碼中使用FILE*操作。輸出會自動重定向到正確的文件,如果您嘗試同時使用程序內部的文件,則會發生不好的事情。

只是簡單地system("cmd >> file")和「cmd」的輸出將在文件中結束。

+0

但我有我的命令設置是這樣的:ping -n 2 >> filename.txt,而我雖然>>會照顧寫入文本文件。糾正我,如果我錯了。 – infinitloop 2011-03-30 23:07:18

+0

sprintf寫入一個字符串,多數民衆贊成我如何彌補我的文件名 – infinitloop 2011-03-30 23:09:03

+0

啊!我沒有足夠的研究你的代碼。回答編輯 – pmg 2011-03-30 23:11:44

0

你爲什麼要在這個程序運行ping命令

之前打開文件我懷疑ping失敗寫入文件,但你不要看到stderr輸出。

運行命令然後打開讀取模式文件

相關問題