-2

I want to make a C program which will be called with some parameters; Each parameter will represent a filename and I want to write some stuffs in each of them.

FILE * h0;    
h0 = fopen(argv[0],"w");    
char buffer[100] = "something here\n";    
fprintf(h0,buffer);    
fclose(h0);

For C++ there is something called c_str() but I didn't manage to use it here. Any tips how to handle it?

Sufian Latif
  • 13,086
  • 3
  • 33
  • 70

2 Answers2

1

A file name is exactly a C string (null terminated array of char) and you've already answered your own question (you don't need anything like c_str in C), since you open the file and you write in it. The argc tells you how many arguments there are in the command line, the name of the program inclusive and it is at argv[0]. So you need a loop, like

const char *your_stuff = "something here\n";
for(i = 1; i < argc; i++)
{
   FILE *h = fopen(argv[i], "w");
   if (h) {
     fputs(your_stuff, h);
     fclose(h);
   }
}

or something like that.

ShinTakezou
  • 9,432
  • 1
  • 29
  • 39
1

You should look at how the command line arguments are formed:

http://crasseux.com/books/ctutorial/argc-and-argv.html

Then have a look at your argv[0].

Ben Ruijl
  • 4,973
  • 3
  • 31
  • 44