将ping命令的输出写入c中的文本文件的问题?

时间:2011-03-30 23:01:32

标签: c multithreading file-io accessibility ping

下面是我的代码,每个线程都会调用该代码,以便将ping命令的输出写入文本文件。文件已正确创建,但其中没有任何内容。现在我没有创建任何线程,只是从main调用这个函数:

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。(如果有帮助的话) 谢谢。

2 个答案:

答案 0 :(得分:1)

要写入文件,您必须使用fprintf,而不是printfsprintf


不要在代码中使用FILE*操作。输出会自动重定向到正确的文件,如果您尝试同时使用程序内部的文件,则会发生错误。

只需system("cmd >> file"),“cmd”的输出就会以文件结尾。

答案 1 :(得分:0)

为什么在运行ping命令之前打开此程序中​​的文件

我怀疑ping无法写入文件,但你没有看到stderr输出。

运行命令,然后以读取模式打开文件