Use a variable as the name of a file in C

3

I'm using the system("pathping xxx.xxx.xxx > c:\i.txt") function to leave the program running pathping tests and saving the result to a file to analyze later.

Basically I wanted to play this function inside an infinite loop to always be analyzing but could not find a way to instead of i.txt use the variable i .

#include <stdio.h>

main(){

   int i=0;

   while(i>=0){
      system("pathping xxx.xxx.xxx.xxx > i.txt");
      i++;
   }
   return 0;
}
    
asked by anonymous 08.12.2016 / 18:57

2 answers

3

You need to format the string to put the variable within it. You can even concatenate string , but it is gambiarra *.

I would not do an loop infinite, just a big one. It is not to have problems of performance or of memory, but there will be problems when passing of 2 billion and little and would have to treat this, there begins to complicate the algorithm, and if it is to complicate, nor is it to do any of this. >

If you need a larger number, use a long or long long instead of int , with your due limit .

#include <stdio.h>
#include <limits.h>

int main() {
    int i = 0;
    while (i < INT_MAX) {
        char buffer[100] = "";
        sprintf(buffer, "pathping xxx.xxx.xxx.xxx > %d.txt\n", i++);
        system(buffer);
    }
}

I made an ideology slightly modified because I am not allowed to run the system () '. And yes, it is dangerous. Also on the Coding Ground .

Maybe take some time ( sleep or timer ) between one step and another is a good idea.

    
08.12.2016 / 19:44
-3

Inner Loop you can put:

while(true){
    system("pathping xxx.xxx.xxx.xxx > i.txt");  
    i++;
} 
    
08.12.2016 / 19:04