3

I want to use some printf to print to a file.

I can use

for{i in set1}  printf '%10.5f\n',var1[i] >> ('a' & 'very' & 'long' & 'string' & 123 & sprintf('%5d', foo));
for{i in set2}  printf '%10.5f\n',var2[i] >> ('a' & 'very' & 'long' & 'string' & 123 & sprintf('%5d', foo));
for{i in set3}  printf '%10.5f\n',var3[i] >> ('a' & 'very' & 'long' & 'string' & 123 & sprintf('%5d', foo));

But I don't want to repeat the file each time.

It seems option log_file should do the trick, but doesn't work for me: the file is created but empty, and the output is printed in the console.

Compass
  • 5,867
  • 4
  • 30
  • 42
Oriol
  • 274,082
  • 63
  • 437
  • 513

2 Answers2

2

I have discovered that I must change option log_file after printing, because it seems that AMPL doesn't close the file, even if I use close.

Then, the following works:

print "Hello, ";              # Printed to the console
option log_file "test.txt";
print "World";                # Printed to the console and file
option log_file ""; 
close;
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • Well, on my machine, it works just fine without the `close;`. – Ali Dec 14 '13 at 22:32
  • @Ali I use windows XP and without `option log_file ""; close;` the produced file is empty and I can't rename or delete it because it's in use by ampl.exe. Which OS do you use? – Oriol Dec 14 '13 at 22:36
  • Ahh, interesting. I am on Linux. But it's probably not the OS. Could you try running the `ampl.exe your_model.mod` in the command line? In this way ampl.exe exits after running the model and the log file cannot be used by ampl.exe anymore. – Ali Dec 14 '13 at 23:08
  • @Ali I have tried the console (I was using amplide) and the file is not printed until I use `exit;`, and then `ampl: exit;` appears at the end of the logfile. – Oriol Dec 14 '13 at 23:17
  • It is either an AMPL quirk or a Windows bug. If the `close;` command solves it for you then I say there is no point in investigating it any further. – Ali Dec 14 '13 at 23:23
2

To avoid repeating the file name, store it in a parameter:

param out symbolic =
  'a' & 'very' & 'long' & 'string' & 123 & sprintf('%5d', foo);
for{i in set1} printf '%10.5f\n',var1[i] >> (out);
for{i in set2} printf '%10.5f\n',var2[i] >> (out);
for{i in set3} printf '%10.5f\n',var3[i] >> (out);

Note that the parentheses around out are important, because they allow passing an expression (a parameter reference in this case) rather than verbatim text as a file name.

vitaut
  • 49,672
  • 25
  • 199
  • 336
  • Thanks, I tried something like that but AMPL tried to convert the string to a number and threw errors. – Oriol Dec 15 '13 at 17:10