Below is my code that will be called by each thread in order to write the output of ping command to a text file. The file is created properly but there is nothing in it. For now i did not create any threads and just called the function like this from 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");
}
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 . . .
Any ideas on what am i doing wrong???
I am using Visual Studio 2008, Win vista.(if that helps)
Thank you.
To write to the file you must usefprintf, notprintforsprintf!Don’t use
FILE*operations in your code. The output is automatically redirected to the correct file, and if you try to use the file from inside the program at the same time, bad things happen.Just simply
system("cmd >> file")and the output of “cmd” will end up in the file.