Using a variable as a C file name

Asked

Viewed 91 times

3

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

Basically wanted to play this role within a loop infinity to always be analyzing but I could not find a way to in place 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;
}

2 answers

3


You need format the string to put the value of the variable inside it. You can even concatenate string, but it’s a scam*.

I wouldn’t make a loop infinite, just a big one. It’s not to have performance or memory problems, but there will be problems when it goes over 2 billion and little and would have to treat that, then it starts to complicate the algorithm, and if it’s to complicate, it’s not to do any of this.

If you need a bigger number, use a longor long long in place of int, with its 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 a ideone slightly modified because I am not allowed to run the system()`. And yes, it is dangerous. And put on the repl it.. Also put on the Github for future reference.

Maybe take a break (Sleep or timer) between one step and another is a good idea.

  • Exactly what I was looking for! Thank you! Although it is an infinite loop I believe it will not reach the billions but vlw by tip!

-3

Endless loop you can put:

while(true){
    system("pathping xxx.xxx.xxx.xxx > i.txt");  
    i++;
} 
  • Note: I am not responsible for possible performance and memory problems.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.